【问题标题】:How to get top n terms with highest tf-idf score - Big sparse matrix如何获得具有最高 tf-idf 分数的前 n 个术语 - 大稀疏矩阵
【发布时间】:2019-11-04 12:52:39
【问题描述】:

有这个代码:

feature_array = np.array(tfidf.get_feature_names())
tfidf_sorting = np.argsort(response.toarray()).flatten()[::-1]

n = 3
top_n = feature_array[tfidf_sorting][:n]

来自this 的回答。

我的问题是,如果我的稀疏矩阵太大而无法立即转换为密集矩阵(使用response.toarray()),我该如何有效地做到这一点?

显然,一般的答案是将稀疏矩阵分割成块,在 for 循环中对每个块进行转换,然后将所有块的结果组合起来。

但我想具体看一下执行此操作的代码。

【问题讨论】:

    标签: python python-3.x scikit-learn tf-idf tfidfvectorizer


    【解决方案1】:

    如果您深入了解that 问题,他们有兴趣了解单个文档的最高tf_idf 分数。

    当您想对大型语料库做同样的事情时,您需要将所有文档中每个特征的分数相加(仍然没有意义,因为分数在 TfidfVectorizer() 中被归一化 l2,请阅读 here )。我建议使用.idf_ 分数来了解具有高逆文档频率分数的特征。

    如果您想根据出现次数了解最重要的特征,请使用CountVectorizer()

    from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
    corpus = [
        'I would like to check this document',
        'How about one more document',
        'Aim is to capture the key words from the corpus'
    ]
    vectorizer = TfidfVectorizer(stop_words='english')
    X = vectorizer.fit_transform(corpus)
    feature_array = vectorizer.get_feature_names()
    
    top_n = 3
    
    print('tf_idf scores: \n', sorted(list(zip(vectorizer.get_feature_names(), 
                                                 X.sum(0).getA1())), 
                                     key=lambda x: x[1], reverse=True)[:top_n])
    # tf_idf scores : 
    # [('document', 1.4736296010332683), ('check', 0.6227660078332259), ('like', 0.6227660078332259)]
    
    print('idf values: \n', sorted(list(zip(feature_array,vectorizer.idf_,)),
           key = lambda x: x[1], reverse=True)[:top_n])
    
    # idf values: 
    #  [('aim', 1.6931471805599454), ('capture', 1.6931471805599454), ('check', 1.6931471805599454)]
    
    vectorizer = CountVectorizer(stop_words='english')
    X = vectorizer.fit_transform(corpus)
    feature_array = vectorizer.get_feature_names()
    print('Frequency: \n', sorted(list(zip(vectorizer.get_feature_names(), 
                                             X.sum(0).getA1())),
                                key=lambda x: x[1], reverse=True)[:top_n])
    
    # Frequency: 
    #  [('document', 2), ('aim', 1), ('capture', 1)]
    

    【讨论】:

    • 嘿,谢谢你的回答(赞成)。是的,我希望在所有文档中都使用这个,我明白你对 L2 的意思。从这个意义上说,也许最好进行简单的计数(CountVectorizer)。顺便说一句,我的问题更多是关于如何在大型 TF-IDF 稀疏矩阵上执行此操作 - 在这种情况下您的代码是否也可以工作,否则我会遇到内存错误?我认为它实际上是因为你直接.sum()。此外,我认为您也可以回答我的这个问题:stackoverflow.com/questions/56703244/… - 如果可以,请回答:)。
    • 我认为,它可以用于大稀疏矩阵,因为我没有使用.toarray()
    • 是的,我也是这么想的——我还没有测试过。
    • 顺便说一句,我不知道你是否有这个想法,但我认为你上面的代码,特别是你如何使用sorted 不会按 (tf-idf 或 idf 或等)值,但按单词的名称。
    • 你必须使用这个.sort(key=lambda x: x[1], reverse=True)或类似的东西。
    猜你喜欢
    • 2016-03-17
    • 2018-03-23
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 2019-06-09
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多