NLTK准确度:" ValueError:解包的数量太多"

时间:2015-08-10 12:56:15

标签: python nltk text-classification

我试图使用NLTK工具包从Twitter对新电影进行一些情感分析。我已经关注了NLTK' movie_reviews'例如,我已经构建了自己的CategorizedPlaintextCorpusReader对象。当我致电nltk.classify.util.accuracy(classifier, testfeats)时会出现问题。这是代码:

import os
import glob
import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import movie_reviews

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]

trainfeats = negfeats + posfeats

# Building a custom Corpus Reader
tweets = nltk.corpus.reader.CategorizedPlaintextCorpusReader('./tweets', r'.*\.txt', cat_pattern=r'(.*)\.txt')
tweetsids = tweets.fileids()
testfeats = [(word_feats(tweets.words(fileids=[f]))) for f in tweetsids]

print 'Training the classifier'
classifier = NaiveBayesClassifier.train(trainfeats)

for tweet in tweetsids:
        print tweet + ' : ' + classifier.classify(word_feats(tweets.words(tweetsids)))

classifier.show_most_informative_features()

print 'accuracy:', nltk.classify.util.accuracy(classifier, testfeats)

这一切看起来都很好,直到它到达最后一行。那是我收到错误的时候:

>>> nltk.classify.util.accuracy(classifier, testfeats)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/nltk/classify/util.py", line 87, in accuracy
    results = classifier.classify_many([fs for (fs,l) in gold])
ValueError: too many values to unpack

是否有人在代码中看到任何错误?

感谢。

1 个答案:

答案 0 :(得分:1)

错误消息

File "/usr/lib/python2.7/dist-packages/nltk/classify/util.py", line 87, in accuracy
  results = classifier.classify_many([fs for (fs,l) in gold])
ValueError: too many values to unpack

出现是因为gold中的项目无法解压缩为2元组,(fs,l)

[fs for (fs,l) in gold]  # <-- The ValueError is raised here

如果gold等于[(1,2,3)],则会出现同样的错误,因为3元组(1,2,3)无法解压缩为2元组(fs,l):< / p>

In [74]: [fs for (fs,l) in [(1,2)]]
Out[74]: [1]
In [73]: [fs for (fs,l) in [(1,2,3)]]
ValueError: too many values to unpack

gold可能会被隐藏在nltk.classify.util.accuracy的实现中,但这暗示您的输入classifiertestfeats是错误的&#34;形状&#34 ;

classifer,没有问题,因为调用accuracy(classifier, trainfeats) 工作原理:

In [61]: print 'accuracy:', nltk.classify.util.accuracy(classifier, trainfeats)
accuracy: 0.9675

问题必须在testfeats

trainfeatstestfeats进行比较。 trainfeats[0]是一个包含字典和分类的2元组:

In [63]: trainfeats[0]
Out[63]: 
({u'!': True,
  u'"': True,
  u'&': True,
  ...
  u'years': True,
  u'you': True,
  u'your': True},
 'neg')           # <---  Notice the classification, 'neg'

testfeats[0]只是一个词典,word_feats(tweets.words(fileids=[f]))

testfeats = [(word_feats(tweets.words(fileids=[f]))) for f in tweetsids]

因此,要解决此问题,您需要定义testfeats,使其更像trainfeats - word_feats返回的每个字典必须与分类配对。