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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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