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

相关推荐
半兽先生24 分钟前
大模型实现金融文本分类
人工智能·python·金融
汤姆小白31 分钟前
06-LoRA参数高效微调
人工智能·python·机器学习·transformer
铅笔侠_小龙虾1 小时前
Rust 学习(6)-所有权规则、移动语义、Clone 与 Copy
python·学习·rust
码云骑士1 小时前
65-AI-Agent基础原理-AutoGPT-四大架构全景解读
人工智能·python·架构
Ulyanov2 小时前
刚体动力学方程——牛顿-欧拉与陀螺效应的奥秘
开发语言·python·目标跟踪·雷达电子对抗·导引头
观察员2 小时前
用 Streamlit + 智谱 AI 打造虚拟伴侣聊天机器人
python
Cubar2 小时前
[一]开源ERP:odoo19二次开发问题-原库存模块问题
python·开源·odoo·开源erp
不能只会打代码2 小时前
Day 002 — Python 工程化 & FastAPI & 数据库速通
数据库·redis·python·docker·fastapi·测试
滴滴滴嘟嘟嘟.3 小时前
强化学习-PPO 奖励塑形实验:Pendulum-v1 中角速度惩罚权重的影响
开发语言·python
deephub3 小时前
用 Scikit-LLM 和 Groq 搭建情感分析 pipeline
人工智能·大语言模型·sklearn