from sklearn.datasets import load_iris
from sklearn import tree
import pydotplus
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from numpy import *
iris=load_iris()
clf=tree.DecisionTreeClassifier()#决策树模型
clf=clf.fit(iris.data,iris.target)#训练模型
result=clf.predict(iris.data[:5,:])#预测类别
result_prob=clf.predict_proba(iris.data[:5,:])#预测类别对应的概率
print(result)
print(result_prob)
#输出决策树形式的dot文件
with open("iris.dot","w") as f:
f=tree.export_graphviz(clf,out_file=f)
输出结果:
[0 0 0 0 0]
[[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]]
……
#画决策树
dot_data=tree.export_graphviz(clf,out_file=None)
graph=pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("iris.pdf")
输出结果:
共有150个样本,分为3类,每类各有50个样本。根据X[3]是否小于0.8分为两块,若小于0.8,50个样本属于第1类;大于0.8,根据X[3]是否小于1.75继续分为两块,若小于1.75,49个样本属于第2类,5个样本属于第3类;大于1.75,1个样本属于第2类,45个样本属于第3类。以此类推,继续划分。
#导入文本文件数据
data=[]
label=[]
with open("1.txt") as f:
for line in f:
tokens=line.strip().split(' ')
data.append([float(i) for i in tokens[:-1]])#特征
label.append(tokens[-1])#类别
x=array(data)
labels=array(label)
#文本类别转换为数字类别
y=zeros(labels.shape)
y[labels=='fat']=1
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)#训练集,测试集
clf=tree.DecisionTreeClassifier(criterion='entropy')#决策树模型,信息熵作为划分标准
clf.fit(x_train,y_train)#训练模型
print("不同特征对分类的影响权重:",clf.feature_importances_)
answer=clf.predict(x_test)#预测
print("测试数据为:",x_test)
print("预测结果为:",answer)
print("真实类别为:",y_test)
print("准确率为:",mean(answer==y_test))
输出结果:
不同特征对分类的影响权重: [0.27501449 0.72498551]
测试数据为: [[ 1.6 40. ]
[ 1.9 70. ]]
预测结果为: [0. 0.]
真实类别为: [0. 0.]
准确率为: 1.0
#输出决策树形式的dot文件
with open("1.dot","w") as f:
f=tree.export_graphviz(clf,out_file=f)
输出结果:
#画决策树
dot_data=tree.export_graphviz(clf,out_file=None)
graph=pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("1.pdf")
输出结果:
#准确率与召回率
precision,recall,thresholds=precision_recall_curve(y_train,clf.predict(x_train))#准确度、召回率、阈值
answer=clf.predict(x)
print("y:",y)
print("answer:",answer)
print(classification_report(y,answer,target_names = ['thin', 'fat']))
输出结果: