如何使用n-gram完成分类任务?

问题描述

我将使用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元语法转换为大小为的代码矩阵。例如,文档表示是一个词袋,其中语料词典的每个词/ n个语法在文档中都有其出现频率。

朴素贝叶斯分类器是最简单的分类器。但是它在嘈杂的数据上效果不好,并且需要平衡的数据类分布进行训练。您可以尝试使用任何提升分类器,例如,梯度提升机或支持向量机。

所有分类器和转换器都可以在scikit-learn库中找到。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...