安装Graphviz时出现“no module named graphviz”错误提示

8
我一直在尝试安装Graphviz,并连接Python来绘制决策树的节点。我读了很多与我遇到相同问题的帖子,尽管我已经尝试了很多解决方案,但我仍然无法运行我的决策树:(
我不是一个程序员,我只是一名简单的经济学家,正在尝试学习机器学习模型,所以对我来说,阅读其他帖子中提供的解决方案很困难。
我已经可以通过cmd使用conda install -c anaconda graphvizconda install -c anaconda pydot 安装Graphviz(我还从GraphViz页面下载了rar包)。
然后我尝试import graphviz,但是Python显示以下错误 No module named 'graphviz'
因此,我尝试添加到环境变量中的新路径为 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它找不到它。很抱歉我的英语不好:(我正在学习:)。

1
这意味着Graphviz未按预期安装。可能您正在执行Python脚本的环境与conda安装Graphviz的环境不同。在Anaconda文档中有关于此主题的指南。https://conda.io/docs/user-guide/troubleshooting.html#conda-reports-that-a-package-is-installed-but-it-appears-not-to-be - Håken Lid
4个回答

10

现在Anaconda.org上有一个名为python-graphviz的包,其中包含了graphviz工具的Python接口。只需执行以下安装命令即可:

conda install python-graphviz

查看这里获取更多信息。


这个"conda install python-graphviz"在我的Mac-Intel上,在VSCode中,使用Anaconda Navigator,非常有效,谢谢。 - Mahfuz

3

以下命令适用于 Windows 10 版本,Anaconda 版本为 4.8.3:

conda install -c anaconda python-graphviz

1

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接