利用tf-idf对特征进行提取

本文介绍了如何使用Python的sklearn库中的TfidfVectorizer实现TF-IDF方法,计算文档中单词的重要性,并提供了代码示例和结果展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TF-IDF是一种文本特征提取的方法,用于评估一个词在一组文档中的重要性。 

一、代码

from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

def print_tfidf_words(documents):
    """
    打印TF-IDF矩阵中每个文档中非零值对应的单词及其概率。
    
    Parameters:
    - documents: list,包含文档的列表
    
    Returns:
    - None
    """
    # 创建TF-IDF向量化器
    vectorizer = TfidfVectorizer()
    
    # 对文档集合进行拟合和转换
    tfidf_matrix = vectorizer.fit_transform(documents)
    
    # 获取特征词列表
    feature_names = vectorizer.get_feature_names_out()

    # 将TF-IDF矩阵转换为稠密矩阵
    # 在TF-IDF矩阵中,每一行代表一个文档,每一列代表一个特征词
    # 非零值对应的列索引  就是  该文档中的非零权重对应的单词  在特征词列表中的索引
    # dense_tfidf_matrix 是一个 NumPy 稠密矩阵,可以使用索引操作符 [row, column] 来获取矩阵中的特定元素
    dense_tfidf_matrix = tfidf_matrix.todense()
    
    # 打印每个文档中非零值对应的单词及其概率
    for i, document in enumerate(dense_tfidf_matrix):
        nonzero_indices = document.nonzero()[1]
        dic = {idx: document[0, idx] for idx in nonzero_indices}
        # 根据概率进行排序
        sorted_dic = dict(sorted(dic.items(), key=lambda x: x[1], reverse=True))
        words = {feature_names[k]: v for k, v in sorted_dic.items()}
        print(f"文档 {i + 1} 中的非零值对应的单词及其概率:{words}")

    # 打印特征词对应的索引
    print("Feature indices:", {feature: index for index, feature in enumerate(feature_names)})

# 示例文档集合
documents = [
    "This is the first document.",
    "This document is the second document.",
    "And this is the third one.",
    "Is this the first document?"
]

# 调用函数打印结果
print_tfidf_words(documents)

二、结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值