【问题标题】:Python NLTK Classifier.train(trainfeats)... ValueError: need more than 1 value to unpackPython NLTK Classifier.train(trainfeats)... ValueError: need more than 1 value to unpack
【发布时间】:2016-11-10 16:41:34
【问题描述】:
def word_feats(words):
     return dict([(word, True) for word in words])

for tweet in negTweets:
     words = re.findall(r"[\w']+|[.,!?;]", tweet) #splits the tweet into words
     negwords = [(word_feats(words), 'neg')] #tag the words with feature
     negfeats.append(negwords) #add the words to the feature list
for tweet in posTweets:
     words = re.findall(r"[\w']+|[.,!?;]", tweet)
     poswords = [(word_feats(words), 'pos')]
     posfeats.append(poswords)

negcutoff = len(negfeats)*3/4 #take 3/4ths of the words
poscutoff = len(posfeats)*3/4

trainfeats = negfeats[:negcutoff] + posfeats[:poscutoff] #assemble the train set
testfeats = negfeats[negcutoff:] + posfeats[poscutoff:]

classifier = NaiveBayesClassifier.train(trainfeats)
print 'accuracy:', nltk.classify.util.accuracy(classifier, testfeats)
classifier.show_most_informative_features()

运行此代码时出现以下错误...

File "C:\Python27\lib\nltk\classify\naivebayes.py", line 191, in train

for featureset, label in labeled_featuresets:

ValueError: need more than 1 value to unpack

错误来自分类器 = NaiveBayesClassifier.train(trainfeats) 行,我不知道为什么。我以前做过类似的事情,我的 trainfeats 接缝的格式与当时的格式相同……下面列出了格式中的一个示例……

[[({'me': True, 'af': True, 'this': True, 'joy': True, 'high': True, 'hookah': True, 'got': True}, 'pos')]]

我的 trainfeats 还需要什么其他值来创建分类器?强调文本

【问题讨论】:

  • 括号中有两组括号:一个列表,其唯一元素是一个列表,其唯一元素是一个元组。该元组包含一个字典和一个字符串。也许你的包装纸太多,所以拆包时只能看到一件。

标签: python machine-learning nltk sentiment-analysis nl-classifier


【解决方案1】:

@Prune 的评论是正确的:您的 labeled_featuresets 应该是一个对序列(双元素列表或元组):每个数据点的特征字典和类别。相反,trainfeats 中的每个元素都是一个包含一个元素的列表:这两个元素的元组。丢失两个特征构建循环中的方括号,这部分应该可以正常工作。例如,

negwords = (word_feats(words), 'neg')
negfeats.append(negwords)

还有两件事:考虑使用nltk.word_tokenize() 而不是自己进行标记化。你应该随机化你的训练数据的顺序,例如random.scramble(trainfeats)

【讨论】:

    猜你喜欢
    • 2016-03-03
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多