【问题标题】:NLTK classify interface using trained classifier使用经过训练的分类器的 NLTK 分类界面
【发布时间】:2013-01-20 21:43:57
【问题描述】:

我找到了一小段代码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 并阅读原始帖子中的 cmets,以下为该代码生成 'pos' 或 'neg'(这是一个 'pos')

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

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

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

【问题讨论】:

    标签: python nltk


    【解决方案1】:
    print(classifier.classify(word_feats(['magnificent'])))
    

    产量

    pos
    

    classifier.classify 方法本身不对单个单词进行操作,它基于 特征dict 进行分类。在此示例中,word_feats 将一个句子(单词列表)映射到 dict 的特征。

    这里是 another example(来自 NLTK 书),它使用 NaiveBayesClassifier。通过比较该示例与您发布的示例之间的相似之处和不同之处,您可能会更好地了解如何使用它。

    【讨论】:

      猜你喜欢
      • 2011-06-21
      • 2019-06-19
      • 2014-11-25
      • 2013-07-04
      • 1970-01-01
      • 2018-10-31
      • 2013-04-20
      • 2016-12-05
      • 1970-01-01
      相关资源
      最近更新 更多