Python NLTK 朴素贝叶斯分类器
Python NLTK Naive Bayes Classifier
我正在尝试在具有特征提取函数 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()}
因为我不知道到底是什么错误,因为当我 运行 代码它不想完成执行,所以我停止执行,这里是它停止的地方,所以我'我很确定它在这条线上。我有点困惑,我不知道问题出在格式还是函数输入上。如果有人可以提供帮助,我将不胜感激。
很确定您只需要在 results_all
的格式化 return 语句中包含 "{}_{}:{}".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())
,你会得到一个 无效语法错误 。如果您不确定代码,请保留打印语句!
我正在尝试在具有特征提取函数 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()}
因为我不知道到底是什么错误,因为当我 运行 代码它不想完成执行,所以我停止执行,这里是它停止的地方,所以我'我很确定它在这条线上。我有点困惑,我不知道问题出在格式还是函数输入上。如果有人可以提供帮助,我将不胜感激。
很确定您只需要在 results_all
的格式化 return 语句中包含 "{}_{}:{}".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())
,你会得到一个 无效语法错误 。如果您不确定代码,请保留打印语句!