【问题标题】:TfIdf matrix returns wrong number of features for BernoulliNBTfIdf 矩阵为 BernoulliNB 返回错误的特征数量
【发布时间】:2016-01-01 22:02:49
【问题描述】:

使用 python lib sklearn,我尝试从训练集中提取特征,并用这些数据拟合 BernoulliNB 分类器。

在训练完分类器之后,我想预测(分类)一些新的测试数据。 不幸的是,我收到了这个错误:

Traceback (most recent call last):
File "sentiment_analysis.py", line 45, in <module> main()
File "sentiment_analysis.py", line 41, in main
  prediction = classifier.predict(tfidf_data)
File "\Python27\lib\site-packages\sklearn\naive_bayes.py", line 64, in predict
  jll = self._joint_log_likelihood(X)
File "\Python27\lib\site-packages\sklearn\naive_bayes.py", line 724, in _joint_log_likelihood
  % (n_features, n_features_X))
ValueError: Expected input with 4773 features, got 13006 instead

这是我的代码:

#Train the Classifier
data,target = load_file('validation/validation_set_5.csv')
tf_idf = preprocess(data)
classifier = BernoulliNB().fit(tf_idf, target)

#Predict test data
count_vectorizer = CountVectorizer(binary='true')
test = count_vectorizer.fit_transform(test)
tfidf_data = TfidfTransformer(use_idf=False).fit_transform(test)
prediction = classifier.predict(tfidf_data)

【问题讨论】:

    标签: python scikit-learn tf-idf naivebayes


    【解决方案1】:

    这就是您出现此错误的原因:

    test = count_vectorizer.fit_transform(test)
    tfidf_data = TfidfTransformer(use_idf=False).fit_transform(test)
    

    你应该在这里只使用安装在火车上的旧变压器(CountVectorizer 和 TfidfTransformer 是你的变压器)。

    fit_transform

    意味着您将这些转换器安装在新集合上,丢失有关旧拟合的所有信息,然后使用此转换器转换“测试”(在新样本上学习,并具有不同的特征集)。因此,它返回转换为新特征集的测试集,与训练集中使用的旧特征集不兼容。要解决此问题,您应该在旧变压器上使用 transform(不是 fit_transform)方法,并安装在训练集上。

    你应该这样写:

    test = old_count_vectorizer.transform(test)
    tfidf_data = old_tfidf_transformer.transform(test)
    

    【讨论】:

      猜你喜欢
      • 2016-09-14
      • 2022-01-23
      • 2023-03-14
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多