交叉验证错误

时间:2016-03-14 14:33:28

标签: python scikit-learn

我正在尝试估计nltk电影评论语料库的朴素贝叶斯分类的准确性。

from nltk.corpus import movie_reviews
import random
import nltk
from sklearn import cross_validation
from nltk.corpus import stopwords
import string
from nltk.classify import apply_features

def document_features(document):
    document_words = set(document)
    features = {}
    for word in unigrams:
        features['contains({})'.format(word)] = (word in document_words)
    return features

documents = [(list(movie_reviews.words(fileid)), category)
             for category in movie_reviews.categories()
             for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)
stop = stopwords.words('english')
all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words() if w.lower() not in stop and w.lower() not in string.punctuation)
unigrams = list(all_words)[:200]
featuresets = [(document_features(d), c) for (d,c) in documents]

我正在尝试进行10倍的交叉验证,我从sklearn那里得到了一个例子。

training_set = nltk.classify.apply_features(featuresets, documents)
cv = cross_validation.KFold(len(training_set), n_folds=10, shuffle=True, random_state=None)

for traincv, testcv in cv:
    classifier = nltk.NaiveBayesClassifier.train(training_set[traincv[0]:traincv[len(traincv)-1]])
    result = nltk.classify.util.accuracy(classifier, training_set[testcv[0]:testcv[len(testcv)-1]])
    print 'Accuracy:', result

但我在行

中收到错误
classifier = nltk.NaiveBayesClassifier.train(training_set[traincv[0]:traincv[len(traincv)-1]])

'列表'对象不可调用

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:1)

实际错误在于这一行:

training_set = nltk.classify.apply_features(featuresets, documents)

featuresets是Python抱怨的列表。

来自nltk.classify.apply_features的文档:

  

apply_features(feature_func,toks,label = None)

     

使用LazyMap类构建类似惰性列表   与map(feature_func, toks)类似的对象。在   特别是,如果labeled=False,则返回类似列表   对象的值等于:

[feature_func(tok) for tok in toks]
     

如果labeled=True,则返回类似列表的对象的值   等于:

[(feature_func(tok), label) for (tok, label) in toks]

以与map类似的方式行事,此函数需要函数(特征提取器)作为第一个参数,该参数将应用于传递的列表的每个元素(文档)作为第二个论点。它返回一个LazyMap,它根据需要应用该函数以节省内存。

但是您已将功能集列表传递给apply_features而不是功能提取器功能。因此,有两种可能的解决方案可以让您的工作像您希望的那样:

  1. 放弃training_set并改为使用featuresets
  2. 放弃featuresets并使用training_set = nltk.classify.apply_features(document_features, documents, True)(请注意第三个参数)。
  3. 我建议使用第二个选项,因为它不会构建内存中所有文档的功能列表。

相关问题