问题描述
我将使用n-gram
在样本数据集上训练分类器。我搜索了相关内容,并在下面编写了代码。因为我是python的初学者,所以我有两个问题。
1-为什么词典要具有这种“ True”结构(标有注释)?这与朴素贝叶斯分类器输入有关吗?
2-您建议使用哪个分类器执行此任务?
欢迎其他任何缩短代码的建议:)。
from nltk.corpus import movie_reviews
from nltk.corpus import stopwords
from nltk import ngrams
from nltk.classify import NaiveBayesClassifier
import nltk.classify.util
stoplist = set(stopwords.words("english"))
def stopword_removal(words):
useful_words = [word for word in words if word not in stoplist]
return useful_words
def create_ngram_features(words,n):
ngram_vocab = ngrams(words,n)
my_dict = dict([(ng,True) for ng in ngram_vocab]) # HERE
return my_dict
for n in [1,2]:
positive_data = []
for fileid in movie_reviews.fileids('pos'):
words = stopword_removal(movie_reviews.words(fileid))
positive_data.append((create_ngram_features(words,n),"positive"))
print('\n\n---------- Positive Data Sample----------\n',positive_data[0])
negative_data = []
for fileid in movie_reviews.fileids('neg'):
words = stopword_removal(movie_reviews.words(fileid))
negative_data.append((create_ngram_features(words,"negative"))
print('\n\n---------- Negative Data Sample ----------\n',negative_data[0])
train_set = positive_data[:100] + negative_data[:100]
test_set = positive_data[100:] + negative_data[100:]
classifier = NaiveBayesClassifier.train(train_set)
accuracy = nltk.classify.util.accuracy(classifier,test_set)
print('\n',str(n)+'-gram accuracy:',accuracy)
解决方法
在进行数据训练之前,您需要将n元语法转换为大小为
朴素贝叶斯分类器是最简单的分类器。但是它在嘈杂的数据上效果不好,并且需要平衡的数据类分布进行训练。您可以尝试使用任何提升分类器,例如,梯度提升机或支持向量机。
所有分类器和转换器都可以在scikit-learn
库中找到。