我正在 python 中尝试这个朴素贝叶斯分类器:
classifier = nltk.NaiveBayesClassifier.train(train_set)
print "Naive Bayes Accuracy " + str(nltk.classify.accuracy(classifier, test_set)*100)
classifier.show_most_informative_features(5)
我有以下输出:
可以清楚地看到哪些词更多地出现在“重要”类别中,哪些词出现在“垃圾邮件”类别中。但我无法使用这些值。我实际上想要一个如下所示的列表:
[[pass,important],[respective,spam],[investment,spam],[internet,spam],[understands,spam]]
我是 python 的新手,很难弄清楚所有这些,有人可以帮忙吗?我将非常感激。
最佳答案
您可以稍微修改 source code of show_most_informative_features
以满足您的目的。
子列表的第一个元素对应于信息量最大的特征名称,而第二个元素对应于它的标签(更具体地说,标签与比率的分子项相关联)。
辅助函数:
def show_most_informative_features_in_list(classifier, n=10):
"""
Return a nested list of the "most informative" features
used by the classifier along with it's predominant labels
"""
cpdist = classifier._feature_probdist # probability distribution for feature values given labels
feature_list = []
for (fname, fval) in classifier.most_informative_features(n):
def labelprob(l):
return cpdist[l, fname].prob(fval)
labels = sorted([l for l in classifier._labels if fval in cpdist[l, fname].samples()],
key=labelprob)
feature_list.append([fname, labels[-1]])
return feature_list
在 nltk
的正面/负面电影评论语料库训练的分类器上对此进行测试:
show_most_informative_features_in_list(classifier, 10)
产生:
[['outstanding', 'pos'],
['ludicrous', 'neg'],
['avoids', 'pos'],
['astounding', 'pos'],
['idiotic', 'neg'],
['atrocious', 'neg'],
['offbeat', 'pos'],
['fascination', 'pos'],
['symbol', 'pos'],
['animators', 'pos']]
关于python - 将来自 NLTK NaiveBayesClassifier 的信息量最大的特征存储在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42970646/