【发布时间】:2018-10-10 17:23:06
【问题描述】:
我一直在尝试安装 graphviz 并与 python 连接以绘制决策树的一些节点。我已经阅读了很多与我有同样问题的线程,但我执行了很多解决方案,但我仍然无法执行我的决策树:(
我不是程序员,我只是一个简单的经济学家,正在尝试学习机器学习模型,所以对我来说很难阅读其他线程中提供的许多解决方案。
我已经可以在我的 cmd 和 conda install -c anaconda pydot 中使用 conda install -c anaconda graphviz 并完成安装。 (我也从 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 没有找到它。
对不起我的英语:(我正在学习:)。
【问题讨论】:
-
这意味着 graphviz 没有按预期安装。可能您在与 conda 安装 graphviz 的环境不同的环境中执行您的 python 脚本。 Anaconda 文档中有关于此主题的指南。 conda.io/docs/user-guide/…
标签: python python-3.x graphviz random-forest decision-tree