sklearn 计算 tfidf 得到每个词分数

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_)

在这里插入图片描述

# 得到 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

相关推荐

  1. 使用sklearn严格计算AUROC和AUPRC

    2024-01-31 19:12:03       35 阅读
  2. 分类使用sklearn计算y_pred和y_prob

    2024-01-31 19:12:03       22 阅读
  3. sklearn混淆矩阵的计算和seaborn可视化

    2024-01-31 19:12:03       20 阅读
  4. sklearn和torch计算的r2 score不一样

    2024-01-31 19:12:03       14 阅读
  5. 释放计算潜力:SKlearn模型并行训练指南

    2024-01-31 19:12:03       2 阅读

最近更新

  1. 写一个字符设备的驱动步骤

    2024-01-31 19:12:03       0 阅读
  2. Transformer和Bert的原理是什么

    2024-01-31 19:12:03       0 阅读
  3. 使用tkinter 制作工作流ui

    2024-01-31 19:12:03       1 阅读
  4. postman工具介绍

    2024-01-31 19:12:03       1 阅读
  5. vue-路由自动化

    2024-01-31 19:12:03       1 阅读
  6. el-date-picker 扩展

    2024-01-31 19:12:03       1 阅读
  7. Go语言入门之变量、常量、指针以及数据类型

    2024-01-31 19:12:03       1 阅读
  8. Kotlin 处理livedata数据倒灌

    2024-01-31 19:12:03       1 阅读

热门阅读

  1. 使用HSE配置系统时钟

    2024-01-31 19:12:03       43 阅读
  2. 前端网站website

    2024-01-31 19:12:03       41 阅读
  3. adb控制设备状态

    2024-01-31 19:12:03       42 阅读
  4. 华为HCIE课堂笔记第十七章 广域网互联技术

    2024-01-31 19:12:03       33 阅读
  5. Android 8.1 预置WIFI

    2024-01-31 19:12:03       32 阅读
  6. c++函数解释

    2024-01-31 19:12:03       39 阅读