【问题标题】:Transform results of estimator in a sklearn pipeline在 sklearn 管道中转换估计器的结果
【发布时间】:2021-03-09 10:25:58
【问题描述】:

我有一个 sklearn 管道,它由一个自定义转换器和 XGBClassifier 组成。作为转换器的最后一步,我想添加的是另一个自定义转换器,它可以转换 XGBClassifier 的结果。

最后一个自定义转换器会将预测的概率排列成等级(5​​ 个百分位数)。

Pipeline([
          ('custom_trsf1', custom_trsf1),
          ('clf', XGBCLassifier()),
          ('custom_trsf2', custom_trsf2)])

问题在于 sklearn 管道要求所有步骤(但最后一步)都应该有一个 fit and transform 方法。我可以用另一种方式解决这个问题,而不是扩展 XGBclassifier 并向其添加转换方法吗?

【问题讨论】:

    标签: python scikit-learn pipeline xgboost


    【解决方案1】:

    Pipeline实现的源代码来看,用于拟合数据的估计器位于您步骤的最后位置,Pipeline的_final_estimator属性调用Pipeline步骤的最后位置。

    @property
    def _final_estimator(self):
        estimator = self.steps[-1][1]
        return 'passthrough' if estimator is None else estimator
    

    steps 可能类似于

    steps = [('scaler', StandardScaler(copy=True, with_mean=True, with_std=True)),
     ('svc',
      SVC(C=1.0, break_ties=False, cache_size=200, class_weight=None, coef0=0.0,
          decision_function_shape='ovr', degree=3, gamma='scale', kernel='rbf',
          max_iter=-1, probability=False, random_state=None, shrinking=True,
          tol=0.001, verbose=False))]
    

    _final_estimator 属性只是被调用,在一个接一个地拟合所有变换之后,以获得要拟合到模型的估计器,详见333 行。

    所以,考虑到steps,我可以从SVC 类的最后一个位置检索它

    final_estimator = steps[-1][1]
    final_estimator
    >>> SVC(C=1.0, ..., verbose=False)
    

    并拟合训练数据

    final_estimator.fit(Xt, y)
    

    其中Xt 是转换后的训练数据(calculated 在拟合估计器之前),y 是训练目标。

    【讨论】:

      猜你喜欢
      • 2017-06-13
      • 2020-12-26
      • 2018-06-24
      • 2017-01-17
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 2017-05-15
      相关资源
      最近更新 更多