使用训练好的分类器的NLTK分类接口

2 投票
1 回答
6395 浏览
提问于 2025-04-17 14:52

我找到了一段代码,链接在这里

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的反馈和一些深入的研究,链接在这里,还有阅读原帖的评论后,下面的代码可以返回'pos'或'neg'(这个是'pos')

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

而这段代码可以评估这个单词是'pos'还是'neg'

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

1 个回答

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

产生

pos

classifier.classify这个方法并不是直接对每个单词进行操作,而是根据一个包含特征dict来进行分类。在这个例子中,word_feats把一个句子(也就是一串单词)转换成一个特征的dict

这里有一个来自NLTK书籍的另一个例子,它使用了NaiveBayesClassifier。通过比较这个例子和你提到的例子之间的相似和不同之处,你可能会更好地理解它是如何使用的。

撰写回答