名称错误:名称“image_path”未定义

lmb*_*loo 2 python scikit-learn

我读过 stackoverflow 问题,解决方案似乎是插入完整路径,但是这样做后它给了我名称错误。我正在使用 Windows 10 python 3.7.1

这是我的代码:

from sklearn.tree import export_graphviz


export_graphviz(
        tree_clf,
        out_file = image_path("C:/Users/my_name/Desktop/iris_tree.dot"),# path where you want it to output
        feature_names=iris.feature_names[2:],
        class_names = iris.target_names,
        rounded=True,
        filled=True
)
Run Code Online (Sandbox Code Playgroud)

Ada*_*old 5

到底是什么image_pathexport_graphviz接受一个名为 的参数out_file,它可以是字符串或文件对象:

文件对象或字符串,可选(默认=无)

所以我会写:

from sklearn.tree import export_graphviz

f = open("C:/Users/my_name/Desktop/iris_tree.dot", 'w')
export_graphviz(
        tree_clf,
        out_file=f,  # path where you want it to output
        feature_names=iris.feature_names[2:],
        class_names = iris.target_names,
        rounded=True,
        filled=True
)
Run Code Online (Sandbox Code Playgroud)

如果您正在阅读 Aurelien Geron 的《Hands on Machine Learning with Scikit-Learn and TensorFlow》一书,以下是他的GitHubimage_path上的定义(仍然没有做您想要的事情,我只会使用我的第一个解决方案):

import os

# 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)
Run Code Online (Sandbox Code Playgroud)