scikit-learn本身不负责绘图,fit()只返回训练对象,plot_tree等需配合%matplotlib inline和plt.show()才能在jupyter中显示;漏掉任一环节都会导致图形不出现。

scikit-learn 本身不负责绘图——它不生成图形,也不调用 plt.show() 或内联渲染。你在 Jupyter 中“看不到图形”,根本不是 scikit-learn 的问题,而是你没用对可视化工具,或者漏了关键渲染指令。
下面直奔常见真实场景,说清楚怎么做、为什么、踩什么坑。
为什么 fit() 之后什么图都没出来?
因为 scikit-learn 的模型训练(比如 clf.fit(X, y))只返回一个训练好的对象,不画图、不打印、不显示任何可视化内容。如果你期望它自动弹窗或 inline 出决策树/特征重要性图,那是误解。
常见错误现象:
- 运行
clf.fit(X, y)后单元格输出空,或只显示DecisionTreeClassifier(...)文本 - 误以为
sklearn.tree.plot_tree会自动显示——其实它只返回matplotlib.Artist对象,不触发渲染
怎么让 plot_tree 在 Jupyter 里真正显示出来?
sklearn.tree.plot_tree 依赖 matplotlib,但默认不会自动展示。必须配合内联后端 + 显式触发。
实操建议:
- 确保第一块代码单元格中已执行:
%matplotlib inline - 调用
plot_tree后,**必须加plt.show()**,否则只返回对象,不渲染图像 - 别用
fig = plt.figure()手动建图再传给plot_tree(fig=...)—— 容易因尺寸/布局错乱导致空白
正确示例:
%matplotlib inline from sklearn.tree import plot_tree from sklearn.datasets import make_classification from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as plt <p>X, y = make_classification(n_samples=100, n_features=2, n_informative=2, n_redundant=0, random_state=42) clf = DecisionTreeClassifier(max_depth=3, random_state=42).fit(X, y)</p><p>plt.figure(figsize=(10, 6)) plot_tree(clf, filled=True, rounded=True, fontsize=10, feature_names=['x1', 'x2']) plt.show() # ← 这行不能少</p>
想看特征重要性条形图,为什么 plt.bar() 没反应?
这是典型的「有绘图命令但无显示触发」问题。即使你写了 plt.bar(...),Jupyter 也不会自动把 figure 推到输出区。
关键点:
-
plt.bar()只是往当前 figure 添加元素,figure 本身还“关着” -
%matplotlib inline是前提,但不是万能——它只让后续的plt.show()或隐式 figure 输出生效 - 如果用了
fig, ax = plt.subplots(),记得最后调用plt.show()或fig.show()(后者在 Jupyter 中不一定可靠)
安全写法:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
<p>X, y = make_classification(n_samples=1000, n_features=5, n_informative=3, random_state=42)
rf = RandomForestClassifier(n_estimators=100, random_state=42).fit(X, y)</p><h1>直接用 plt.bar,不手动建 fig</h1><p>plt.figure(figsize=(8, 4))
plt.bar(range(len(rf.feature<em>importances</em>)), rf.feature<em>importances</em>)
plt.xticks(range(len(rf.feature<em>importances</em>)), [f'Feature {i}' for i in range(len(rf.feature<em>importances</em>))])
plt.ylabel('Importance')
plt.title('Feature Importances')
plt.show() # ← 必须有</p>
dtreeviz 能直接显示,但为啥 pip install 后还是报 ModuleNotFoundError?
这不是显示问题,是环境隔离问题。Jupyter Notebook 运行时用的 Python kernel 和你 pip install dtreeviz 的环境很可能不一致。
验证和修复步骤:
- 在 notebook 单元格中运行:
import sys; print(sys.executable),确认路径 - 在终端中,cd 到该路径所在目录(或用
which python/where python查),再执行pip install dtreeviz - 或者更稳妥:在 notebook 里直接用魔法命令安装:
!pip install dtreeviz(注意开头的!) - 安装后务必重启 kernel(Kernel → Restart),否则旧环境缓存仍生效
容易被忽略的一点:dtreeviz 依赖 graphviz,但只装 dtreeviz 不等于装了 graphviz 二进制。Mac 用户需 brew install graphviz,Windows 用户要手动下载并加进 PATH——否则 viz_model.view() 会静默失败,只返回空输出。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











