【问题标题】:sklearn Pipeline correct usagesklearn Pipeline 正确使用
【发布时间】:2018-01-24 10:58:43
【问题描述】:

我在 python 中有一个数据框,它有一个名为“datetime”的日期时间文件。使用 Pipeline 和 FeatureUnion 我正在尝试提取日、月、工作日和 isBusinessday。为了提取这些功能,我编写了自定义代码。

我正在使用以下代码来提取日、月、工作日和 isBusinessday

class itemselector(BaseEstimator, TransformerMixin):
    def __init__(self, key):
        self.key = key

    def transform(self, X):
        return X[self.key]

    def fit(self, X, y=None):
        return self


    f_df = Pipeline([

       ('union', FeatureUnion([
    ('date', Pipeline([
        ('sitem', itemselector('pickup_datetime')),
        ('sday', Extract_date()),
    ])),
    ('month', Pipeline([
        ('sitem', itemselector('pickup_datetime')),
        ('smonth', Extract_month()),
    ])),
])),

    ])

当我运行此代码时,我将列表作为输出。比如说:

df = f_df.fit_transform(df_train[:5])

输出:

[14 12 19  6 26  3  6  1  4  3]  // it has both day and month.  it is not expected output 

但我是天和月是分开的功能。我怎样才能做到这一点 ?我的代码出了什么问题?谁能帮我找到它?

更新

总结一下我的问题,我得到了输出形状(10,),但我希望我的输出是(5,2)

更新了 1 根据要求我添加了必要的代码

class Extract_date(BaseEstimator, TransformerMixin):
    def fit(self, X):
        print('one')
        return self

    def transform(self, X):
        return X.apply(lambda y: y.day)


class Extract_month(BaseEstimator, TransformerMixin):
    def fit(self, X, **atr):
        print('two')
        return self

    def transform(self, X):
        return X.apply(lambda y: y.month)

【问题讨论】:

  • 投反对票的请留言并投反对票
  • FeatureUnion 将水平堆叠来自内部转换器每个部分的数据。你能显示Extract_monthExtract_date 返回的内容吗?
  • @VivekKumar,我添加了必要的代码。请看一下

标签: python pandas scikit-learn pipeline


【解决方案1】:

好的,Extract_monthExtract_date 返回一个系列,它是一维向量,因此 FeatureUnion 没有正确堆叠它们。对于 FeatureUnion,您需要来自每个内部转换器的具有相同行数的二维数据。

您可以为此使用reshape(-1,1)

所以像这样改变你的方法:

class Extract_date(BaseEstimator, TransformerMixin):
    ...
    ...

    def transform(self, X):
        return X.apply(lambda y: y.day).values.reshape(-1,1)


class Extract_month(BaseEstimator, TransformerMixin):
    ...
    ...

    def transform(self, X):
        return X.apply(lambda y: y.month).values.reshape(-1,1)

现在输出应该是正确的。如果还有问题,请随时询问。

【讨论】:

    猜你喜欢
    • 2022-12-19
    • 2022-01-12
    • 2021-06-17
    • 2019-06-05
    • 2020-02-12
    • 2021-11-04
    • 2017-10-02
    • 2020-09-25
    • 1970-01-01
    相关资源
    最近更新 更多