【问题标题】:Error in FeatureUnion Sklearn PipelineFeatureUnion Sklearn 管道中的错误
【发布时间】:2017-12-20 10:28:28
【问题描述】:

我有以下数据框:

ID Text 
1  qwerty
2  asdfgh

我正在尝试为 Text 字段创建 md5 哈希,并从上面的数据框中删除 ID 字段。为了实现这一点,我创建了一个简单的pipeline,其中包含来自sklearn 的自定义转换器。

这是我使用的代码:

class cust_txt_col(sklearn.base.BaseEstimator, sklearn.base.TransformerMixin):
    def __init__(self, key):
        self.key = key
    def fit(self, x, y=None):
        return self

    def hash_generate(self, txt):

        m = hashlib.md5()
        text = str(txt)
        long_text = ' '.join(text.split())
        m.update(long_text.encode('utf-8'))
        text_hash= m.hexdigest()
        return text_hash

    def transform(self, x):
        return x[self.key].apply(lambda  z: self.hash_generate(z)).values

class cust_regression_vals(sklearn.base.BaseEstimator, sklearn.base.TransformerMixin):
    def fit(self, x, y=None):
        return self
    def transform(self, x):
        x = x.drop(['Gene', 'Variation','ID','Text'], axis=1)
        return x.values

fp = pipeline.Pipeline([

 ('union', pipeline.FeatureUnion([
        ('hash', cust_txt_col('Text')), # can pass in either a pipeline
        ('normalized', cust_regression_vals()) # or a transformer
    ]))
])

当我运行它时,我收到以下错误:

ValueError: all the input arrays must have same number of dimensions

你能告诉我我的代码有什么问题吗?

如果我一个一个地运行课程:

对于 cust_txt_col 我低于 o/p

['3e909f222a1e06098ec7ca1ea7e84540' '1691bdba3b75df145169e0501369fce3'
 '1691bdba3b75df145169e0501369fce3' ..., 'e11ec9863aaeb93f77a231319021e14d'
 '851c517b2af0a46cb9bc9373b748b6ff' '0ffe46fc75d21a5347b1f1a5a84526ad']

对于 cust_regression_vals 我低于 o/p

[[qwerty],
  [asdfgh]]

【问题讨论】:

  • 不应该是cust_txt_col(dataframe['Text'])吗?另外,如果你一个一个地运行类,你会收到什么输出?
  • @E.Z.用 o/p 类更新了我的帖子
  • 问题可能是cust_regression_vals;尝试在第二个类的末尾添加return x.ravel().values 并验证是否可以。如果没有,您可以发布cust_txt_col.shape 的输出吗?
  • @E.Z... cust_txt_col.shape 是 (3321,) 并且 cust_regression_vals.shape 是 (3321, 8)

标签: python scikit-learn


【解决方案1】:

cust_txt_col 正在返回一个一维数组。 FeatureUnion 要求每个组成转换器返回一个二维数组。

【讨论】:

  • 还建议 OP @Backtrack 如何解决问题。就像使用 reshape() 改变 transform() 的输出形状一样。那么这个答案就完成了。
猜你喜欢
  • 1970-01-01
  • 2017-08-15
  • 2017-12-24
  • 1970-01-01
  • 2020-01-28
  • 2019-05-14
  • 2017-12-29
  • 2018-11-30
  • 2016-07-06
相关资源
最近更新 更多