由TF-IDF Vectorizer功能构建的词云



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

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

使用上面的代码,我能够获得一个包含 5 行(针对列表中的每个项目(和 n 列的数据帧,其中包含此语料库中每个术语的 tf-idf。

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

我尝试了以下方法:

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

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

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

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

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

最新更新