我正在尝试在拟合的线性回归器上使用 .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)
我应该提到我已经尝试 reshape 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)
最佳答案
来自 scikit docs , score(X, y, sample_weight=None)
,因此您不会将预测作为第一个参数发送给它。相反,您发送功能。
因此,最后一行应该是
print(reg.score(X_test, y_test))
关于python - 使用 .score() 方法时出错 : shapes (10719, 1) 和 (16,1) 未对齐 : 1 (dim 1) ! = 16 (dim 0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51959370/