繁体   English   中英

如何在python中的sklearn中打印tf-idf得分矩阵

[英]How to print tf-idf scores matrix in sklearn in python

我使用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分数,如下所示。 tf-idf矩阵

我尝试按如下方式进行。

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

但是,我得到如下输出。

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

请帮我。

感谢σηγ,我可以从这个问题中找到答案

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)

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

         Doc1     Doc2

优点1

特点2

矩阵应该看起来像这样

         feature1     feature2

文档1

文档2

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

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

我找到了另一种使用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'])) `

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM