python - 使用 sklearn 计算仅给定单词列表的 tf-idf 权重
问题描述
我想从文档中获取给定单词列表的 tf-idf 权重。例如,我有下面感兴趣的词。
document_list = ['''document 1 blabla''', '''document 2 blabla''']
words = ['project', 'management', 'uml theory', 'wireframe']
当然,我可以使用 sklearn 从文档中获取术语和权重。但我只想使用 scikit-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
使用vocabulary
param 进行初始化也提供了相同的结果。在这种情况下注意words
是单独的单词列表:
mod_tfidf = TfidfVectorizer(vocabulary=words)
在这种情况下,结果特征的排序将由您的words
订单确定。您可以通过以下方式检查:
mod_tfidf.get_feature_names()
推荐阅读
- mongodb - MongoDb 用户缺少操作“删除”,但在继承角色中启用
- reactjs - 如何将客户端从 ApolloProvider 传递到也采用其他道具的组件?
- sql - SQL:添加逻辑以在选择最大值时处理平局
- javascript - 在 JS 中优化一个 deep 和 map 函数
- javascript - ReactRouter:传入数据/对象
- java - 具有递归的可变数据类型的乘积
- ssl - TLS 的 WebSocketpp 握手问题
- c - C中函数typedef的前向声明
- assembly - Intel 8086 程序集 - 间接寻址和比较指令 (MASM)
- django - 你能帮我修复这个错误吗?