You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Google Colab中无法导入DecisionBoundaryDisplay的ImportError问题?

解决Google Colaboratory中导入DecisionBoundaryDisplay的报错问题

问题重现

运行以下代码尝试绘制决策边界时:

import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.inspection import DecisionBoundaryDisplay
iris = load_iris()

触发ImportError:

ImportError: cannot import name 'DecisionBoundaryDisplay' from 
'sklearn.inspection' (/usr/local/lib/python3.7/dist-packages/sklearn/inspection/__init__.py).

原因分析

DecisionBoundaryDisplay是scikit-learn 1.0版本新增的可视化工具,而Colab默认安装的scikit-learn版本较低,不包含该模块。

解决方案

方案1:升级scikit-learn到最新版

执行以下命令升级库:

!pip install --upgrade scikit-learn

升级完成后,必须重启Colab运行时(点击顶部菜单栏「Runtime」→「Restart runtime」),之后重新导入模块即可正常使用。

方案2:使用旧版手动绘制方法(无需升级)

如果不想升级库,可以手动生成网格并预测来绘制决策边界,示例代码如下(以决策树为例):

import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
import numpy as np

# 加载数据集,仅取前两个特征用于可视化
iris = load_iris()
X = iris.data[:, :2]
y = iris.target

# 训练决策树模型
clf = DecisionTreeClassifier(max_depth=3)
clf.fit(X, y)

# 生成覆盖特征范围的网格点
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
                     np.arange(y_min, y_max, 0.02))

# 预测网格点的类别
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

# 绘制决策边界与样本点
plt.figure(figsize=(8, 6))
plt.contourf(xx, yy, Z, alpha=0.7, cmap=plt.cm.Paired)
plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1])
plt.title('Decision Tree Decision Boundary')
plt.show()

内容的提问来源于stack exchange,提问作者Alamgir Hossain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:15:32