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

Regression Plane颜色不均原因及纯色设置技术咨询

问题分析与解决方案

问题原因

  1. 回归平面计算错误:代码中计算z_plane时误用系数索引,将y的系数写成plane_coef[2](实际应为plane_coef[1]),同时重复使用plane_coef[2]作为截距,导致平面方程错误。
  2. 网格生成不合理:直接用原始样本点生成meshgrid,得到的是不规则离散网格,绘制平面时会产生大量小面,视觉上出现不均匀暗纹。
  3. 绘图参数设置不当:alpha=0.01透明度极低,加上默认边缘线和颜色映射,加剧了颜色不均匀的视觉效果。

修正后的代码

import numpy as np
import pandas as pandas
import statsmodels.api as sm
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D

v = [1000, 1200, 1000, 900, 1500, 1000, 1400, 1500, 1500, 1600, 1100, 1300, 1000, 1600, 1600, 1600, 1600, 2200, 1600, 2000, 1600, 2000, 2100, 1600, 1600, 2000, 2000, 2000, 1600, 2000, 2100, 2000, 1600, 1600, 1600, 2500]
w = [790, 1160, 929, 865, 1140, 929, 1109, 1365, 1112, 1150, 980, 990, 1112, 1252, 1326, 1330, 1365, 1280, 1119, 1328, 1584, 1428, 1365, 1415, 1415, 1465, 1490, 1725, 1523, 1705, 1605, 1746, 1235, 1390, 1405, 1395]
c = [99, 95, 95, 90, 105, 105, 90, 92, 98, 99, 99, 101, 99, 94, 97, 97, 99, 104, 104, 105, 94, 99, 99, 99, 99, 102, 104, 114, 109, 114, 115, 117, 104, 108, 109, 120]

# Create the plot
fig=plt.figure()
ax = fig.add_subplot(111,projection='3d')

z=np.array(c)
x=np.array(v)
y=np.array(w)

# Add the data points
ax.scatter(x, y, z, color='red')

# Fit a plane using np.linalg.lstsq
A = np.vstack([x, y, np.ones_like(x)]).T
plane_coef, _, _, _ = np.linalg.lstsq(A, z, rcond=None)

# 生成均匀覆盖数据范围的网格(替代原始离散样本点)
x_min, x_max = x.min(), x.max()
y_min, y_max = y.min(), y.max()
x_plane = np.linspace(x_min, x_max, 50)
y_plane = np.linspace(y_min, y_max, 50)
x_plane, y_plane = np.meshgrid(x_plane, y_plane)

# 修正平面方程计算:使用正确的系数索引
z_plane = plane_coef[0] * x_plane + plane_coef[1] * y_plane + plane_coef[2]

# 绘制纯色平面:关闭边缘线、禁用颜色映射、调整合适透明度
ax.plot_surface(x_plane, y_plane, z_plane, zorder=15, color='c', alpha=0.3, edgecolor='none', cmap=None)

# Add labels and title
ax.set_xlabel('weight')
ax.set_ylabel('volume')
ax.set_zlabel('Co2')
plt.title('Multiple Linear Regression')

for ii in np.arange(-60,60,45):
    ax.view_init(elev=32, azim=ii)
    fig.savefig('gif_image%d.png' % ii)

fig.tight_layout()

plt.show()

关键修正点说明

  • 修正平面方程:将plane_coef[2] * y_plane + plane_coef[2]改为plane_coef[1] * y_plane + plane_coef[2],确保回归平面计算正确。
  • 生成均匀网格:用np.linspace生成覆盖x、y数据范围的均匀网格,让平面绘制更平滑。
  • 优化绘图参数:
    • 设置edgecolor='none'去除平面小面的边缘线,避免暗纹;
    • 加上cmap=None禁用默认颜色映射,强制使用指定纯色;
    • 调整alpha到0.3(可按需调整),平衡透明度和纯色显示效果。

内容的提问来源于stack exchange,提问作者Basir Touati

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 01:02:33