首页 > 解决方案 > 如何获得 CountVectorizer ngram 频率

问题描述

我有一个大约 50k 短文本的数据集,每个平均 9 个标记。它们包含大量不常见的标记('nw'、'29203822'、'x989' 等)以及常规单词,我相信这些会降低我的分类工作。我想生成最常见的不提供任何价值的 n-gram 的停用词列表并将其删除。我认为最好的方法是在我的 Count Vectorizer 之后但在我的 TF-IDF 之前获得这些计数。

count_vect = CountVectorizer(ngram_range=(1,4))
X_train_counts = count_vect.fit_transform(X_train)
X_train_counts.shape

(19859, 122567)

count_vect.vocabulary_

{'look': 66431,
'1466': 1827,
'cl sign': 23055,
'in': 56587,
...}

我没有看到任何用于在数据集中输出这些 ngram 频率的函数。有没有?谢谢!

标签: pythonn-gramword-frequencycountvectorizer

解决方案


没有构建功能(据我所知),但您可以使用以下功能实现它:

def create_n_gram_frequency(n_gram_from, n_gram_to, corpus):
    vec = CountVectorizer(ngram_range=(n_gram_from, n_gram_to)).fit(corpus)
    bag_of_words = vec.transform(corpus)
    sum_words = bag_of_words.sum(axis = 0)
    words_freq = [(word, sum_words[0, i]) for word, i in vec.vocabulary_.items()]
    words_freq = sorted(words_freq, key = lambda x: x[1], reverse = True)
    return words_freq

推荐阅读