【问题标题】:Training Naive Bayes Classifier on ngrams在 ngram 上训练朴素贝叶斯分类器
【发布时间】:2023-03-23 18:25:02
【问题描述】:

我一直在使用Ruby Classifier libraryclassify privacy policies。我得出的结论是,这个库中内置的简单的词袋方法是不够的。为了提高分类准确度,除了单个单词之外,我还想在 n-gram 上训练分类器。

我想知道是否有一个库用于预处理文档以获取相关的 n-gram(并正确处理标点符号)。一种想法是我可以预处理文档并将伪 ngram 输入 Ruby 分类器,例如:

wordone_wordtwo_wordthree

或者也许有更好的方法可以做到这一点,例如从一开始就内置了基于 ngram 的朴素贝叶斯分类的库。如果他们完成工作,我愿意在这里使用 Ruby 以外的语言(如果需要,Python 似乎是一个很好的候选者)。

【问题讨论】:

    标签: python ruby nlp machine-learning classification


    【解决方案1】:
    >> 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 可枚举有一个名为 enum_cons 的方法,该方法将返回可枚举的 n 个连续项目中的每一个。使用该方法生成 ngram 很简单。

    【讨论】:

    • 谢谢。必须使用each_cons 而不是enum_cons
    • Dru:似乎 enum_cons 已被弃用。在我的回答中用 each_cons 替换它。谢谢!
    【解决方案2】:

    如果你对 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

    【讨论】:

    • 与 Ruby 所提供的相比,NLTK 在许多方面看起来都很棒。 Python 赢了,谢谢!
    • @babonk 我很高兴。我发现 nltk 使用起来很有趣,而且功能非常强大,希望你玩得开心:D
    • 嘿,Nolen,对您的示例的一个更正是您需要在拆分为 ngram 之前word_tokenize,否则它将拆分为字母 :)
    猜你喜欢
    • 2015-06-25
    • 2020-09-13
    • 2017-06-21
    • 2017-08-30
    • 2013-04-11
    • 2012-04-18
    • 2019-05-04
    • 2014-02-21
    相关资源
    最近更新 更多