【问题标题】:how to find which word has maximum tfidf in a tfidf matrix for a single document?如何在单个文档的 tfidf 矩阵中找到哪个单词具有最大 tfidf?
【发布时间】:2017-11-11 01:00:09
【问题描述】:

我目前正在使用以下代码。我已经为所有文档存储了 tfidf 矩阵,现在我需要特定文档的前 n 个单词吗? 我不知道如何获得它?

这是我目前使用的代码。我现在需要从每个 tfidf 最高的文档中找到单词

import glob
import pandas as pd
import math
filenames=[]
corpus = []
df=pd.DataFrame(columns=['article','similar','score'])
for file in glob.glob("*.txt"):
    with open(file, "r") as paper:
    corpus.append((file, paper.read()))
    filenames.append(file)
from sklearn.feature_extraction.text import TfidfVectorizer

tf = TfidfVectorizer(analyzer='word', ngram_range=(1,1), min_df = 0, stop_words = 'english')
tfidf_matrix =  tf.fit_transform([content for file, content in corpus])

【问题讨论】:

    标签: python-2.7 pandas tf-idf


    【解决方案1】:

    您可以使用np.argmax获取索引,然后使用它在TfidfVectorizer._vocabulary中查找对应的单词,如:

    vocab_lookup = {v:k for k,v in tf.vocabulary_.items()}
    [vocab_lookup[np.argmax(v)] for v in tfidf_matrix]
    

    【讨论】:

    • canyou更具体?我是python的新手,我收到一个错误,因为'tfidfvectorizer'对象没有属性'_vocabulary' span>
    • 抱歉应该是vocabulary_
    • 还意识到键/值在词汇表中的顺序错误_您必须将它们反转
    猜你喜欢
    • 1970-01-01
    • 2021-01-03
    • 2011-07-25
    • 2015-06-21
    • 1970-01-01
    • 2016-12-22
    • 2017-02-27
    • 2016-03-30
    • 2014-10-02
    相关资源
    最近更新 更多