【问题标题】:Pipeline Python with if and else statement for two models使用 if 和 else 语句为两个模型流水线 Python
【发布时间】:2021-12-07 13:36:01
【问题描述】:

假设我已经训练了两个机器学习模型,它们都使用随机森林,但其中一个用于分类,另一个用于预测。我想先进行分类,如果输出为 2,则进行谓词。我想为此使用一个管道(除了管道一切正常)将模型转换为 PMML 文件。我想知道如何为此实现管道(因为每个说有两个模型,并用 if 和 else 语句分隔),理想情况下我希望有一个管道来做这两个。

例如,我对每个管道都有类似的东西,但不知道如何将它们与 if-else 语句结合起来。

Pipe1 = Pipeline([('scaler', StandardScaler()),('classifier', RandomForestRegressor())])

Pipe2 = Pipeline([('classifier', RandomForestClassifier())])

在执行分类的预测阶段后,如果输出为 2,则运行第二个管道。

【问题讨论】:

  • @desertnaut,我添加了更多细节。我有这两条管道,并希望将它们合并到一条管道中,但我不知道如何进行。我知道管道仅适用于变换和拟合,而没有 if else 语句。
  • 为什么你觉得你需要在一些管道内部实现任何 if-then 逻辑?为什么不只是一个外部 if-then,以 Pipe2 的输出为条件?
  • 假设我想要一个 PMML 文件,那么我需要一个管道。总体计划是有一个 PMML 文件。

标签: python if-statement machine-learning pipeline pmml


【解决方案1】:

总体思路 - 将第一个估计器包装为转换器,并根据其转换值选择下一个模型。包装是必要的,因为根据 Scikit-Learn 约定,管道不应包含多个模型。

from sklego.meta import EstimatorTranformer
from sklearn2pmml.ensemble import SelectFirstClassifier
from sklearn2pmml.pipeline import PMMLPipeline

pipeline = PMMLPipeline([
  ("transformer", EstimatorTransformer(RandomForestClassifier())),
  ("estimator", SelectFirstClassifier([
    ("is_two", "X[0] == 2", RandomForestClassifier()),
    ("is_not_two", "True", RandomForestClassifier())
  ]))
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-12
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多