【问题标题】:How to print tf-idf scores matrix in sklearn in python如何在 python 中的 sklearn 中打印 tf-idf 分数矩阵
【发布时间】:2018-03-17 18:32:15
【问题描述】:

我使用sklearn获取tf-idf值如下。

from sklearn.feature_extraction.text import TfidfVectorizer
myvocabulary = ['life', 'learning']
corpus = {1: "The game of life is a game of everlasting learning", 2: "The unexamined life is not worth living", 3: "Never stop learning"}
tfidf = TfidfVectorizer(vocabulary = myvocabulary, ngram_range = (1,3))
tfs = tfidf.fit_transform(corpus.values())

现在我想在矩阵中查看我计算的 tf-idf 分数,如下所示。

我尝试如下。

idf = tfidf.idf_
dic = dict(zip(tfidf.get_feature_names(), idf))
print(dic)

但是,我得到如下输出。

{'life': 1.2876820724517808, 'learning': 1.2876820724517808}

请帮帮我。

【问题讨论】:

  • 您从tfidf.fit_transform() 获得的实际输出只是这种形式。唯一需要的是您从tfidf.get_feature_names() 获得的列名。只需将这两个包装到一个数据框中。

标签: python scikit-learn tf-idf


【解决方案1】:

感谢 σηγ 我可以从 this question 找到答案

feature_names = tfidf.get_feature_names()
corpus_index = [n for n in corpus]
import pandas as pd
df = pd.DataFrame(tfs.T.todense(), index=feature_names, columns=corpus_index)
print(df)

【讨论】:

    【解决方案2】:

    提问者提供的答案是正确的,我想做一个调整。 上面的代码给出了

             Doc1     Doc2
    

    功能1

    功能2

    矩阵应该是这样的

             feature1     feature2
    

    文档1

    文档2

    所以你可以做一个简单的改变来得到它

    df = pd.DataFrame(tfs.todense(), index=corpus_index, columns=feature_names)
    

    【讨论】:

      【解决方案3】:

      我发现了另一种可能的方法,使用 toarray() 函数

      import pandas as pd
      print(tfidf.get_feature_names())
      print(tfs.toarray())
      print(pd.DataFrame(tfs.toarray(), 
      columns=tfidf.get_feature_names(), 
      index=['doc1','doc2','doc3'])) `
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-01
        • 2017-06-19
        • 2016-02-03
        • 1970-01-01
        • 2016-05-08
        • 2020-05-11
        • 2019-08-13
        • 2018-10-24
        相关资源
        最近更新 更多