在sklearn中使用管道从列车测试拆分到交叉验证

2024-05-20 00:05:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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-fold交叉验证来训练我的模型,而不是训练测试分割。但是,我不知道如何使用管道结构来实现它。我发现: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)

Tags: fromtestimportdataframemodel管道pipelinetrain
1条回答
网友
1楼 · 发布于 2024-05-20 00:05:43

Pipeline用于组合几个步骤,如预处理、转换和建模StratifiedKFold用于分割数据集以评估模型的性能。它不打算用作Pipeline的一部分,因为您不想在新数据上执行它

因此,在管道结构之外执行此操作是正常的

相关问题 更多 >