python - 如何获得 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 频率的函数。有没有?谢谢!
解决方案
没有构建功能(据我所知),但您可以使用以下功能实现它:
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
推荐阅读
- r - R - tmap:添加粗边界并将具有 NA 的县转换为对角线条纹
- python - 当局部变量 line 为 #out 时,在 For 循环范围内识别 NumberOfSymbols。为什么它扮演一个全球性的角色?
- spring - 是否可以在 SpringBatch 的 JdbcBatchItemWriter() 方法中编写更新查询
- mysql - 在多行中的两列之间选择值
- authentication - Blazor - 在不同布局之间使用级联身份验证状态
- machine-learning - 如果我的 R2 高但 RMSE 和 MAE 低,这意味着什么
- excel - 如何使用变量选择一行
- react-native - 在 react-native 中使文本模糊
- c++ - 将一个元素从一个向量复制到另一个向量
- java - bean-validation @Pattern 第一个数字是 '1'