2012-04-09 188 views
10

我一直在使用Ruby Classifier libraryclassify privacy policies。我得出的結論是,這個庫中內置的簡單的單詞袋方法是不夠的。爲了提高我的分類準確度,我想除了單詞之外還要訓練n-gram的分類器。在ngrams上訓練樸素貝葉斯分類器

我想知道是否有一個庫用於預處理文檔以獲得相關n-gram(並正確處理標點符號)。一個想法是,我可以預處理的文件和飼料僞的n-gram與Ruby的分類,如:

wordone_wordtwo_wordthree

或者,也許有更好的方式來這樣做,比如有一個圖書館從getgo構建的基於ngram的樸素貝葉斯分類。如果他們完成了這項工作,我很樂於使用Ruby以外的其他語言(如果需要的話,Python似乎是一個很好的候選人)。

回答

11

如果你確定蟒蛇,我會說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

+0

很棒的答案+1 – Yavar 2012-04-09 20:39:41

+3

與許多Ruby相比,NLTK看起來很棒。 Python獲勝了,謝謝! – babonk 2012-04-09 21:49:47

+0

@babonk我的榮幸。我發現nltk是一個使用和令人難以置信的強大的快樂,希望你有它的樂趣:D – 2012-04-09 21:50:43

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"] 

紅寶石可枚舉有一個方法叫enum_cons將返回所有的n個連續的項目從枚舉。用這種方法生成ngram是一個簡單的單行程。

+0

Thx。必須使用'each_cons'而不是'enum_cons'。 – Dru 2013-01-20 15:57:21

+0

Dru:似乎enum_cons已被棄用。用我的答案中的each_cons替換它。謝謝! – 2013-01-20 17:09:10