利用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)

二、结果

相关推荐
nju_spy3 天前
机器学习 - Kaggle项目实践(8)Spooky Author Identification 作者识别
人工智能·深度学习·机器学习·nlp·tf-idf·glove·南京大学
nju_spy5 天前
机器学习 - Kaggle项目实践(7)NLP with Disaster Tweets 灾难消息
人工智能·深度学习·自然语言处理·bert·tf-idf·glove·南京大学
2202_7567496913 天前
自然处理语言NLP:One-Hot编码、TF-IDF、词向量、NLP特征输入、EmbeddingLayer实现、word2vec
人工智能·深度学习·自然语言处理·tf-idf·word2vec
nju_spy19 天前
机器学习 - Kaggle项目实践(4)Toxic Comment Classification Challenge 垃圾评论分类问题
人工智能·深度学习·自然语言处理·tf-idf·南京大学·glove词嵌入·双头gru
fsnine20 天前
机器学习——TF-IDF算法
tf-idf
qqxhb23 天前
零基础数据结构与算法——第七章:算法实践与工程应用-搜索引擎
算法·搜索引擎·tf-idf·倒排索引·pagerank·算法库
赴3351 个月前
机器学习 TF-IDF提取关键词,从原理到实践的文本特征提取利器
人工智能·机器学习·tf-idf·sklearn
欧阳小猜1 个月前
机器学习②【字典特征提取、文本特征处理(TF-IDF)、数据标准化与归一化、特征降维】
人工智能·机器学习·tf-idf
合作小小程序员小小店2 个月前
web网页开发,在线%微博,舆情%系统,基于python,pycharm,django,nlp,内容推荐,余弦,线性,TF-IDF,mysql
自然语言处理·django·nlp·html5·tf-idf
suixinm3 个月前
One-Hot、BOW、TF-IDF、N-Gram区别
tf-idf