决策树
from sklearn.feature_extraction import DictVectorizer
from sklearn import tree
from sklearn import preprocessing
import csv
import graphviz
# 读入数据
Dtree = open(r'AllElectronics.csv' ,'r')
reader = csv.reader(Dtree)
# 获取第一行数据
headers = next(reader)
print(headers)
# 定义两个列表
featureList = []
labelList = []
for row in reader:
# 把label存入list
labelList.append(row[-1])
rowDict = {}
for i in range(1 ,len(row)-1):
# 建立一个数据字典
rowDict[headers[i]] = row[i]
# 把数据字典存入list
featureList.append(rowDict)
print(featureList)
# 把数据转换成01表示
vec = DictVectorizer()
x_data = vec.fit_transform(featureList).toarray()
print('x_data:' + str(x_data))
# 打印属性名称
print(vec.get_feature_names())
# 打印标签
print('labelList:' + str(labelList))
# 把标签转换成01表示
lb = preprocessing.LabelBinarizer()
y_data = lb.fit_transform(labelList)
print('y_data:' + str(y_data))
# 创建决策树模型
model = tree.DecisionTreeClassifier(criterion='entropy')
# 输入数据建立模型
model.fit(x_data ,y_data)
# 测试
x_test = x_data[0]
print('x_text:' + str(x_test))
predict = model.predict(x_test.reshape(1 ,-1))
print('predict:' + str(predict))
dot_data = tree.export_graphviz(model,
out_file=None,
feature_names=vec.get_feature_names(),
filled=True,
rounded=True,
special_characters=True)
graph = graphviz.Source(dot_data)
graph.render('computer')
图片:决策树-cart算法
from sklearn import tree
import numpy as np
import graphviz
# 载入数据
data = np.genfromtxt('cart.csv' ,delimiter=',')
x_data = data[1:,1:-1]
y_data = data[1:,-1]
# 创建决策树模型
model = tree.DecisionTreeClassifier() #criterion默认为gini,即为CART算法
# 输入数据建立模型
model.fit(x_data ,y_data)
# 导出决策树
dot_data = tree.export_graphviz(model,
out_file=None,
feature_names=['house_yes', 'house_no', 'single', 'married', 'divorced', 'income'],
class_names=['no', 'yes'],
filled=True,
rounded=True,
special_characters=True)
graph = graphviz.Source(dot_data)
graph.render('cart')
图片:
决策树线性二分类
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import classification_report
from sklearn import tree
import graphviz
# 载入数据
data = np.genfromtxt('LR-testSet.csv' ,delimiter=',')
x_data = data[:,:-1]
y_data = data[:,-1]
plt.scatter(x_data[:,0] ,x_data[:,1],c = y_data)
plt.show()
# 创建决策树模型
model = tree.DecisionTreeClassifier()
# 输入数据建立模型
model.fit(x_data, y_data)
# 导出决策树
dot_data = tree.export_graphviz(model,
out_file=None,
feature_names=['x', 'y'],
class_names=['label0', 'label1'],
filled=True,
rounded=True,
special_characters=True)
graph = graphviz.Source(dot_data)
graph.render('binary')
# 获取数据值所在的范围
x_min ,x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min ,y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# 生成网格矩阵
xx ,yy = np.meshgrid(np.arange(x_min ,x_max ,0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])#ravel(),多维数据转一维
z = z.reshape(xx.shape)
# 等高线图
cs = plt.contourf(xx, yy ,z)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c = y_data)
plt.show()
predictions = model.predict(x_data)
print(classification_report(predictions, y_data))
图片:
决策树非线性二分类
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import classification_report
from sklearn import tree
from sklearn.model_selection import train_test_split
import graphviz
# 载入数据
data = np.genfromtxt("LR-testSet2.txt", delimiter=',')
x_data = data[:, :-1]
y_data = data[:, -1]
plt.scatter(x_data[:, 0], x_data[:, 1], c = y_data)
plt.show()
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data)# 分割数据0.2为测试数据,0.8为训练数据
# 创建决策树模型
# max_depth, 树的深度,可以通过改变树的深度来完成剪枝
# min_samples_split内部节点再划分所需最小样本数,也可以完成剪枝
model = tree.DecisionTreeClassifier()
# 输入数据建立模型
model.fit(x_train, y_train)
# 导入决策树
dot_data = tree.export_graphviz(model,
out_file=None,
feature_names=['x', 'y'],
class_names=['label0', 'label1'],
filled=True,
rounded=True,
special_characters=True)
graph = graphviz.Source(dot_data)
graph.render('nonlinearbinary')
# 获取数据值所在的范围
x_min ,x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min ,y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# 生成网格矩阵
xx ,yy = np.meshgrid(np.arange(x_min ,x_max ,0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])#ravel(),多维数据转一维
z = z.reshape(xx.shape)
# 等高线图
cs = plt.contourf(xx, yy ,z)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c = y_data)
plt.show()
predictions = model.predict(x_train)
print(classification_report(predictions, y_train))
图片:
Bagging
from sklearn import neighbors
from sklearn import datasets
from sklearn.ensemble import BaggingClassifier
from sklearn import tree
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
iris = datasets.load_iris()
x_data = iris.data[:,:2]
y_data = iris.target
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data)
knn = neighbors.KNeighborsClassifier()
knn.fit(x_train, y_train)
def plot(model):
# 获取数据值所在范围
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# 生成网络矩阵
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])
z = z.reshape(xx.shape)
# 等高线图
cs = plt.contourf(xx, yy, z)
# 画图
plot(knn)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[: ,1], c = y_data)
plt.show()
# 准确率
print(knn.score(x_test, y_test))
# 决策树
dtree = tree.DecisionTreeClassifier()
dtree.fit(x_train, y_train)
# 画图
plot(dtree)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[: ,1], c = y_data)
plt.show()
# 准确率
print(dtree.score(x_test, y_test))
# bagging
bagging_knn = BaggingClassifier(knn, n_estimators=100)
bagging_knn.fit(x_train, y_train)
plot(bagging_knn)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[: ,1], c = y_data)
plt.show()
# 准确率
print(bagging_knn.score(x_test, y_test))
bagging_tree = BaggingClassifier(dtree, n_estimators=100)
bagging_tree.fit(x_train, y_train)
plot(bagging_tree)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[: ,1], c = y_data)
plt.show()
# 准确率
print(bagging_tree.score(x_test, y_test))
图片:
随机森林
from sklearn import tree
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
# 载入数据
data = np.genfromtxt("LR-testSet2.txt", delimiter=',')
x_data = data[:, :-1]
y_data = data[:, -1]
plt.scatter(x_data[:, 0], x_data[:, 1], c = y_data)
plt.show()
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data)
def plot(model):
# 获取数据值所在范围
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# 生成网络矩阵
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])
z = z.reshape(xx.shape)
# 等高线图
cs = plt.contourf(xx, yy, z)
# 样本散点图
plt.scatter(x_test[:, 0], x_test[:, 1], c = y_test)
plt.show()
# 决策树
dtree = tree.DecisionTreeClassifier()
dtree.fit(x_train, y_train)
plot(dtree)
# 准确率
print(dtree.score(x_test, y_test))
RF = RandomForestClassifier(n_estimators=50)
RF.fit(x_train, y_train)
plot(RF)
print(RF.score(x_test, y_test))
图片:stacking
from sklearn import datasets
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from mlxtend.classifier import StackingClassifier
from sklearn.ensemble import VotingClassifier #投票的分类器
import numpy as np
# 载入数据集
iris = datasets.load_iris()
# 只要第1,2列的特征
x_data, y_data = iris.data[:, 1:3], iris.target
# 定义三个不同的分类器
clf1 = KNeighborsClassifier(n_neighbors=1)
clf2 = DecisionTreeClassifier()
clf3 = LogisticRegression()
# 定义一个次级分类器
lr = LogisticRegression()
sclf = StackingClassifier(classifiers=[clf1, clf2, clf3],
meta_classifier=lr)
for clf, label in zip([clf1, clf2, clf3, sclf],
['KNN', 'Decision Tree', 'LogisticRegression', 'StackingClassifier']):
scores = model_selection.cross_val_score(clf, x_data, y_data, cv=3, scoring='accuracy')
print("Accuracy: %0.2f [%s]" % (scores.mean(), label))
# VotingClassifier
sclf1 = VotingClassifier([('knn',clf1), ('dtree', clf2), ('rf', clf3)])
for clf, label in zip([clf1, clf2, clf3, sclf1],
['KNN', 'Decision Tree', 'LogisticRegression', 'VotingClassifier']):
scores = model_selection.cross_val_score(clf, x_data, y_data, cv=3, scoring='accuracy')
print("Accuracy: %0.2f [%s]" % (scores.mean(), label))
adaboost
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import classification_report
from sklearn import tree
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_gaussian_quantiles
# 生成二维正态分布,生成的数据按分位数分为两类,500个样本,2个样本特征
x1, y1 = make_gaussian_quantiles(n_samples=500, n_features=2, n_classes=2)
# 生成二维正态分布,生成的数据按分位数分为两类,500个样本,2个样本特征的均值都为3
x2, y2 = make_gaussian_quantiles(mean=(3, 3), n_samples=500, n_features=2, n_classes=2)
# 将两组数据合成一组数据
x_data = np.concatenate((x1, x2))
y_data = np.concatenate((y1, -y2+1))#稍微处理下y,没有特别的意义
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()
# 决策树模型
model = tree.DecisionTreeClassifier(max_depth=3)
# 输入数据建立模型
model.fit(x_data, y_data)
# 获取数据值所在范围
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# 生成网络矩阵
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])
z = z.reshape(xx.shape)
# 等高线图
cs = plt.contourf(xx, yy, z)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c = y_data)
plt.show()
# 准确率
print(model.score(x_data, y_data))
# adaboost模型
model = AdaBoostClassifier(DecisionTreeClassifier(max_depth=3), n_estimators=10)
# 训练模型
model.fit(x_data, y_data)
# 获取数据值所在范围
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# 生成网络矩阵
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])
z = z.reshape(xx.shape)
# 等高线图
cs = plt.contourf(xx, yy, z)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c = y_data)
plt.show()
# 准确率
print(model.score(x_data, y_data))
图片: