嘿,我正在尝试使用朴素贝叶斯分类器对某些文本进行分类。我正在使用 NLTK。每当我使用classify() 方法测试分类器时,它总是为第一项返回正确的分类,并为我分类的每一行文本返回相同的分类。以下是我的代码:
from nltk.corpus import movie_reviews
from nltk.tokenize import word_tokenize
import nltk
import random
import nltk.data
documents = [(list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)
all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())
word_features = all_words.keys()[:2000]
def bag_of_words(words):
return dict([word,True] for word in words)
def document_features(document):
document_words = set(document)
features = {}
for word in word_features:
features['contains(%s)' % word] = (word in document_words)
return features
featuresets = [(document_features(d), c) for (d,c) in documents]
train_set, test_set = featuresets[100:], featuresets[:100]
classifier = nltk.NaiveBayesClassifier.train(train_set)
text1="i love this city"
text2="i hate this city"
feats1=bag_of_words(word_tokenize(text1))
feats2=bag_of_words(word_tokenize(text2))
print classifier.classify(feats1)
print classifier.classify(feats2)
此代码将打印 pos 两次,就好像我翻转了代码的最后 2 行一样,它将打印 neg 两次。任何人都可以帮忙吗?