FeatureUnion Sklearn管道出错

时间:2017-07-15 11:54:04

标签: python scikit-learn

我有以下数据框:

ID Text 
1  qwerty
2  asdfgh

我正在尝试为文字字段创建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]]

1 个答案:

答案 0 :(得分:3)

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