我找到了here的这一小块代码:
import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import movie_reviews
from nltk.corpus import stopwords
def word_feats(words):
return dict([(word, True) for word in words])
negids = movie_reviews.fileids('neg')
posids = movie_reviews.fileids('pos')
negfeats = [(word_feats(movie_reviews.words(fileids=[f])), 'neg') for f in negids]
posfeats = [(word_feats(movie_reviews.words(fileids=[f])), 'pos') for f in posids]
negcutoff = len(negfeats)*3/4
poscutoff = len(posfeats)*3/4
trainfeats = negfeats[:negcutoff] + posfeats[:poscutoff]
testfeats = negfeats[negcutoff:] + posfeats[poscutoff:]
print 'train on %d instances, test on %d instances' % (len(trainfeats), len(testfeats))
classifier = NaiveBayesClassifier.train(trainfeats)
print 'accuracy:', nltk.classify.util.accuracy(classifier, testfeats)
classifier.show_most_informative_features()
但是,我如何对可能在语料库中的随机单词进行分类。
classifier.classify('magnificent')
不起作用。它需要某种物体吗?
非常感谢。
编辑:感谢@ unutbu的反馈和一些挖掘here并阅读原始帖子的评论,以下为此代码产生'pos'或'neg'(这个是'pos')
print(classifier.classify(word_feats(['magnificent'])))
这会产生对'pos'或'neg'
这个词的评价print(classifier.prob_classify(word_feats(['magnificent'])).prob('neg'))
答案 0 :(得分:1)
print(classifier.classify(word_feats(['magnificent'])))
产量
pos
classifier.classify
方法不对单个单词本身进行操作,而是根据功能的dict
进行分类。在此示例中,word_feats
将句子(单词列表)映射到dict
个要素。
以下是使用NaiveBayesClassifier
的{{3}}(来自NLTK书籍)。通过比较该示例与您发布的示例之间的相似和不同之处,您可以更好地了解如何使用该示例。