Sklearn:异构特征的 FeatureUnion 给出了与管道中的分类器不兼容的行尺寸错误

Sklearn: FeatureUnion of heterogenous features gives incompatible row dimensions error with classifier in the pipeline

我想根据我拥有的不同特征(文本和数字)进行二元分类。训练数据是 pandas 数据框的形式。我的管道看起来像这样:

final_pipeline = Pipeline([('union', FeatureUnion(
                transformer_list=[('body_trans', Pipeline([('selector', ItemSelector(key='body')),
                                                          ('count_vect', CountVectorizer())])),
                                  ('body_trans2', Pipeline([('selector', ItemSelector(key='body2')),
                                                          ('count_vect', TfidfVectorizer())])),
                                 ('length_trans', Pipeline([('selector', ItemSelector(key='length')),
                                                           ('min_max_scaler',  MinMaxScaler())]))],
                transformer_weights={'body_trans': 1.0,'body_trans2': 1.0,'length_trans': 1.0})),
                          ('svc', SVC())])

ItemSelector 看起来像这样:

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

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

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

现在,当我尝试 final_pipeline.fit(X_train, y_train) 时,它给了我 ValueError: blocks[0,:] has incompatible row dimensions 异常。

X_train, X_test, y_train, y_test = train_test_split(train_set, target_set)

是我获取训练数据的方式。 train_set 是一个包含 bodybody2length 等字段的数据框。target_set 是一个只有一个名为 label 的字段的数据框,它是我要分类的实际标签。

编辑:

我认为我输入管道的数据格式不正确。

train_set 是我的具有特征的训练数据,示例:

   body           length  body2
0  blah-blah      193     blah-blah-2
1  blah-blah-blah 153     blah-blah-blah-2 

target_set,这是带有分类标签

的DataFrame
  label
0  True
1  False

如果有任何关于使用DataFrames 的Pipeline 拟合参数的输入格式的教程,请提供link!我找不到关于如何在使用多列作为单独的功能时加载数据帧作为管道输入的适当文档。

感谢任何帮助!

问题出在您的 ItemSelector 中。它输出一个二维数据帧,但 CountVectorizer 和 TfidfVectorizer 需要一个一维字符串数组。

显示 ItemSelector 输出的代码:-

import numpy as np
from pandas import DataFrame
df = DataFrame(columns = ['body','length','body2'],data=np.array([['blah-blah', 193, 'blah-blah-2'],['blah-blah-2', 153, 'blah-blah-blah-2'] ]))

body_selector = ItemSelector(key='body')
df_body = body_selector.fit_transform(df)

df_body.shape
# (2,1)

您可以定义另一个 class,它可以以正确的形式整理要呈现给下一步的数据。

将此 class 添加到您的代码中,如下所示:

class Converter(BaseEstimator, TransformerMixin):
    def fit(self, x, y=None):
        return self

    def transform(self, data_frame):
        return data_frame.values.ravel()

然后像这样定义你的管道:

final_pipeline = Pipeline([('union', FeatureUnion(
                transformer_list=[('body_trans', Pipeline([('selector', ItemSelector(key='body')),
                                                           ('converter', Converter()),
                                                          ('count_vect', CountVectorizer())])),
                                  ('body_trans2', Pipeline([('selector', ItemSelector(key='body2')),
                                                            ('converter', Converter()),
                                                          ('count_vect', TfidfVectorizer())])),
                                 ('length_trans', Pipeline([('selector', ItemSelector(key='length')),
                                                           ('min_max_scaler',  MinMaxScaler())]))],
                transformer_weights={'body_trans': 1.0,'body_trans2': 1.0,'length_trans': 1.0})),
                          ('svc', SVC())])

无需将此添加到第三方,因为 MinMaxScalar 需要二维输入数据。

如有问题欢迎随时提问