【发布时间】:2019-08-31 10:43:35
【问题描述】:
我正在使用GridSearchCV 执行RandomForest 的超参数调整,如下所示。
X = np.array(df[features]) #all features
y = np.array(df['gold_standard']) #labels
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
param_grid = {
'n_estimators': [200, 500],
'max_features': ['auto', 'sqrt', 'log2'],
'max_depth' : [4,5,6,7,8],
'criterion' :['gini', 'entropy']
}
CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 5)
CV_rfc.fit(x_train, y_train)
print(CV_rfc.best_params_)
我得到的结果如下。
{'criterion': 'gini', 'max_depth': 6, 'max_features': 'auto', 'n_estimators': 200}
之后,我将调整后的参数重新应用到x_test,如下所示。
rfc=RandomForestClassifier(random_state=42, criterion ='gini', max_depth= 6, max_features = 'auto', n_estimators = 200, class_weight = 'balanced')
rfc.fit(x_train, y_train)
pred=rfc.predict(x_test)
print(precision_recall_fscore_support(y_test,pred))
print(roc_auc_score(y_test,pred))
但是,我仍然不清楚如何将GridSearchCV 与10-fold cross validation 一起使用(即不只是将调整后的参数应用于x_test)。即如下所示。
kf = StratifiedKFold(n_splits=10)
for fold, (train_index, test_index) in enumerate(kf.split(X, y), 1):
X_train = X[train_index]
y_train = y[train_index]
X_test = X[test_index]
y_test = y[test_index]
或
既然GridSearchCV 使用了crossvalidation,我们可以使用所有X 和y 并得到最好的结果作为最终结果吗?
如果需要,我很乐意提供更多详细信息。
【问题讨论】:
-
您在问如果您进行交叉验证,是否可以将您的测试集用作 GridSearch 的一部分?这样做最终会提供一个有偏差的分类性能,高估你的 trianed 分类器的泛化能力。 Imo,您目前拥有的代码提供了对泛化能力的最佳估计。所以我不会改变任何东西。
标签: python machine-learning scikit-learn cross-validation