【问题标题】:New Feature in Scikit-Learn Pipeline - Interaction between two existing FeaturesScikit-Learn Pipeline 中的新功能 - 两个现有功能之间的交互
【发布时间】:2021-10-03 09:49:17
【问题描述】:

我的数据集中有两个特征:高度和面积。我想通过使用 scikit-learn 中的管道交互区域和高度来创建一个新功能。

谁能指导我如何实现这一目标?

谢谢

【问题讨论】:

    标签: feature-engineering scikit-learn-pipeline


    【解决方案1】:

    您可以使用自定义转换器实现此目的,实现拟合和转换方法。可选地,您可以让它从 sklearn TransformerMixin 继承以进行子弹分析。

    from sklearn.base import TransformerMixin
    
    class CustomTransformer(TransformerMixin):
        def fit(self, X, y=None):
            """The fit method doesn't do much here, 
               but it still required if your pipeline
               ever need to be fit. Just returns self."""
            return self
    
        def transform(self, X, y=None):
            """This is where the actual transformation occurs.
               Assuming you want to compute the product of your feature
               height and area.
            """
            # Copy X to avoid mutating the original dataset
            X_ = X.copy()
            # change new_feature and right member according to your needs
            X_["new_feature"] = X_["height"] * X_["area"]
            # you then return the newly transformed dataset. It will be 
            # passed to the next step of your pipeline
            return X_
    

    您可以使用以下代码对其进行测试:

    import pandas as pd
    from sklearn.pipeline import Pipeline
    
    # Instantiate fake DataSet, your Transformer and Pipeline
    X = pd.DataFrame({"height": [10, 23, 34], "area": [345, 33, 45]})
    custom = CustomTransformer()
    pipeline = Pipeline([("heightxarea", custom)])
    
    # Test it
    pipeline.fit(X)
    pipeline.transform(X)
    

    对于这样一个简单的处理,它可能看起来有点矫枉过正,但将任何数据集操作放入 Transformer 中是一个很好的做法。那样的话,它们的重现性更高。

    【讨论】:

      猜你喜欢
      • 2015-08-13
      • 2016-02-01
      • 1970-01-01
      • 2018-10-27
      • 2014-03-02
      • 2014-04-16
      • 2020-11-15
      • 2014-05-01
      • 2014-08-09
      相关资源
      最近更新 更多