使用不在训练集中的一些词进行分类预测(朴素贝叶斯)

我创建了一个朴素贝叶斯模型来预测结果是“负面”还是“正面”。我遇到的问题是在一组新的数据上运行模型时,其中一些词不在模型中。我在预测新数据集时收到的错误是:

ValueError: Expected input with 6 features, got 4 instead

我读到我需要在模型中加入拉普拉斯平滑器,而Bernoulli()已经有一个默认的alpha值为1。我还能做些什么来修复我的错误?谢谢

from nltk.corpus import stopwordsfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.naive_bayes import BernoulliNBfrom sklearn import cross_validationfrom sklearn.metrics import classification_reportimport numpy as npfrom sklearn.metrics import accuracy_scoreimport textblob as TextBlob#scikitcomments = list(['happy','sad','this is negative','this is positive', 'i like this', 'why do i hate this'])classes = list(['positive','negative','negative','positive','positive','negative'])# preprocess creates the term frequency matrix for the review data setstop = stopwords.words('english')count_vectorizer = CountVectorizer(analyzer =u'word',stop_words = stop, ngram_range=(1, 3))comments = count_vectorizer.fit_transform(comments)tfidf_comments = TfidfTransformer(use_idf=True).fit_transform(comments)# preparing data for split validation. 60% training, 40% testdata_train,data_test,target_train,target_test = cross_validation.train_test_split(tfidf_comments,classes,test_size=0.2,random_state=43)classifier = BernoulliNB().fit(data_train,target_train)#new datacomments_new = list(['positive','zebra','george','nothing'])comments_new = count_vectorizer.fit_transform(comments_new)tfidf_comments_new = TfidfTransformer(use_idf=True).fit_transform(comments_new)classifier.predict(tfidf_comments_new)

回答:

你不应该在新数据上使用fit_transform来拟合一个新的估计器,而应该使用之前构建的count_vectorizer,只使用transform。这样会忽略所有不在字典中的词。

我不同意Maxim的观点:虽然这对CountVectorizer没有影响,但在联合数据集上使用TfidfTransformer会将测试集的信息泄露到训练集中,这是你需要避免的。

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中创建了一个多类分类项目。该项目可以对…

发表回复

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