我正在使用执行超参数调整,RandomForest
如下所示GridSearchCV
。
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
并获得最好的结果作为最终结果?
如果需要,我很乐意提供更多详细信息。
在这种情况下,您不应执行网格搜索。
在内部,GridSearchCV
将分配给它的数据集分为多个训练和验证子集,然后使用提供给它的超参数网格,找到在验证子集上给出最佳分数的单个超参数集。
列车测试分割的点,然后,这个过程完成后,进行一个测试数据,它迄今未知的模型最终的得分,看看你的超参数已经过拟合来验证的子集。如果运行良好,则下一步是将模型投入生产/部署。
如果在交叉验证中执行网格搜索,则将有多组超参数,每组超参数在交叉验证拆分的其网格搜索验证子子集上表现最佳。您无法将这些集合组合为单个一致的超参数规范,因此无法部署模型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句