Pipeline using multiple columns

我有一个二分类问题。我的数据集包含不同类型的列:二元(0或1)或文本(来自电子邮件的文本)。我有超过40列的数据。

一个例子可能是这样的:

Text                             is_it_capital?     is_it_upper?      contains_num?   Label
an example of text                      0                  0               0            0
ANOTHER example of text                 1                  1               0            1
What's happening?Let's talk at 5        1                  0               1            1

我正在尝试使用管道进行预测。然而,我已经对一些列进行了编码(如is_it_capital?等),这并没有对我有太大帮助,因为我不知道如何将这些列(特征)添加到我的管道中。它们都是数值型的,值为1或0(通过numerical_columns = train_set.select_dtypes(include=[np.number])检查)。

如果我没有预先编码这些列,可能使用FeatureUnion会是一个不错的解决方案;但在这种情况下,我不知道该如何进行。

我尝试了如下方法:

  nb_pipeline = Pipeline([            ('NBCV',extract_func. tf_idf_n),            ('nb_clf',MultinomialNB())])    nb_pipeline.fit(train_set,train_set['Label']) # 我考虑了整个训练集    predicted_nb = nb_pipeline.predict(test_set)    np.mean(predicted_nb == test_set['Label'])

但我得到了以下错误:

ValueError: Found input variables with inconsistent numbers of samples: [30, 4394]

我使用train_test_split将数据集分为训练集(80%)和测试集(20%)。y仅包含Label,而X包含我示例中的所有其他列。分割数据集后,我按如下方式连接X_trainy_train

train_set= pd.concat([X_train, y_train], axis=1)
test_set = pd.concat([X_test, y_test], axis=1)

完整的错误跟踪:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-50-bab0cc0a9f07> in <module>
      6         ('nb_clf',MultinomialNB())])
      7 ----> 8 nb_pipeline.fit(train_set.drop('Label', axis=1), train_set['Label'])
      9 predicted_nb = nb_pipeline.predict(test_set.drop('Label', axis=1))
     10 np.mean(predicted_nb == test_set['Label'])
/anaconda3/lib/python3.7/site-packages/sklearn/pipeline.py in fit(self, X, y, **fit_params)
    333             if self._final_estimator != 'passthrough':
    334                 fit_params_last_step = fit_params_steps[self.steps[-1][0]]
--> 335                 self._final_estimator.fit(Xt, y, **fit_params_last_step)
    336
    337         return self
/anaconda3/lib/python3.7/site-packages/sklearn/naive_bayes.py in fit(self, X, y, sample_weight)
    613         self : object
    614         """
--> 615         X, y = self._check_X_y(X, y)
    616         _, n_features = X.shape
    617         self.n_features_ = n_features
/anaconda3/lib/python3.7/site-packages/sklearn/naive_bayes.py in _check_X_y(self, X, y)
    478
    479     def _check_X_y(self, X, y):
--> 480         return self._validate_data(X, y, accept_sparse='csr')
    481
    482     def _update_class_log_prior(self, class_prior=None):
/anaconda3/lib/python3.7/site-packages/sklearn/base.py in _validate_data(self, X, y, reset, validate_separately, **check_params)
    430                 y = check_array(y, **check_y_params)
    431             else:
--> 432                 X, y = check_X_y(X, y, **check_params)
    433             out = X, y
    434
/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in inner_f(*args, **kwargs)
     70                           FutureWarning)
     71         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 72         return f(**kwargs)
     73     return inner_f
     74
/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator)
    810         y = y.astype(np.float64)
    811
--> 812     check_consistent_length(X, y)
    813
    814     return X, y
/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
    254     if len(uniques) > 1:
    255         raise ValueError("Found input variables with inconsistent numbers of"
--> 256                          " samples: %r" % [int(l) for l in lengths])
    257
    258
ValueError: Found input variables with inconsistent numbers of samples: [29, 4394]

回答:

从错误跟踪中可以看到,tfidf转换器完成了工作,而NB模型出现了问题。我怀疑tfidf没有按你期望的方式工作,因为它将整个数据框视为要编码的的可迭代对象;所以它认为只有29个“文档”,因此NB模型看到29行训练数据和4394个标签。

我认为以下方法应该能按你期望的方式工作。

ct = ColumnTransformer(    transformers=[('tfidf', extract_func.tf_idf_n, 'Text')],    remainder='passthrough',)
nb_pipeline = Pipeline([    ('preproc', ct),    ('nb_clf', MultinomialNB())])
nb_pipeline.fit(train_set.drop('Label', axis=1), train_set['Label'])

Related Posts

如何对SVC进行超参数调优?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

如何在初始训练后向模型添加训练数据?

我想在我的scikit-learn模型已经训练完成后再…

使用Google Cloud Function并行运行带有不同用户参数的相同训练作业

我正在寻找一种方法来并行运行带有不同用户参数的相同训练…

加载Keras模型,TypeError: ‘module’ object is not callable

我已经在StackOverflow上搜索并阅读了文档,…

在计算KNN填补方法中特定列中NaN值的”距离平均值”时

当我从头开始实现KNN填补方法来处理缺失数据时,我遇到…

使用巨大的S3 CSV文件或直接从预处理的关系型或NoSQL数据库获取数据的机器学习训练/测试工作

已关闭。此问题需要更多细节或更清晰的说明。目前不接受回…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注