对n元语法进行朴素贝叶斯分类器训练

11
我一直在使用 Ruby Classifier library 来进行 隐私政策分类。我得出的结论是,这个库内置的简单词袋方法不够。为了提高分类准确性,我想训练分类器来处理 n-grams,除了单独的单词。
我想知道是否有一个库可以对文档进行预处理,以获取相关的 n-grams(并正确处理标点符号)。一个想法是,我可以预处理文档,并将伪-ngrams 提供给 Ruby Classifier,例如:

wordone_wordtwo_wordthree

或者也许有更好的方法来做到这一点,比如一个从一开始就具有基于 ngram 的朴素贝叶斯分类的库。如果需要,我可以使用其他语言(如果它们能完成任务,则 Python 似乎是一个好选择)。
2个回答

12
如果您熟悉Python,我会建议您使用nltk。例如:
>>> import nltk
>>> s = "This is some sample data.  Nltk will use the words in this string to make ngrams.  I hope that this is useful.".split()
>>> model = nltk.NgramModel(2, s)
>>> model._ngrams
set([('to', 'make'), ('sample', 'data.'), ('the', 'words'), ('will', 'use'), ('some', 'sample'), ('', 'This'), ('use', 'the'), ('make', 'ngrams.'), ('ngrams.', 'I'), ('hope', 'that'
), ('is', 'some'), ('is', 'useful.'), ('I', 'hope'), ('this', 'string'), ('Nltk', 'will'), ('words', 'in'), ('this', 'is'), ('data.', 'Nltk'), ('that', 'this'), ('string', 'to'), ('
in', 'this'), ('This', 'is')])

你甚至可以使用 nltk.NaiveBayesClassifier 方法。

3
相比Ruby提供的工具,NLTK在很多方面看起来都很棒。Python胜出,谢谢! - Ben G
@babonk 不客气。我发现nltk非常好用且功能强大,希望你也能玩得开心:D - Nolen Royalty
嘿,Nolen,你的例子需要更正一下,你需要在分割成ngrams之前使用word_tokenize,否则它会按字母进行分割 :) - Ben G

3
>> s = "She sells sea shells by the sea shore"
=> "She sells sea shells by the sea shore"
>> s.split(/ /).each_cons(2).to_a.map {|x,y| x + ' ' +  y}
=> ["She sells", "sells sea", "sea shells", "shells by", "by the", "the sea", "sea shore"]

Ruby中的enumerables有一个名为enum_cons的方法,它可以返回可枚举对象中n个连续项。使用该方法生成n-gram只需要一行代码。


谢谢。不得不使用each_cons代替enum_cons - Dru
Dru: 似乎 enum_cons 已被弃用。在我的答案中,我用 each_cons 替换它了。谢谢! - Aditya Mukherji

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接