【问题标题】:getting top words from the tf-idf sparse matrix (highest tf-idf value)从 tf-idf 稀疏矩阵中获取最高单词(最高 tf-idf 值)
【发布时间】:2018-03-23 11:30:39
【问题描述】:

我有一个大小为 208 的列表(208 个句子数组),看起来像:

all_words = [["this is a sentence ... "] , [" another one hello bob this is alice ... "] , ["..."] ...] 

我想得到具有最高 tf-idf 值的单词。 我创建了一个 tf-idf 矩阵:

from sklearn.feature_extraction.text import TfidfVectorizer

tokenize = lambda doc: doc.split(" ")
sklearn_tfidf = TfidfVectorizer(norm='l2', tokenizer=tokenize, ngram_range=(1,2))
tfidf_matrix = sklearn_tfidf.fit_transform(all_words)
sentences = sklearn_tfidf.get_feature_names()

dense_tfidf = tfidf_matrix.todense()

现在我不知道如何获取具有最高 tf-idf 值的单词。

dense_tfidf 的每一列代表一个单词/2 个单词。 (矩阵为208x5481)

当我对每一列求和时,它并没有真正帮助 - 得到一个简单的热门词的相同结果(我猜是因为它与简单的字数相同)。

如何获取 tf-idf 值最高的单词?或者我怎样才能明智地将它标准化?

【问题讨论】:

    标签: python feature-extraction tf-idf sklearn-pandas


    【解决方案1】:

    有一个类似的问题,但在https://towardsdatascience.com/multi-class-text-classification-with-scikit-learn-12f1e60e0a9f 发现了这个问题,只需根据您的数据框更改 X 和 y 输入。博客中的代码如下。 Sklearn 的文档帮助了我:http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.chi2.html

    from sklearn.feature_selection import chi2
    import numpy as np
    N = 2
    for Product, category_id in sorted(category_to_id.items()):
    features_chi2 = chi2(features, labels == category_id)
    indices = np.argsort(features_chi2[0])
    feature_names = np.array(tfidf.get_feature_names())[indices]
    unigrams = [v for v in feature_names if len(v.split(' ')) == 1]
    bigrams = [v for v in feature_names if len(v.split(' ')) == 2]
    print("# '{}':".format(Product))
    print("  . Most correlated unigrams:\n. {}".format('\n. '.join(unigrams[-N:])))
    print("  . Most correlated bigrams:\n. {}".format('\n. '.join(bigrams[-N:])))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-04
      • 2019-03-15
      • 2017-07-01
      • 1970-01-01
      • 2021-01-22
      • 2020-05-11
      • 2019-06-09
      • 1970-01-01
      相关资源
      最近更新 更多