我一直在尝试安装 graphviz 并与 python 连接以绘制决策树的一些节点。我已经阅读了很多与我有相同问题的线程,但我执行了很多解决方案,但我仍然无法执行我的决策树:(
我不是程序员,我只是一个正在尝试学习机器学习模型的简单经济学家,所以对我来说很难阅读其他线程中提供的大部分解决方案。
我已经可以 conda install -c anaconda graphviz
在我的 cmd 和 conda install -c anaconda pydot
安装完成。 (我也是从GraphViz页面下载的rar包)
然后我尝试导入 graphviz,但 python 显示以下错误 No module named 'graphviz'
。
因此,我尝试使用以下 cd C:\Program Files (x86)\Graphviz2.38\bin
但我仍然遇到同样的问题。
我试图在我的 spyder 代码中运行以下脚本,但没有成功
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pydot
from IPython.display import Image, display
# import graphviz as gv
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.externals.six import StringIO
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier,
export_graphviz
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier,
BaggingRegressor, RandomForestRegressor, GradientBoostingRegressor
from sklearn.metrics import mean_squared_error,confusion_matrix,
classification_report
# This function creates images of tree models using pydot
def print_tree(estimator, features, class_names=None, filled=True):
tree = estimator
names = features
color = filled
classn = class_names
dot_data = StringIO()
export_graphviz(estimator, out_file=dot_data, feature_names=features,
class_names=classn, filled=filled)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
return(graph)
hitter =
pd.read_csv('C:\\Users\\ldresl\\Documents\\Chapter8\\Hitters.csv',sep=';')
hitter = hitter.dropna()
#Llamo una nueva matriz
X = hitter[['Years','Hits']].as_matrix()
y = np.log(hitter.Salary.as_matrix())
#Se corre todo el codigo junto
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(11,4))
ax1.hist(hitter.Salary.as_matrix())
ax1.set_xlabel('Salary')
ax2.hist(y)
ax2.set_xlabel('Log(Salary)');
# Corro la regresion de la decision tree (NOTAR QUE NO ES RANDOM FOREST!!!)
regr = DecisionTreeRegressor(max_leaf_nodes=3)
regr.fit(X, y)
graph, = print_tree(regr, features=['Years', 'Hits'])
Image(graph.create_png())
但每当我尝试运行最后两行时,都会抛出以下错误 [WinError 2] "dot.exe" not found in path.
。另外,如果我写 import graphviz as gv
找不到它。
对不起我的英语 :( 我正在学习 :)。
原文由 Lucas Dresl 发布,翻译遵循 CC BY-SA 4.0 许可协议
现在 Anaconda.org 上有一个 python-graphviz 包,其中包含 graphviz 工具的 Python 接口。只需安装它:
在 这里 查看更多信息。