Python线性回归代码报错:传入值形状(1,5)与索引暗示的(5,1)不匹配
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

