首页 文章

使用.score()方法时出错:shape(10719,1)和(16,1)未对齐:1(dim 1)!= 16(dim 0)

提问于
浏览
-1

我试图在拟合的线性回归器上使用.score()方法,但我收到一个错误 .

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
from sklearn.metrics import mean_squared_error

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, 
random_state = 104)
reg = LinearRegression()
reg.fit(X_train, y_train)
y_pred = reg.predict(X_test)
print("R^2: {}".format(reg.score(X_test, y_test)))
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
print("Root Mean Squared Error: {}".format(rmse))
reg.score(y_test.reshape(-1,1), y_pred.reshape(-1,1))

ValueError: shapes (10719,1) and (16,1) not aligned: 1 (dim 1) != 16 (dim 0)

我应该提一下,我已经尝试重塑y_pred和y_test,以便它们匹配,但它仍然不起作用 . 我不确定为什么错误说(16,1);这些维度是什么?我试图寻找类似这样的问题:Error using sklearn and linear regression: shapes (1,16) and (1,1) not aligned: 16 (dim 1) != 1 (dim 0)但我仍然感到困惑 .

编辑:这是形状的输出:

print(X_test.shape, y_test.shape, y_pred.shape)

(10719, 16) (10719, 1) (10719, 1)

1 回答

  • 2

    从scikit docsscore(X, y, sample_weight=None) ,所以你不要将预测作为第一个参数发送给它 . 相反,您发送功能 .

    因此,最后一行应为 print(reg.score(X_test, y_test))

相关问题