我正在尝试在 IPython 中运行这个机器学习树算法代码:
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
iris = load_iris()
X = iris.data[:, 2:] # petal length and width
y = iris.target
tree_clf = DecisionTreeClassifier(max_depth=2)
tree_clf.fit(X, y)
from sklearn.tree import export_graphviz
export_graphviz(tree_clf, out_file=image_path("iris_tree.dot"),
feature_names=iris.feature_names[2:],
class_names=iris.target_names,
rounded=True,
filled=True
)
但是在 IPython 中运行时出现此错误:
我不熟悉 export_graphviz,有没有人知道如何纠正这个问题?
最佳答案
我猜您正在阅读 Aurelien Geron 所著的“使用 Scikit-Learn 和 TensorFlow 进行机器学习实践”一书。我在尝试“决策树”一章时遇到了同样的问题。你可以随时引用他的GitHub notebooks .对于你的代码,你可以引用“decision tree”笔记本。
下面我粘贴了笔记本中的代码。请继续看一下笔记本。
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
# Where to save the figures
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "decision_trees"
def image_path(fig_id):
return os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID, fig_id)
def save_fig(fig_id, tight_layout=True):
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(image_path(fig_id) + ".png", format='png', dpi=300)
关于python-3.x - 为什么在使用 export_graphviz 时我的 image_path 未定义? - python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47293271/