【问题标题】:From train test split to cross validation in sklearn using pipeline从训练测试拆分到使用管道在 sklearn 中进行交叉验证
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 我试过你说的,但可能有错误。我更新了我的帖子,你能看看它吗
    • cv 参数期望一个 int 值或一个可迭代的产生(训练、测试)拆分为索引数组。
    猜你喜欢
    • 2011-12-16
    • 2016-01-29
    • 2021-03-04
    • 2020-12-15
    • 2018-12-07
    • 2021-06-28
    • 2016-05-12
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多