【问题标题】:Is there a more efficient way to find most common n-grams?有没有更有效的方法来查找最常见的 n-gram?
【发布时间】:2017-07-11 10:55:18
【问题描述】:

我正在尝试从大型语料库中找到 k 个最常见的 n-gram。我看到很多地方都在暗示这种幼稚的方法——只需扫描整个语料库并保存所有 n-gram 计数的字典。有没有更好的方法来做到这一点?

【问题讨论】:

  • 你在比较什么?语料库有多大?我认为你可以很容易地在 C++ 中快速计算 ngram 的数量,以获得巨大的语料库,即使在 Python 中也非常快 =)
  • 你是指字符 ngram 还是单词 ngram?
  • 我使用的是单词 ngram,但我想字符 ngram 会泛化。至于语料,应该可以扩展到20gb左右的语料,在hadoop集群上运行

标签: algorithm nlp n-gram


【解决方案1】:

在 Python 中,使用 NLTK:

$ wget http://norvig.com/big.txt
$ python
>>> from collections import Counter
>>> from nltk import ngrams
>>> bigtxt = open('big.txt').read()
>>> ngram_counts = Counter(ngrams(bigtxt.split(), 2))
>>> ngram_counts.most_common(10)
[(('of', 'the'), 12422), (('in', 'the'), 5741), (('to', 'the'), 4333), (('and', 'the'), 3065), (('on', 'the'), 2214), (('at', 'the'), 1915), (('by', 'the'), 1863), (('from', 'the'), 1754), (('of', 'a'), 1700), (('with', 'the'), 1656)]

在 Python 中,原生(参见 Fast/Optimize N-gram implementations in python):

>>> import collections
>>> def ngrams(text, n=2):
...     return zip(*[text[i:] for i in range(n)])
>>> ngram_counts = collections.Counter(ngrams(bigtxt.split(), 2))
>>> ngram_counts.most_common(10)
    [(('of', 'the'), 12422), (('in', 'the'), 5741), (('to', 'the'), 4333), (('and', 'the'), 3065), (('on', 'the'), 2214), (('at', 'the'), 1915), (('by', 'the'), 1863), (('from', 'the'), 1754), (('of', 'a'), 1700), (('with', 'the'), 1656)]

在 Julia 中,请参阅 Generate ngrams with Julia

import StatsBase: countmap
import Iterators: partition
bigtxt = readstring(open("big.txt"))
ngram_counts = countmap(collect(partition(split(bigtxt), 2, 1)))

大致时间:

$ time python ngram-test.py # With NLTK.

real    0m3.166s
user    0m2.274s
sys 0m0.528s

$ time python ngram-native-test.py 

real    0m1.521s
user    0m1.317s
sys 0m0.145s

$ time julia ngram-test.jl 

real    0m3.573s
user    0m3.188s
sys 0m0.306s

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多