python-3.x - 为什么在使用 export_graphviz 时我的 image_path 未定义? - python 3

标签 python-3.x

我正在尝试在 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 中运行时出现此错误:
enter image description here

我不熟悉 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/

相关文章:

python - 可选参数初始化中的访问类

python-3.x - 根据其他列的最大值选择列中的值

python-3.x - 哪个版本的 Miniconda 有适用于 64 位 Windows 的 Python 3.6?

regex - 使用正则表达式模式从 pandas 数据框中过滤行

python - 解析括号

python - 如何解决 "pip install pygame"问题?

python - 为什么 request.method 没有被调用?

python-3.x - ValueError : The number of FixedLocator locations (5), 通常来自对 set_ticks 的调用,与刻度标签的数量不匹配 (12)

Python:for循环 - 在同一行打印

python - Python3 定义名称时出现名称错误