我正在尝试解决 Boston Dataset 上的回归问题在random forest regressor的帮助下.我用的是GridSearchCV用于选择最佳超参数。
问题一
我是否应该将 GridSearchCV
拟合到一些 X_train, y_train
上,然后获得最佳参数。
或
我是否应该将它放在 X, y
上以获得最佳参数。(X, y = 整个数据集)
问题2
假设我将它拟合到 X, y
上并获得最佳参数,然后在这些最佳参数上构建一个新模型。
现在我应该如何训练这个新模型?
我应该在 X_train, y_train
还是 X, y.
上训练新模型
问题3
如果我在 X,y
上训练新模型,那么我将如何验证结果?
到目前为止我的代码
#Dataframes
feature_cols = ['CRIM','ZN','INDUS','NOX','RM','AGE','DIS','TAX','PTRATIO','B','LSTAT']
X = boston_data[feature_cols]
y = boston_data['PRICE']
训练数据的测试拆分
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 1)
网格搜索以获得最佳超参数
from sklearn.grid_search import GridSearchCV
param_grid = {
'n_estimators': [100, 500, 1000, 1500],
'max_depth' : [4,5,6,7,8,9,10]
}
CV_rfc = GridSearchCV(estimator=RFReg, param_grid=param_grid, cv= 10)
CV_rfc.fit(X_train, y_train)
CV_rfc.best_params_
#{'max_depth': 10, 'n_estimators': 100}
在 max_depth:10,n_estimators:100 上训练模型
RFReg = RandomForestRegressor(max_depth = 10, n_estimators = 100, random_state = 1)
RFReg.fit(X_train, y_train)
y_pred = RFReg.predict(X_test)
y_pred_train = RFReg.predict(X_train)
RMSE:2.8139766730629394
我只是想要一些关于正确步骤的指导
最佳答案
一般来说,要调整超参数,您应该始终在 X_train
上训练您的模型,并使用 X_test
来检查结果。您必须根据 X_test
获得的结果调整参数。
您永远不应该调整整个数据集的超参数,因为这会破坏测试/训练拆分的目的(正如您在问题 3 中正确提出的那样)。
关于python - 拟合 sklearn GridSearchCV 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53449337/