如何对随机森林进行交叉验证?

SSM*_*SMK 1 python classification machine-learning prediction random-forest

我正在使用随机森林进行二元分类。我的数据集不平衡,比例为 77:23。我的数据集形状是 (977, 7)

我最初尝试了以下方法

model = RandomForestClassifier(class_weight='balanced',max_depth=5,max_features='sqrt',n_estimators=300,random_state=24)
model.fit(X_train,y_train)
y_pred = mode.predict(X_test)
Run Code Online (Sandbox Code Playgroud)

但是,现在我想在随机森林训练期间应用交叉验证,然后使用该模型来预测测试数据的 y 值。所以,我做了下面的事情

model = RandomForestClassifier(class_weight='balanced',max_depth=5,max_features='sqrt',n_estimators=300,random_state=24)
scores = cross_val_score(model,X_train, y_train,cv=10, scoring='f1')
y_pred = cross_val_predict(model,X_test,cv=10)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这是不正确的。如何在训练随机森林期间应用交叉验证,然后使用该交叉验证模型来y_pred正确预测?

Ale*_*gat 5

交叉验证的目的是模型检查,而不是模型构建。

一旦您通过交叉验证检查了每次分割都获得了相似的指标,您就必须使用所有训练数据来训练您的模型。