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

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

一、代码

python 复制代码
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)

二、结果

相关推荐
小码哥哥12 天前
从TF-IDF到RAG:企业AI知识库检索技术的六次范式跃迁
人工智能·tf-idf
解局易否结局12 天前
鸿蒙端侧 NLP 实战:分词器 + TF-IDF + 朴素贝叶斯分类 + 文本相似度
华为·自然语言处理·分类·harmonyos·tf-idf
五条凪14 天前
简单理解 BM25 与 TF-IDF
人工智能·算法·搜索引擎·全文检索·tf-idf
All The Way North-14 天前
【NLP文本分类实战】随机森林 + TF-IDF 完整流程,准确率82.5%(数据分析/分词/模型训练)
随机森林·机器学习·nlp·tf-idf·文本分类·sklearn·保姆级教程
XGeFei15 天前
TF-IDF(词频-逆文档频率)
算法·tf-idf
想会飞的蒲公英25 天前
TF-IDF + 随机森林中文文本分类全链路实战:从训练脚本到 Flask API + Streamlit 前端
人工智能·pytorch·python·随机森林·分类·flask·tf-idf
TE-茶叶蛋2 个月前
TF-IDF 与 BM25 深度解析:从理论到项目实战
python·django·tf-idf
m沐沐2 个月前
【机器学习】NLP---用 Python+TF-IDF 给《红楼梦》自动提取关键词
人工智能·python·机器学习·自然语言处理·nlp·中文分词·tf-idf
SHolmes18542 个月前
TF-IDF为什么能找出文本里的重要词?
tf-idf
不会计算机的g_c__b2 个月前
基于酒店文本描述的相似酒店推荐系统:从TF-IDF到余弦相似度实战
tf-idf