我正在尝试让我的MultinomialNB工作。我在训练和测试集上使用CountVectorizer,当然在两个setz中都有不同的单词。所以我明白了,为什么错误
ValueError: dimension mismatch
发生了,但我不知道如何解决它。我按照其他帖子(SciPy and scikit-learn - ValueError: Dimension mismatch)的建议尝试了CountVectorizer().transform
而不是CountVectorizer().fit_transform
,但这只是给了我
NotFittedError: CountVectorizer - Vocabulary wasn't fitted.
如何正确使用CountVectorizer?
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.cross_validation import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report
import sklearn.feature_extraction
df = data
y = df["meal_parent_category"]
X = df['name_cleaned']
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)
X_train = CountVectorizer().fit_transform(X_train)
X_test = CountVectorizer().fit_transform(X_test)
algo = MultinomialNB()
algo.fit(X_train,y_train)
y = algo.predict(X_test)
print(classification_report(y_test,y_pred))
答案 0 :(得分:1)
好的,所以在问了这个问题之后我就明白了:) 这是词汇表的解决方案:
df = train
y = df["meal_parent_category_cleaned"]
X = df['name_cleaned']
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)
vectorizer_train = CountVectorizer()
X_train = vectorizer_train.fit_transform(X_train)
vectorizer_test = CountVectorizer(vocabulary=vectorizer_train.vocabulary_)
X_test = vectorizer_test.transform(X_test)
algo = MultinomialNB()
algo.fit(X_train,y_train)
y_pred = algo.predict(X_test)
print(classification_report(y_test,y_pred))