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

相关推荐
大连好光景22 分钟前
conda管理包还是pip管理包
python·conda·pip
m0_7301151126 分钟前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
FreakStudio34 分钟前
MicroPython+PycoClaw,3 分钟搞定 ESP32 跑上 OpenClaw!
python·单片机·嵌入式·电子diy
罗罗攀1 小时前
PyTorch学习笔记|张量的广播和科学运算
人工智能·pytorch·笔记·python·学习
傻啦嘿哟1 小时前
Python 操作 Excel 条件格式指南
开发语言·python·excel
2301_807367191 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
2301_795741791 小时前
构建一个基于命令行的待办事项应用
jvm·数据库·python
小鸡吃米…2 小时前
Python 网络爬虫 —— 环境设置
开发语言·爬虫·python
sw1213892 小时前
Python字典与集合:高效数据管理的艺术
jvm·数据库·python
进击的小头2 小时前
第13篇:基于伯德图的超前_滞后校正器深度设计
python·算法