sklearn 计算 tfidf 得到每个词分数

python 复制代码
from sklearn.feature_extraction.text import TfidfVectorizer

# 语料库 可以换为其它同样形式的单词
corpus = [
    list(range(-5, 5)),
    list(range(-6,4)),
    list(range(12)),
    list(range(13))]

# corpus = [
#    ['Two', 'wrongs', 'don\'t', 'make', 'a', 'right', '.'],
#    ['The', 'pen', 'is', 'mightier', 'than', 'the', 'sword'],
#    ['Don\'t', 'put', 'all', 'your', 'eggs', 'in', 'one', 'basket', '.']]
    
def dummy_fun(doc):
    return doc
    
tfidf_vec = TfidfVectorizer(
    analyzer='word',
    tokenizer=dummy_fun,
    preprocessor=dummy_fun,
    token_pattern=None)  

# 使用 fit_transform() 得到 TF-IDF 矩阵。此为 scipy 稀疏矩阵
tfidf_matrix = tfidf_vec.fit_transform(corpus)
# print(tfidf_matrix)

# 使用 get_feature_names() 得到不重复的单词
print(tfidf_vec.get_feature_names_out())

# 得到每个单词对应的 ID
print(tfidf_vec.vocabulary_)
python 复制代码
# 得到 corpus 中每个词得分
for i in range(len(corpus)):
    column_indexes = [tfidf_vec.vocabulary_[key] for key in corpus[i]]
    tf_idf = tfidf_matrix[i, column_indexes].toarray()[0]
    print(tf_idf)

参考:
Applying scikit-learn TfidfVectorizer on tokenized text
sklearn.feature_extraction.text.TfidfVectorizer

相关推荐
老胖闲聊6 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1186 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之7 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
lyaihao8 小时前
使用python实现奔跑的线条效果
python·绘图
ai大师8 小时前
(附代码及图示)Multi-Query 多查询策略详解
python·langchain·中转api·apikey·中转apikey·免费apikey·claude4
小小爬虾9 小时前
关于datetime获取时间的问题
python
蓝婷儿10 小时前
6个月Python学习计划 Day 16 - 面向对象编程(OOP)基础
开发语言·python·学习
chao_78910 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
大霞上仙11 小时前
nonlocal 与global关键字
开发语言·python
Mark_Aussie12 小时前
Flask-SQLAlchemy使用小结
python·flask