跟着教程写的代码,原版python2,所以还是出现不少问题,希望以后不要踩踩过的坑又来了。小李加油!
import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
test_idx = [0, 50, 100]
#training data
train_target = np.delete(iris.target, test_idx)
train_data = np.delete(iris.data, test_idx, axis=0)
#testing data
test_target = iris.target[test_idx]
test_data = iris.data[test_idx]
clf = tree.DecisionTreeClassifier()
clf.fit(train_data, train_target)
print (test_target)
print (clf.predict(test_data))
#viz code
from sklearn.externals.six import StringIO
import pydot
dot_data = StringIO()
tree.export_graphviz(clf,
out_file=dot_data,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True,
impurity=False)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph[0].write_pdf("iris.pdf")
1. debug网站
debug最好是在stackoverflow网站
stackoverflow:https://stackoverflow.com/questions/22324459/pygraphviz-valueerror-program-dot-not-found-in-path-python
2. 遇到的错误类型
##2.1 descriptor ‘init’ requires a ‘super’ object but received a ‘str’
原因:dot_data = StringIO未加上括号
改为:dot_data = StringIO()
##2.2 ‘list’ object has no attribute ‘write_pdf’
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph[0].write_pdf(“iris.pdf”)
参考:https://blog.csdn.net/petermsh/article/details/78515712
##2.3 dot not found in path (python)
1)If you have Anaconda installed the simplest way to go about this is run the following from CMD:
conda install graphviz
安装很慢,尝试安装brew:/usr/bin/ruby -e “$(curl -fsSL https://cdn.jsdelivr.net/gh/ineo6/homebrew-install/install)”
详见:https://zhuanlan.zhihu.com/p/90508170
brew install graphviz
2)you might also need the following:
conda install pydot-ng
参考:https://stackoverflow.com/questions/22324459/pygraphviz-valueerror-program-dot-not-found-in-path-python
鸢尾花不错的文章链接:
https://www.jianshu.com/p/52b86c774b0b