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

简单线性回归报错:Expected a 2D array,求排查解决方案

解决简单线性回归中"Expected a 2D array, got 1D array instead"错误

错误信息

ValueError: Expected a 2D array, got 1D array instead:
array=[1140. 1635. 1755. 1354. 1978. 1696. 1212. 2736. 1055. 2839. 2325. 1688.
2733. 2332. 2159. 2133.].

问题原因

这个错误和数据集无关,是因为scikit-learn的线性回归模型要求输入的特征矩阵必须是二维数组,但你用x=df["Area"]提取的是Pandas Series对象,本质是一维结构,不符合模型的输入规范。

解决方法

有三种简单的修正方式,任选其一即可:

  • 方式1:用双括号提取特征,直接得到二维DataFrame:
    x = df[["Area"]]  # 注意是双括号
    
  • 方式2:用reshape(-1,1)把一维数组转为二维:
    x = df["Area"].values.reshape(-1, 1)
    
  • 方式3:用NumPy扩展维度:
    x = np.expand_dims(df["Area"], axis=1)
    

修改后的完整代码

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

# 读取数据
df = pd.read_csv('C:/Users/AgroMech/Desktop/ASDS/data.csv')
# 检查重复值数量
print("重复值数量:", df.duplicated().sum())
# 处理缺失值
df.dropna(inplace=True)
# 提取特征(改为二维结构)
x = df[["Area"]]
y = df["Price"]

# 划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=4)

# 训练模型
reg = LinearRegression()
reg.fit(x_train, y_train)

# 输出结果
print("回归系数:", reg.coef_)
y_pred = reg.predict(x_test)
mse = np.mean((y_pred - y_test)**2)
print("测试集均方误差:", mse)

内容的提问来源于stack exchange,提问作者Joy Biswas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:51:23