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

复现作业3D绘图示例时仅显示空白窗口,求问题排查

解决3D绘图空白问题

以下是针对你代码导致空白窗口的几个修复点:

1. 解决LinearSVC收敛不足问题

LinearSVC默认迭代次数max_iter=1000不足以让模型在这个数据集上收敛,会导致计算出的分类面数值异常,超出可视范围。修改模型训练代码,增大迭代次数:

linear_svm_3d = LinearSVC(max_iter=10000, random_state=8).fit(X_new, y)

2. 修正3D轴初始化方式

部分matplotlib版本中直接实例化Axes3D会引发渲染异常,改用官方推荐的3D轴创建方式:
替换原代码中的

ax = Axes3D(figure, elev=-152, azim=-26)

为:

ax = figure.add_subplot(projection='3d', elev=-152, azim=-26)

3. 优化分类面绘制逻辑(可选)

原代码仅绘制了第一个类别的分类面,若需要展示所有4个类别的分隔面,可循环处理每个类别的系数:

# 遍历所有类别,绘制对应分隔面
for i in range(4):
    curr_coef = coef[i*3 : (i+1)*3]
    ZZ = (curr_coef[0] * XX + curr_coef[1] * YY + intercept[i]) / -curr_coef[2]
    ax.plot_surface(XX, YY, ZZ, rstride=8, cstride=8, alpha=0.3)

完整修复后代码

import numpy as np
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
from sklearn.svm import LinearSVC
from mpl_toolkits.mplot3d import Axes3D

X, y = make_blobs(centers=4, random_state=8)

# 添加第二个特征的平方项
X_new = np.hstack([X, X[:, 1:] ** 2])

# 增加迭代次数确保模型收敛
linear_svm_3d = LinearSVC(max_iter=10000, random_state=8).fit(X_new, y)

coef, intercept = linear_svm_3d.coef_.ravel(), linear_svm_3d.intercept_

# 显示线性分类器的分隔面
figure = plt.figure()
# 修正3D轴创建方式
ax = figure.add_subplot(projection='3d', elev=-152, azim=-26)
xx = np.linspace(X_new[:, 0].min() - 2, X_new[:, 0].max() + 2)
yy = np.linspace(X_new[:, 1].min() - 2, X_new[:, 1].max() + 2)
XX, YY = np.meshgrid(xx, yy)

# 绘制所有类别的分隔面
for i in range(4):
    curr_coef = coef[i*3 : (i+1)*3]
    ZZ = (curr_coef[0] * XX + curr_coef[1] * YY + intercept[i]) / -curr_coef[2]
    ax.plot_surface(XX, YY, ZZ, rstride=8, cstride=8, alpha=0.3)

mask=y==0
ax.scatter(X_new[mask, 0], X_new[mask, 1], X_new[mask, 2], c='b', marker='o', s=60)
ax.scatter(X_new[~mask, 0], X_new[~mask, 1], X_new[~mask, 2], c='r', marker='^', s=60)
ax.set_xlabel('特征0')
ax.set_ylabel('特征1')
ax.set_zlabel('特征2')
plt.show()

内容的提问来源于stack exchange,提问作者Illia Dariev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:05:58