AttributeError: ‘NoneType’ object has no attribute ‘items’ for classifier = nltk.NaiveBayesClassifier.train(training_set)

我在运行代码时遇到了这个错误:AttributeError: ‘NoneType’ object has no attribute ‘items’。以下是我的代码:

import nltk
import random
from nltk.corpus import movie_reviews
from nltk.classify import NaiveBayesClassifier
from nltk.probability import FreqDist
documents = [ (list(movie_reviews.words(fileid)), category)
            for category in movie_reviews.categories()
                for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)
all_words = []
for w in movie_reviews.words():
    all_words.append(w.lower())
all_words = nltk.FreqDist(all_words)
word_features = list(all_words.keys())[:3000]
print (word_features)
def find_features(documents):
    words = set(documents)
    features = {}
    for w in word_features:
        features[w] = (w in words)
featuresets = [(find_features(rev), category) for (rev, category) in documents]
training_set = featuresets[:1500]
testing_set = featuresets[1500:]
classifier = nltk.NaiveBayesClassifier.train(training_set)
print ("Naive Bayes Classifier Algo Accuracy: ",nltk.classify.accuracy(classifier, testing_set))*100)
classifier.show_most_informative_features(15)

我一直在按照一个视频教程进行学习,教程中的代码与这里的一样。在教程中运行正常,但在我的环境中却显示以下错误:

AttributeError: 'NoneType' object has no attribute 'items'

错误发生在以下这行代码:

classifier = nltk.NaiveBayesClassifier.train(training_set)

这是什么原因?有什么解决方案吗?


回答:

您没有从函数中返回列表。在您的 find_feature 函数中使用以下代码:

def find_features(documents):
    words = set(documents)
    features = {}
    for w in word_features:
        features[w] = (w in words)
    return features #添加这一行

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注