You need to enable JavaScript to run this app. 如何绘制波士顿数据集预测值与所有特征的关系图并解决报错
优惠活动
大模型
产品
解决方案
定价
更多

如何绘制波士顿数据集预测值与所有特征的关系图并解决报错

报错原因与解决方案

核心报错原因

你训练的是13特征的多元线性回归模型,输入特征矩阵xtrain维度为(样本数, 13),而matplotlib的2D绘图函数scatter和plot要求x轴输入为1维数组,二者维度不匹配触发报错。13维的线性回归超平面无法直接在2D/3D空间可视化,可选择以下两种适配方案:


方案1:单特征一元线性回归2D可视化

选择单个和房价相关性最高的特征(如LSTAT即区域低收入人口占比)建模,绘制2D散点与拟合线:

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

data1 = load_boston()
df1 = pd.DataFrame(data1.data)
df1.columns = data1.feature_names
df1['price']=data1.target

# 仅选择单个特征输入
X = df1[['LSTAT']]
Y = df1['price']

xtrain,xtest,ytrain,ytest = train_test_split(X,Y,test_size = 0.2,random_state =0)

lin_reg = LinearRegression()
lin_reg.fit(xtrain,ytrain)
ypredict = lin_reg.predict(xtest)

plt.scatter(xtrain, ytrain, color = 'red', s=10, label='训练集真实值')
plt.plot(xtrain, lin_reg.predict(xtrain), color = 'blue', label='拟合线')
plt.xlabel('LSTAT(低收入人口占比)')
plt.ylabel('房价')
plt.legend()
plt.show()

方案2:双特征线性回归3D平面可视化

选择两个特征输入,绘制3D空间的散点与拟合平面,符合你需要的「线性回归平面」需求:

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

data1 = load_boston()
df1 = pd.DataFrame(data1.data)
df1.columns = data1.feature_names
df1['price']=data1.target

# 选择两个特征输入
X = df1[['LSTAT', 'RM']]
Y = df1['price']

xtrain,xtest,ytrain,ytest = train_test_split(X,Y,test_size = 0.2,random_state =0)

lin_reg = LinearRegression()
lin_reg.fit(xtrain,ytrain)
ypredict = lin_reg.predict(xtest)

# 绘制3D图
fig = plt.figure(figsize=(10,7))
ax = fig.add_subplot(111, projection='3d')
# 绘制训练集散点
ax.scatter(xtrain['LSTAT'], xtrain['RM'], ytrain, c='red', s=10, label='训练集真实值')
# 生成网格点绘制拟合平面
x_surf = np.linspace(xtrain['LSTAT'].min(), xtrain['LSTAT'].max(), 100)
y_surf = np.linspace(xtrain['RM'].min(), xtrain['RM'].max(), 100)
x_surf, y_surf = np.meshgrid(x_surf, y_surf)
z_surf = lin_reg.predict(np.c_[x_surf.ravel(), y_surf.ravel()]).reshape(x_surf.shape)
ax.plot_surface(x_surf, y_surf, z_surf, color='blue', alpha=0.3, label='拟合平面')
ax.set_xlabel('LSTAT(低收入人口占比)')
ax.set_ylabel('RM(房屋平均房间数)')
ax.set_zlabel('房价')
plt.legend()
plt.show()

小提示:如果后续scikit-learn版本升级导致load_boston加载失败,可替换为from sklearn.datasets import fetch_openml,用data1 = fetch_openml(name='boston', version=1, parser='auto')加载数据。

内容的提问来源于stack exchange,提问作者Archana Jalaja Surendran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 22:45:02