【问题标题】:sklearn pipelines with fit_transfrom or predict objects instead of fit objects带有 fit_transfrom 或预测对象而不是拟合对象的 sklearn 管道
【发布时间】:2021-01-04 02:50:24
【问题描述】:

This example on sklearn websitethis answer to sklearn pipelines on SO 在管道中使用并仅讨论使用 .fit().fit_transform() 方法。

但是,我如何在 Pipelines 中使用 .predict 或 .transfrom 方法。假设我已经预处理了我的训练数据,搜索了最佳超参数并训练了一个 LightGBM 模型。根据definition,我现在想预测新数据,而不是手动执行所有上述操作,我想一个接一个地完成它们:

依次应用变换列表和最终估算器。 管道的中间步骤必须是“转换”,即它们 必须实现 fit 和 transform 方法。仅最终估计器 需要实现fit。

但是,我只想在我的验证(或测试)数据上实现 .transform 方法,以及更多采用 pandas Series(或 DataFrame 或 numpy 数组)并返回处理过的函数(或类),然后最终实现 @我的 LightGBM 的 987654327@ 方法,它将使用我已有的超参数。

我目前什么都没有,因为我不知道如何正确地包含类的方法(比如 StandardScaler_instance.transform()) 和更多这样的方法。!

我该怎么做或者我错过了什么?

【问题讨论】:

    标签: python machine-learning scikit-learn pipeline


    【解决方案1】:

    您必须构建您的管道,其中将包括 LightGBM 模型并根据您的(预处理的)训练数据训练管道。

    使用代码,它可能如下所示:

    import lightgbm
    from sklearn.pipeline import Pipeline
    from sklearn.datasets import make_classification
    from sklearn.model_selection import train_test_split
    from sklearn.preprocessing import StandardScaler
    
    # Create some train and test data
    X, y = make_classification(random_state=0)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    
    # Define pipeline with scaler and lightgbm model
    pipe = Pipeline([('scaler', StandardScaler()), ('lightgbm', lightgbm.LGBMClassifier())])
    
    # Train pipeline
    pipe.fit(X_train, y_train)
    
    # Make predictions with pipeline (with lightgbm)
    print("Predictions:", pipe.predict(X_test))
    
    # Evaluate pipeline performance
    print("Performance score:", pipe.score(X_test, y_test))
    

    输出:

    Predictions: [1 0 1 0 0 0 1 0 1 1 1 0 0 1 0 1 0 0 1 1 1 0 1 0 0]
    Performance score: 0.84
    

    所以回答你的问题:

    但是,我如何在 Pipelines 中使用 .predict 或 .transfrom 方法。

    • 您不必使用 .transform,因为管道会使用提供的转换器自动处理输入数据的转换。这就是为什么在documentation 中提到:

    管道的中间步骤必须是“转换”,即它们 必须实现 fit 和 transform 方法。

    • 您可以将代码示例中所示的 .predict 用于您的测试数据。

    代替我在本示例中使用的 StandardScaler,您可以为管道提供自定义转换器,但它必须实现管道可以调用的 .transform() 和 .fit() 方法以及转换器的输出需要匹配 lightgbm 模型所需的输入。

    更新

    然后,您可以为管道的不同步骤提供参数,如文档 here 中所述:

    **fit_paramsdict of string -> object 传递给每个步骤的fit 方法的参数,其中每个参数名称都有前缀,这样 步骤s 的参数p 有键s__p

    【讨论】:

    • 非常感谢您的时间和精力。不过我有一个疑问。如果 a 有其实例和方法带参数的对象。例如,我创建了一个带有一些参数的 lightgbm 实例,我认为它可以包含在上面显示的 Pipleine 中。但是,如果将参数传递给 fit 方法,例如验证集(不是测试集)和我的自定义评估指标,该怎么办。
    • 我有这个疑问,因为我认为 pipe.fit() 不接受所有这些参数,我还想知道是否有其他对象的 .fit() 方法采用不同的参数?有什么方法可以在 .fit 和 .predict 或 .transform 期间为管道的每个步骤指定不同的参数?
    • 我的意思是问,有什么方法可以让 Pipleine 对不同的步骤使用不同的参数,适用于 fit 方法和 predict 或 transfrom 方法(如果适用)。
    • 是的,您可以为管道中的每个步骤使用不同的参数。查看文档here 以了解如何在 fit() 方法调用期间提供参数。我也用这些信息更新了我的答案。
    • @NaveenKumar 不用担心,我很高兴能帮上忙!
    猜你喜欢
    • 2019-06-29
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2018-11-08
    • 2018-11-11
    • 2022-01-23
    相关资源
    最近更新 更多