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

多元线性回归模型绘制等高线图触发z需为2D数组报错求解

问题根因
  • 你遇到的TypeError: Input z must be 2D, not 1D错误核心是contourf要求输入的Z值必须是和np.meshgrid生成的X、Y网格维度完全匹配的二维数组,你直接把一维的测试集预测结果y_predict赋值给Z,维度完全不对应。
  • 额外逻辑错误:你没有对网格生成的每一组(X,Y)坐标点用训练好的线性回归模型做预测,生成对应的抗压强度值,而是直接复用了测试集的预测结果。
  • 代码疏漏:你没有提前创建axes对象就直接调用ax.contourf,运行时也会抛出未定义变量的错误。
修正方案

你需要先给网格生成的每一个坐标点构造完整的特征输入,用训练好的模型预测得到对应Z值,操作步骤如下:

  1. 确认你取的两列特征和你定义的坐标轴对应关系准确:X轴SiO2/Al2O3对应数据集第2列(索引1),Y轴Precursor/Aggregate对应数据集第4列(索引3)
  2. 固定其余特征的取值(默认取训练集对应特征的平均值,排除其他特征的影响,你也可以根据研究需要调整固定值)
  3. 遍历网格的所有坐标点,构造完整特征向量输入模型预测,得到二维Z矩阵
  4. 绘图前先创建axes对象
修正后完整代码
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

# 数据读取与模型训练部分保持不变
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

regressor = LinearRegression()
regressor.fit(X_train, y_train)

# 取出目标两列特征
feature_x = X_test[:, 1]
feature_y = X_test[:, 3]
# 生成网格
X_grid, Y_grid = np.meshgrid(feature_x, feature_y)

# 计算其余特征的平均值,用来固定其他变量
other_features_mean = np.mean(X_train, axis=0)
# 初始化Z矩阵,和网格维度一致
Z_grid = np.zeros_like(X_grid)

# 遍历每个网格点构造特征输入,预测抗压强度
for i in range(X_grid.shape[0]):
    for j in range(X_grid.shape[1]):
        # 复制平均特征值,替换成当前网格点的两个目标特征值
        input_feature = other_features_mean.copy()
        input_feature[1] = X_grid[i,j]
        input_feature[3] = Y_grid[i,j]
        # 预测当前点的Z值
        Z_grid[i,j] = regressor.predict(input_feature.reshape(1,-1))[0]

# 创建绘图对象
fig, ax = plt.subplots(figsize=(8,6))
# 绘制等高线填充图
contour = ax.contourf(X_grid, Y_grid, Z_grid, cmap='viridis')
# 添加颜色条
plt.colorbar(contour, ax=ax, label='Compressive Strength')
# 设置坐标轴和标题
ax.set_title('Filled Contour Plot')
ax.set_xlabel('SiO2/Al2O3')
ax.set_ylabel('Precursor/Aggregate')
plt.show()
可选优化

如果你觉得双重循环速度慢,可以用numpy向量化操作替代循环,代码逻辑完全等价:

# 构造所有网格点的特征矩阵
n_points = X_grid.size
input_features = np.tile(other_features_mean, (n_points, 1))
input_features[:,1] = X_grid.flatten()
input_features[:,3] = Y_grid.flatten()
# 批量预测再reshape成网格维度
Z_grid = regressor.predict(input_features).reshape(X_grid.shape)

内容的提问来源于stack exchange,提问作者Taqi Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:36:08