【发布时间】:2020-11-02 23:57:56
【问题描述】:
我刚刚了解了交叉验证,当我给出不同的论点时,会有不同的结果。
这是构建回归模型的代码,R 平方输出约为 0.5:
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import numpy as np
boston = load_boston()
X = boston.data
y = boston['target']
X_rooms = X[:,5]
X_train, X_test, y_train, y_test = train_test_split(X_rooms, y)
reg = LinearRegression()
reg.fit(X_train.reshape(-1,1), y_train)
prediction_space = np.linspace(min(X_rooms), max(X_rooms)).reshape(-1,1)
plt.scatter(X_test, y_test)
plt.plot(prediction_space, reg.predict(prediction_space), color = 'black')
reg.score(X_test.reshape(-1,1), y_test)
现在,当我对 X_train、X_test 和 X(分别)进行交叉验证时,它会显示不同的 R 平方值。
这是 X_test 和 y_test 参数:
from sklearn.model_selection import cross_val_score
cv = cross_val_score(reg, X_test.reshape(-1,1), y_test, cv = 8)
cv
结果:
array([ 0.42082715, 0.6507651 , -3.35208835, 0.6959869 , 0.7770039 ,
0.59771158, 0.53494622, -0.03308137])
现在,当我使用参数 X_train 和 y_train 时,会输出不同的结果。
from sklearn.model_selection import cross_val_score
cv = cross_val_score(reg, X_train.reshape(-1,1), y_train, cv = 8)
cv
结果:
array([0.46500321, 0.27860944, 0.02537985, 0.72248968, 0.3166983 ,
0.51262191, 0.53049663, 0.60138472])
现在,当我再次输入不同的参数时;这次 X(在我的例子中是 X_rooms)和 y,我又得到了不同的 R 平方值。
from sklearn.model_selection import cross_val_score
cv = cross_val_score(reg, X_rooms.reshape(-1,1), y, cv = 8)
cv
输出:
array([ 0.61748403, 0.79811218, 0.61559222, 0.6475456 , 0.61468198,
-0.7458466 , -3.71140488, -1.17174927])
我应该使用哪一个?
我知道这是一个很长的问题,所以谢谢!!
【问题讨论】:
标签: python-3.x scikit-learn linear-regression cross-validation