python - 当我尝试使用朴素贝叶斯/Python进行预测时出现尺寸不匹配错误
问题描述
我创建了一个情绪脚本并使用朴素贝叶斯对评论进行分类。我训练并测试了我的模型并将其保存在 Pickle 对象中。现在我想在一个新数据集上执行我的预测,但我总是收到以下错误消息
raise ValueError('dimension mismatch') ValueError: dimension mismatch
它弹出在这一行:
preds = nb.predict(transformed_review)[0]
谁能告诉我我做错了什么?我不明白这个错误。
这是我的脚本:
sno = SnowballStemmer("german")
stopwords = [word.decode('utf-8-sig') for word in stopwords.words('german')]
ta_review_files = glob.glob('C:/users/Documents/review?*.CSV')
review_akt_doc = max(ta_review_files, key=os.path.getctime
ta_review = pd.read_csv(review_akt_doc)
sentiment_de_class= ta_review
x = sentiment_de_class['REV']
y = sentiment_de_class['SENTIMENT']
def text_process(text):
nopunc = [char for char in text.decode('utf8') if char not in string.punctuation]
nopunc = ''.join(nopunc)
noDig = ''.join(filter(lambda x: not x.isdigit(), nopunc))
## stemming
stemmi = u''.join(sno.stem(unicode(x)) for x in noDig)
stop = [word for word in stemmi.split() if word.lower() not in stopwords]
stop = ' '.join(stop)
return [word for word in stemmi.split() if word.lower() not in stopwords]
######################
# Matrix
######################
bow_transformer = CountVectorizer(analyzer=text_process).fit(x)
x = bow_transformer.transform(x)
######################
# Train and test data
######################
x_train, x_test, y_train, y_test = train_test_split(x,y, random_state=101)
print 'starting training ..'
######################
## first use
######################
#nb = MultinomialNB().fit(x_train,y_train)
#file = open(sentiment_MNB_path + 'sentiment_MNB_model.pickle', 'wb')
## dump information to that file
#pickle.dump(nb, file)
######################
## after train
######################
file = open(sentiment_MNB_path + 'sentiment_MNB_model.pickle', 'rb')
nb = pickle.load(file)
predis = []
######################
# Classify
######################
cols = ['SENTIMENT_CLASSIFY']
for sentiment in sentiment_de_class['REV']:
transformed_review = bow_transformer.transform([sentiment])
preds = nb.predict(transformed_review)[0] ##right here I get the error
predis.append(preds)
df = pd.DataFrame(predis, columns=cols)
解决方案
您还需要保存 CountVectorizer 对象,就像保存nb
.
你打电话时
CountVectorizer(analyzer=text_process).fit(x)
您正在对新数据重新训练 CountVectorizer,因此它找到的特征(词汇)将与训练时不同,因此在nb
早期特征上训练的保存的会抱怨维度不匹配。
最好将它们腌制在不同的文件中,但如果您愿意,可以将它们保存在同一个文件中。
在同一个对象中腌制两者:
file = open(sentiment_MNB_path + 'sentiment_MNB_model.pickle', 'wb')
pickle.dump(bow_transformer, file) <=== Add this
pickle.dump(nb, file)
在下一次通话中阅读两者:
file = open(sentiment_MNB_path + 'sentiment_MNB_model.pickle', 'rb')
bow_transformer = pickle.load(file)
nb = pickle.load(file)
请查看此答案以获取更多详细信息:https ://stackoverflow.com/a/15463472/3374996
推荐阅读
- networking - 无法将 Route53 记录定向到新服务器
- python - 如何用字典调用文件并将其传递给类对象?
- kotlin - Rx Java,订阅({})与订阅{}有什么区别?
- c# - windows explorer 看不到由 c# app File.WriteAllLines 编写的文件
- ios - 离开后从 Tab Bar Controller 回收内存
- ruby-on-rails - Capybara 截图格式
- excel - 选择后从列表中删除项目
- c++ - 如何在 C++ 中从文件流中分离数据
- mysql - Mysql:选择id,然后* on id比选择*快很多。为什么?
- cakephp - 预期类型“Cake\Datasource\EntityInterface”。找到“应用\模型\表\实体”