运用python进行决策树分类预测。数据采用鸢尾花数据。(我也是python新手,将视频中的代码敲下来自练习消化。)
# -*- coding: utf-8 -*- import numpy as np import pandas as pd from sklearn.datasets import load_iris #导入鸢尾花数据 from sklearn import tree #导入机器学习决策树包 from sklearn.cross_validation import train_test_split def main(): iris = load_iris() print iris print len(iris["data"]) #数据长度 train_data,test_data,train_target,test_target = train_test_split(iris.data,iris.target,test_size=0.2,random_state=1) #建模 clf = tree.DecisionTreeClassifier(criterion="entropy") #分类器决策树 熵增益 clf.fit(train_data,train_target) #建立模型 y_pred = clf.predict(test_data) #测试集预测 #验证 from sklearn import metrics print metrics.accuracy_score(y_true = test_target,y_pred = y_pred) #真实值和预测值 给出预测精度 print metrics.confusion_matrix(y_true=test_target,y_pred = y_pred) #混淆矩阵 with open("./data/tree.dot","w") as fw: #将决策树输出值文件 tree.export_graphviz(clf,out_file=fw) if __name__ == "__main__": main()