解决dtreeviz的TypeError: ‘module‘ object is not callable问题

解决dtreeviz的TypeError: ‘module‘ object is not callable问题

    • 一般在网上搜索到的答案
    • 正确的调用方法

一般在网上搜索到的答案

导入需要的基本库

from dtreeviz.trees import *

regr = tree.DecisionTreeRegressor(max_depth=2)
boston = load_boston()
regr.fit(boston.data, boston.target)

viz = dtreeviz(regr,
               boston.data,
               boston.target,
               target_name='price',
               feature_names=boston.feature_names)

viz.view()

但是如果你这样调用就会指向dtreeviz,出现
TypeError: ‘module‘ object is not callable
再搜索会发现有的人是这样导入包:

import dtreeviz

这样还是会出现上面的问题。
最后找到Github上的文档,会发现现在的调用方法变了。
链接: https://github.com/parrt/dtreeviz.

正确的调用方法

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier

import dtreeviz

iris = load_iris()
X = iris.data
y = iris.target

clf = DecisionTreeClassifier(max_depth=4)
clf.fit(X, y)

viz_model = dtreeviz.model(clf,
                           X_train=X, y_train=y,
                           feature_names=iris.feature_names,
                           target_name='iris',
                           class_names=iris.target_names)

v = viz_model.view()     # render as SVG into internal object 
v.show()                 # pop up window
v.save("/tmp/iris.svg")  # optionally save as svg

如果你想在notebook中显示,可以把show()函数换成view()

viz_model.view()       # in notebook, displays inline

生成的图片是这样的
解决dtreeviz的TypeError: ‘module‘ object is not callable问题_第1张图片

同时,上面还强调了,如果用Jupyter notebook显示.svg文件会有问题,可以换成Jupyter Lab。

你可能感兴趣的:(机器学习,python)