CountVectorizer MultinomialNB 中的维度不匹配错误

dimension mismatch error in CountVectorizer MultinomialNB

在我提出这个问题之前,我不得不说我已经彻底阅读了这个论坛上超过 15 个类似的主题,每个主题都有不同的建议,但所有这些都无法让我正确。

好的,所以我将我的 'spam email' 文本数据(最初是 csv 格式)分成训练集和测试集,使用 CountVectorizer 及其 'fit_transform' 函数来拟合语料库的词汇并提取单词从文本中计算特征。然后我应用 MultinomialNB() 从训练集中学习并对测试集进行预测。这是我的代码(简化):

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.cross_validation import train_test_split
from sklearn.naive_bayes import MultinomialNB

# loading data 
# data contains two columns ('text', 'target')

spam = pd.read_csv('spam.csv')
spam['target'] = np.where(spam_data['target']=='spam',1,0)

# split data
X_train, X_test, y_train, y_test = train_test_split(spam_data['text'], spam_data['target'], random_state=0) 

# fit vocabulary and extract word count features
cv = CountVectorizer()
X_traincv = cv.fit_transform(X_train)  
X_testcv = cv.fit_transform(X_test)

# learn and predict using MultinomialNB
clfNB = MultinomialNB(alpha=0.1)
clfNB.fit(X_traincv, y_train)

# so far so good, but when I predict on X_testcv
y_pred = algo.predict(X_testcv)

# Python throws me an error: dimension mismatch

我从之前的问题线程中收集到的建议是 (1) 在 X_test 上仅使用 .transform(),或 (2) 确定原始垃圾邮件数据中的每一行是否为字符串格式(是,它们是),或者 (3) 在 X_test 上什么都不做。但是他们都没有按铃,Python 一直给我 'dimension mismatch' 错误。折腾了 4 个小时后,我不得不屈服于 Whosebug。如果有人能启发我,我将不胜感激。只想知道我的代码出了什么问题以及如何正确设置维度。

谢谢。

顺便说一句,原始数据条目如下所示

_

                                         test   target
0 Go until jurong point, crazy.. Available only    0
1 Ok lar... Joking wif u oni...                    0
2 Free entry in 2 a wkly comp to win FA Cup fina   1
3 U dun say so early hor... U c already then say   0
4 Nah I don't think he goes to usf, he lives aro   0
5 FreeMsg Hey there darling it's been 3 week's n   1
6 WINNER!! As a valued network customer you have   1

您的 CountVectorizer 已经用训练数据拟合。所以对于你的测试数据,你只想调用transform(),而不是fit_transform()

否则,如果您对测试数据再次使用 fit_transform(),您将根据测试数据的独特词汇表获得不同的列。所以只适合训练一次。

X_testcv = cv.transform(X_test)