首页 > 解决方案 > 如何获得具有最高 tf-idf 分数的前 n 个术语 - 大稀疏矩阵

问题描述

有这个代码:

feature_array = np.array(tfidf.get_feature_names())
tfidf_sorting = np.argsort(response.toarray()).flatten()[::-1]

n = 3
top_n = feature_array[tfidf_sorting][:n]

来自这个答案。

我的问题是,在我的稀疏矩阵太大而无法立即转换为密集矩阵(使用 )的情况下,如何有效地做到这一点response.toarray()

显然,一般的答案是将稀疏矩阵分成块,在 for 循环中对每个块进行转换,然后将所有块的结果组合起来。

但我想具体看一下总共执行此操作的代码。

标签: pythonpython-3.xscikit-learntf-idftfidfvectorizer

解决方案


如果您深入了解问题,他们会对了解tf_idf单个文档的最高分数感兴趣。

当您想对大型语料库做同样的事情时,您需要将所有文档中每个特征的分数求和(仍然没有意义,因为分数在 中进行了l2归一化TfidfVectorizer(),请阅读此处)。我建议使用.idf_分数来了解具有高逆文档频率分数的特征。

如果您想根据出现次数了解主要特征,请使用CountVectorizer()

from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
corpus = [
    'I would like to check this document',
    'How about one more document',
    'Aim is to capture the key words from the corpus'
]
vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(corpus)
feature_array = vectorizer.get_feature_names()

top_n = 3

print('tf_idf scores: \n', sorted(list(zip(vectorizer.get_feature_names(), 
                                             X.sum(0).getA1())), 
                                 key=lambda x: x[1], reverse=True)[:top_n])
# tf_idf scores : 
# [('document', 1.4736296010332683), ('check', 0.6227660078332259), ('like', 0.6227660078332259)]

print('idf values: \n', sorted(list(zip(feature_array,vectorizer.idf_,)),
       key = lambda x: x[1], reverse=True)[:top_n])

# idf values: 
#  [('aim', 1.6931471805599454), ('capture', 1.6931471805599454), ('check', 1.6931471805599454)]

vectorizer = CountVectorizer(stop_words='english')
X = vectorizer.fit_transform(corpus)
feature_array = vectorizer.get_feature_names()
print('Frequency: \n', sorted(list(zip(vectorizer.get_feature_names(), 
                                         X.sum(0).getA1())),
                            key=lambda x: x[1], reverse=True)[:top_n])

# Frequency: 
#  [('document', 2), ('aim', 1), ('capture', 1)]

推荐阅读