使用经过训练的分类器进行 NLTK 分类接口

2024-01-10

我找到了一小块代码here http://streamhacker.com/2010/05/10/text-classification-sentiment-analysis-naive-bayes-classifier/:

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 http://nltk.googlecode.com/svn/trunk/doc/api/nltk.probability.ProbDistI-class.html#samples并阅读原始帖子的评论,以下代码会产生“pos”或“neg”(这是一个“pos”)

print(classifier.classify(word_feats(['magnificent'])))

这会产生单词“pos”或“neg”的评估

print(classifier.prob_classify(word_feats(['magnificent'])).prob('neg'))

print(classifier.classify(word_feats(['magnificent'])))

yields

pos

The classifier.classify方法本身不对单个单词进行操作,它基于dict of features。在这个例子中,word_feats将句子(单词列表)映射到dict的功能。

Here is 另一个例子 http://nltk.org/book/ch06.html(来自 NLTK 书)它使用NaiveBayesClassifier。通过比较该示例与您发布的示例之间的相似点和不同点,您可能会更好地了解如何使用它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用经过训练的分类器进行 NLTK 分类接口 的相关文章

随机推荐