繁体   English   中英

由 TF-IDF Vectorizer function 构建的词云

[英]Word Cloud built out of TF-IDF Vectorizer function

我有一个名为corpus的列表,我正在尝试 TF-IDF,使用sklearn内置 function。 该列表有 5 个项目。 这些项目中的每一项都来自文本文件。 我为此示例生成了一个名为 corpus 的玩具列表。

corpus = ['Hi what are you accepting here do you accept me',
'What are you thinking about getting today',
'Give me your password to get accepted into this school',
'The man went to the tree to get his sword back',
'go away to a far away place in a foreign land']

vectorizer = TfidfVectorizer(stop_words='english')
vecs = vectorizer.fit_transform(corpus)
feature_names = vectorizer.get_feature_names()
dense = vecs.todense()
lst1 = dense.tolist()
df = pd.DataFrame(lst1, columns=feature_names)
df

使用上面的代码,我能够得到一个 dataframe 5 行(列表中的每个项目)和 n 列,该语料库中的每个术语都有 tf-idf。

作为下一步,我想在语料库中获得最高权重的 5 个项目中构建具有最大 tf-idf 术语的词云。

我尝试了以下方法:

x = vectorizer.vocabulary_
Cloud = WordCloud(background_color="white", max_words=50).generate_from_frequencies(x)

这显然是行不通的。 字典是附有索引的单词列表,而不是单词评分。

因此,我需要一个字典,将 TF-IDF 分数分配给语料库中的每个单词。 然后,生成的词云以得分最高的词作为最大的大小。

您快到了。 您需要转置以获得每个术语的频率而不是每个文档的术语频率,然后求和,然后将该系列直接传递到您的 wordcloud

df.T.sum(axis=1)

accept       0.577350
accepted     0.577350
accepting    0.577350
away         0.707107
far          0.353553
foreign      0.353553
getting      0.577350
hi           0.577350
land         0.353553
man          0.500000
password     0.577350
place        0.353553
school       0.577350
sword        0.500000
thinking     0.577350
today        0.577350
tree         0.500000
went         0.500000

Cloud = WordCloud(background_color="white", max_words=50).generate_from_frequencies(df.T.sum(axis=1))

暂无
暂无

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

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