【问题标题】:Understanding the `ngram_range` argument in a CountVectorizer in sklearn了解 sklearn 中 CountVectorizer 中的“ngram_range”参数
【发布时间】:2014-07-23 05:36:34
【问题描述】:

我对如何在 Python 的 scikit-learn 库中使用 ngram 感到有些困惑,特别是 ngram_range 参数如何在 CountVectorizer 中工作。

运行此代码:

from sklearn.feature_extraction.text import CountVectorizer
vocabulary = ['hi ', 'bye', 'run away']
cv = CountVectorizer(vocabulary=vocabulary, ngram_range=(1, 2))
print cv.vocabulary_

给我:

{'hi ': 0, 'bye': 1, 'run away': 2}

我在哪里(显然是错误的)我会得到一元和二元的印象,就像这样:

{'hi ': 0, 'bye': 1, 'run away': 2, 'run': 3, 'away': 4}

我正在处理这里的文档:http://scikit-learn.org/stable/modules/feature_extraction.html

显然,我对如何使用 ngram 的理解存在严重错误。也许这个论点没有效果,或者我对实际的二元组有一些概念上的问题!我难住了。如果有人对我提出建议,我将不胜感激。

更新:
我已经意识到我的做法是愚蠢的。我的印象是ngram_range 会影响词汇,而不是语料库。

【问题讨论】:

    标签: python scikit-learn n-gram feature-selection


    【解决方案1】:

    明确设置vocabulary 意味着不会从数据中学习词汇。如果你不设置它,你会得到:

    >>> v = CountVectorizer(ngram_range=(1, 2))
    >>> pprint(v.fit(["an apple a day keeps the doctor away"]).vocabulary_)
    {u'an': 0,
     u'an apple': 1,
     u'apple': 2,
     u'apple day': 3,
     u'away': 4,
     u'day': 5,
     u'day keeps': 6,
     u'doctor': 7,
     u'doctor away': 8,
     u'keeps': 9,
     u'keeps the': 10,
     u'the': 11,
     u'the doctor': 12}
    

    一个明确的词汇限制将从文本中提取的术语;词汇没有改变:

    >>> v = CountVectorizer(ngram_range=(1, 2), vocabulary={"keeps", "keeps the"})
    >>> v.fit_transform(["an apple a day keeps the doctor away"]).toarray()
    array([[1, 1]])  # unigram and bigram found
    

    (请注意,在提取 n-gram 之前应用了停用词过滤,因此 "apple day"。)

    【讨论】:

    • 所以在你的答案中,你已经适应了数据,因此,你得到了在 CountVectorizer 中指定的ngram_range。然后我的解决方案是手动将我的词汇向量化为预先包含 2 克...除非您推荐任何其他方法?
    • @MattO'Brien 你到底想达到什么目的?
    • 我的目标是简单地使用 CountVectorizer 来计算标记在语料库中出现的次数。我有一个自定义词汇表,由许多不同长度的克(1、2、3、4)组成。我一直在使用 unigram,但我也想探索其他长度标记的计数。
    猜你喜欢
    • 2018-03-20
    • 2021-07-17
    • 2015-02-26
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2013-11-29
    • 1970-01-01
    相关资源
    最近更新 更多