【发布时间】:2021-08-29 13:01:59
【问题描述】:
我有以下代码:
from sklearn import model_selection
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
from sklearn.pipeline import Pipeline
...
x_train, x_test, y_train, y_test= model_selection.train_test_split(dataframe[features_],dataframe[labels], test_size=0.30,random_state=42, shuffle=True)
classifier = RandomForestClassifier(n_estimators=11)
pipe = Pipeline([('feats', feature), ('clf', classifier)])
pipe.fit(x_train, y_train)
predicts = pipe.predict(x_test)
我想使用 k 折交叉验证来训练我的模型,而不是训练测试拆分。但是,我不知道如何通过使用管道结构来实现。我遇到了这个:https://scikit-learn.org/stable/modules/compose.html 但我无法适应我的代码。
如果可能,我想使用from sklearn.model_selection import StratifiedKFold。我可以在没有管道结构的情况下使用它,但我不能在管道中使用它。
更新: 我试过了,但它会产生错误。
x_train = dataframe[features_]
y_train = dataframe[labels]
skf = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
classifier = RandomForestClassifier(n_estimators=11)
#pipe = Pipeline([('feats', feature), ('clf', classifier)])
#pipe.fit(x_train, y_train)
#predicts = pipe.predict(x_test)
predicts = cross_val_predict(classifier, x_train , y_train , cv=skf)
【问题讨论】:
标签: python scikit-learn pipeline cross-validation