首页 > 解决方案 > 使用 sklearn 计算仅给定单词列表的 tf-idf 权重

问题描述

我想从文档中获取给定单词列表的 tf-idf 权重。例如,我有下面感兴趣的词。

document_list = ['''document 1 blabla''', '''document 2 blabla''']
words = ['project', 'management', 'uml theory', 'wireframe']

当然,我可以使用 sklearn 从文档中获取术语和权重。但我只想使用 scikit-learn 从文档组中获取上述单词的权重。任何想法都会对我有很大帮助。

标签: pythonmachine-learningscikit-learn

解决方案


这就像适合TfidfVectorizer您的固定所需单词列表然后使用您的模型一样简单。

证明:

from sklearn.feature_extraction.text import TfidfVectorizer
words = ['project', 'management', 'uml theory', 'wireframe']
mod_tfidf = TfidfVectorizer()
mod_tfidf.fit_transform(words)
<4x5 sparse matrix of type '<class 'numpy.float64'>'
    with 5 stored elements in Compressed Sparse Row format>

再多加一个词,看到第二维的数量仍然是5

mod_tfidf.transform(words + ["dummy"])
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 5 stored elements in Compressed Sparse Row format>

编辑

鉴于您更新的问题和评论:

mod_tfidf.fit(words)
mod_tfidf.transform(document_list)

编辑2

为了完整起见,TfidfVectorizer使用vocabularyparam 进行初始化也提供了相同的结果。在这种情况下注意words是单独的单词列表:

mod_tfidf = TfidfVectorizer(vocabulary=words)

在这种情况下,结果特征的排序将由您的words订单确定。您可以通过以下方式检查:

mod_tfidf.get_feature_names()

推荐阅读