Skip to main content
 首页 » 编程设计

python之如何修复 python 中的 sklearn 多元线性回归 ValueError(样本数不一致 : [2, 1])

2024年12月31日7myhome

我的线性回归与单个特征完美配合。自从尝试使用两个以来,我收到以下错误:ValueError: Found input variables with inconsistent numbers of samples: [2, 1]

第一个打印语句打印以下内容: (2, 6497) (1, 6497)

然后代码在 train_test_split 阶段崩溃。

有什么想法吗?

feat_scores = {} 
X = df[['alcohol','density']].values.reshape(2,-1)    
y = df['quality'].values.reshape(1,-1) 
 
print (X.shape, y.shape) 
 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) 
 
print (X_train.shape, y_train.shape) 
print (X_test.shape, y_test.shape) 
 
reg = LinearRegression() 
reg.fit(X_train, y_train) 
 
reg.predict(y_train) 

请您参考如下方法:

你错过了这一行

X = df[['alcohol','density']].values.reshape(2,-1)    
y = df['quality'].values.reshape(1,-1) 

不要将数据 reshape 为(2, 6497) (1, 6497),而是必须将其作为(6497,2) (6497,)>

Sklearn 直接获取数据帧/系列。所以你可以给,

X = df[['alcohol','density']] 
y = df['quality'] 

此外,您只能使用 X 值进行预测,因此

reg.predict(X_train) 

或

reg.predict(X_test)