【问题标题】:Word Cloud built out of TF-IDF Vectorizer function由 TF-IDF Vectorizer 函数构建的词云
【发布时间】:2020-05-20 14:48:22
【问题描述】:

我有一个名为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

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

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

我尝试了以下方法:

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

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

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你快到了。您需要转置以获取每个术语的频率而不是每个文档的术语频率,然后求和,然后将该系列直接传递给您的 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))
    

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 2017-06-19
      • 1970-01-01
      • 2020-07-21
      • 2016-12-01
      • 2017-01-15
      • 2023-02-07
      • 2020-11-30
      • 2018-08-05
      相关资源
      最近更新 更多