【问题标题】:Python NLTK Naive Bayes ClassifierPython NLTK 朴素贝叶斯分类器
【发布时间】:2016-09-28 14:14:04
【问题描述】:

我正在尝试在具有正面和负面类别的数据集上使用特征提取函数 features_all() 实现 NLTK 朴素贝叶斯分类器。当我运行代码时,我在 features_all() 函数中的一行出现错误。

朴素贝叶斯代码:

import nltk
import random
from nltk.corpus import stopwords
import nltk.classify.util
from nltk.corpus.reader import CategorizedPlaintextCorpusReader
import re

from feature_extractors import features_all #function for features extraction

path = "/.../all kom"

reader = CategorizedPlaintextCorpusReader(path,r'.*\.txt',cat_pattern=r'(^\w..)/*')

po=reader.sents(categories=['pos']) #tokenize 
ne=reader.sents(categories=['neg'])

labeled_sentiments = ([(n, 'positive') for n in po] + [(n, 'negative') for n in ne])

size = int(len(labeled_sentiments) * 0.9) #for separating training set in 90:10
random.shuffle(labeled_sentiments)

featuresets = [(features_all(n), sentiment) for (n, sentiment) in labeled_sentiments]
train_set = featuresets[:size]
test_set = featuresets[size:]

#Naive Bayes
classifier = nltk.NaiveBayesClassifier.train(train_set)
#test
print(classifier.classify(features_all('great')))
print(classifier.classify(features_all('bad')))
print('Accuracy for Naive Bayes: ',nltk.classify.accuracy(classifier,   test_set))
print(classifier.show_most_informative_features(15))

features_all() 函数:

def features_all(dat):

    f_all_dict=open('all_dict.txt','r',encoding='utf-8').read()

    f = literal_eval(f_all_dict)

    result_all = {} 

    for word in f.items():
        result_all = {"{}_{}".format(word, suffix): pol * dat.count(word) for word, (suffix, pol) in f.items()} #here is where I get the error

    if len(f) == len(result_all):
       return result_all
    else:
       return None

而 features_all() 给出的输出类似于(示例):

great_pos:1, bad_neg:1

all_dict.txt 看起来像这样:

"great":("pos",2),"bad":("neg",2)

我在线收到错误 result_all = {"{}_{}".format(word, suffix): pol * dat.count(word) for word, (suffix, pol) in f.items()}

因为我不知道到底是什么错误,因为当我运行代码时它不想完成执行,所以我停止执行,这里是它停止的地方,所以我很确定它在这个线。我有点困惑,我不知道问题出在格式还是函数输入上。如果有人可以提供帮助,我将不胜感激。

【问题讨论】:

  • 你试过用这个吗? "{}_{}:{}".format(word, suffix, pol * dat.count(word))

标签: python-3.x nltk corpus


【解决方案1】:

很确定您只需要在results_all 的格式化返回语句中包含"{}_{}:{}".format(word, suffix, pol * dat.count(word)) for word, (suffix, pol) in f.items()。检查您的代码是否有效的一个非常简单的方法是检查您是否始终以您期望的格式获得输出!如果你只是做了print("{}_{}".format(word, suffix): pol * dat.count(word) for word, (suffix, pol) in f.items()),你会得到一个Invalid Syntax error。如果您不确定代码,请保留打印语句!

【讨论】:

  • 很高兴我能帮上忙。喜欢我的回答就点个赞吧! :)
猜你喜欢
  • 2012-12-05
  • 2015-12-20
  • 2017-04-19
  • 2014-01-13
  • 2017-08-30
  • 2012-04-01
  • 2017-01-10
  • 2013-04-19
相关资源
最近更新 更多