我有以下一段代码:
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)
答案 0 :(得分:1)
Pipeline
用于组装预处理、转换和建模等几个步骤。 StratifiedKFold
用于拆分数据集以评估模型的性能。它不打算用作 Pipeline
的一部分,因为您不想对新数据执行它。
因此在管道的结构之外执行它是正常的。