python - 将来自 NLTK NaiveBayesClassifier 的信息量最大的特征存储在列表中

标签 python scikit-learn classification nltk naivebayes

我正在 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)

我有以下输出:

Console Output

可以清楚地看到哪些词更多地出现在“重要”类别中,哪些词出现在“垃圾邮件”类别中。但我无法使用这些值。我实际上想要一个如下所示的列表:

[[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/

相关文章:

python - 如何在 scikit-learn 中的 tfidf 之后查看术语文档矩阵的前 n 个条目

python - Scikits-学习 : Use custom vocabulary together with Pipeline

python-3.x - 为什么使用 sklearn 库随机生成的数据精度较低

python - 无法使用 Python 检测乱码名称

python - 预测类别或类别概率?

python - 当将 text() 与 python-escpos 一起使用时,我得到 [Errno None] 和关键错误 = 1 (windows 10)

Python:从列表中删除具有相同楼层函数的数字

python - 如何在 Selenium 中保存 Whatsapp 网络 session ?

python - 如何针对 Django 数据迁移运行测试?

machine-learning - 为什么 ID3 算法在 Weka 的 UCI Mushroom 数据集上不起作用?