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

Python线性回归代码报错:传入值形状(1,5)与索引暗示的(5,1)不匹配

Fixing the Shape Mismatch Error in Your Linear Regression Code

Hey there, let's break down that shape error you're hitting when creating your coefficient DataFrame.

First, let's recap the exact error you encountered:

"Shape of passed values is (1, 5), indices imply (5, 1)"

What's Causing This?

The issue boils down to how pandas interprets the data structure you're feeding into pd.DataFrame(). Here's the problem line in your code:

cdf = pd.DataFrame(lm.coef_, X.columns, columns = ['Coeff'])
  • When you fit a multi-feature linear regression, lm.coef_ returns a 1-dimensional array (shape (5,)) if you have 5 features. Pandas treats this 1D array as a single row of data (shape (1,5)).
  • But you’re passing X.columns (which has 5 elements) as the second argument, which pandas uses as the DataFrame’s index. This tells pandas you want a 5-row DataFrame—but your input data only has 1 row. That’s the shape mismatch triggering the error!

Two Simple Fixes

Fix 1: Reshape the Coefficient Array

Convert the 1D coef_ array into a 2D column vector using reshape(-1,1) so pandas recognizes it as 5 rows of data:

cdf = pd.DataFrame(lm.coef_.reshape(-1, 1), X.columns, columns=['Coeff'])

Fix 2: Use Explicit Parameter Names

Avoid ambiguity by specifying the index parameter directly, and pass coefficients as a dictionary (this makes the data structure clearer at a glance):

cdf = pd.DataFrame({'Coeff': lm.coef_}, index=X.columns)

Either approach will create a clean DataFrame where each row maps a feature from X.columns to its corresponding regression coefficient.

Your Original Code for Reference

Just to align on context, here's the code snippet you shared:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.4, random_state=101)
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit(X_train,y_train)
print(lm.intercept_)
lm.coef_
X_train.columns
cdf = pd.DataFrame(lm.coef_, X.columns, columns = ['Coeff'])

内容的提问来源于stack exchange,提问作者Biprajit Namasudra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:52:44