0

我正在尝试根据熊猫数据框的不同特征训练元分类器。

这些特征本质上是文本或分类的。

我在拟合模型时遇到问题,出现以下错误“找到样本数量不一致的输入变量:[1, 48678]”。我理解错误的含义,但不知道如何修复它。非常感谢帮助!

我正在使用的代码如下:

import pandas as pd
from sklearn import preprocessing
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.feature_extraction.text import TfidfVectorizer

# set target label
target_label = ['target']
features = ['cat_1', 'cat_2', 'cat_3', 'cat_4', 'cat_5', 
'text_1']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(cleansed_data[features], 
cleansed_data[target_label], test_size=0.2, random_state=0)

text_features = ['text_1']
categorical_features = ['cat_1', 'cat_2', 'cat_3', 'cat_4', 'cat_5']

# encoder
le = preprocessing.LabelEncoder()

# vectoriser
vectoriser = TfidfVectorizer()

# classifiers
mlp_clf = MLPClassifier()
rf_clf = RandomForestClassifier()

from sklearn.base import TransformerMixin, BaseEstimator
class SelectColumnsTransfomer(BaseEstimator, TransformerMixin):

    def __init__(self, columns=[]):
    self.columns = columns

    def transform(self, X, **transform_params):
        trans = X[self.columns].copy()
        return trans

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

# text pipeline
text_steps = [('feature extractor', SelectColumnsTransfomer(text_features)),
          ('tf-idf', vectoriser),
          ('classifier', mlp_clf)]

# categorical pipeline
categorical_steps = [('feature extractor', 
SelectColumnsTransfomer(categorical_features)),
                 ('label encode', le),
                 ('classifier', rf_clf)]

pl_text = Pipeline(text_steps)
pl_categorical = Pipeline(categorical_steps)

pl_text.fit(X_train, y_train)

from mlxtend.classifier import StackingCVClassifier
sclf = StackingCVClassifier(classifiers=[pl_text, pl_categorical],
                      use_probas=True,
                      meta_classifier=LogisticRegression())

编辑:这是一些重现问题的代码。'ValueError:发现样本数量不一致的输入变量:[1, 3]'

d = {'cat_1': ['A', 'A', 'B'], 'cat_2': [1, 2, 3], 
'cat_2': ['G', 'H', 'I'], 'cat_3': ['AA', 'DD', 'PP'], 
'cat_4': ['X', 'B', 'V'], 
'text_1': ['the cat sat on the mat', 'the mat sat on the cat', 'sat on the cat mat']} 
features = pd.DataFrame(data=d)

t = [0, 1, 0]
target = pd.DataFrame(data=t)

text_features = ['text_1']
categorical_features = ['cat_1', 'cat_2', 'cat_3', 'cat_4', 'cat_5']

# text pipeline
text_steps = [('feature extractor', SelectColumnsTransfomer(text_features)),
              ('tf-idf', vectoriser),
              ('classifier', mlp_clf)]

# categorical pipeline
categorical_steps = [('feature extractor', 
SelectColumnsTransfomer(categorical_features)),
                 ('label encode', le),
                 ('classifier', rf_clf)]

pl_text = Pipeline(text_steps)
pl_categorical = Pipeline(categorical_steps)

pl_text.fit(features, target)

from mlxtend.classifier import StackingCVClassifier
sclf = StackingCVClassifier(classifiers=[pl_text, pl_categorical],
                          use_probas=True,
                          meta_classifier=LogisticRegression())

sclf.fit(features, target)
4

1 回答 1

2

好的,我设法通过将 text_features = ['text_1'] 替换为 text_features = 'text_1'

基本上,当您将 ['text_1'] 传递给 SelectColumnsTransfomer 类时,它会返回一个 DataFrame 对象,tfidf 向量化器将其视为一个输入。矢量化器在您的管道中应用 fit_transform 并返回单个值。这个单一的值不能用于预测三个目标值。

如果您传入“text_1”,这将为您提供一个系列,并且矢量化器将正确识别您有三个字符串作为特征。您的文本管道现在可以工作了。

于 2017-11-18T20:46:26.590 回答