我有一个名为corpus我正在尝试使用sklearn内置函数的TF-IDF的列表。该列表有 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
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,我能够获得一个包含 5 行(对于列表中的每个项目)和 n 列的数据框,其中包含该语料库中每个术语的 tf-idf。
下一步,我想用最大权重的语料库中的 5 个项目构建具有最大 tf-idf 术语的词云。
我尝试了以下方法:
x = vectorizer.vocabulary_
Cloud = WordCloud(background_color="white", max_words=50).generate_from_frequencies(x)
Run Code Online (Sandbox Code Playgroud)
这显然行不通。字典是带有索引的单词列表,而不是单词评分。
因此,我需要一个字典来为整个语料库中的每个单词分配 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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2824 次 |
| 最近记录: |