【问题标题】:How to get column sum in the matrix returned by sklearn count vectorizer?如何获取 sklearn 计数向量化器返回的矩阵中的列总和?
【发布时间】:2020-01-26 05:23:17
【问题描述】:

如何获取sklearn CountVectorizer返回的词频矩阵中任意给定列的总和?

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()

corpus = [ 'This is a sentence',
           'Another sentence is here',
           'Wait for another sentence',
           'The sentence is coming',
           'The sentence has come'
         ]

x = vectorizer.fit_transform(corpus)

例如我想找出矩阵中sentence 的频率。所以我想要sentence 列的总和。我想不出办法:

  • 例如,我尝试了x['sentence'].sum(),但没有帮助
  • 我还尝试将其转换为 pandas 数据帧并计算总和,但我不需要将此矩阵转换为数据帧。

【问题讨论】:

    标签: python python-3.x scikit-learn countvectorizer


    【解决方案1】:

    您可以尝试以下方法:

    1. 从 CountVectorizer 获取您的术语在 feature_names() 列表中的位置。
    2. 使用该位置对 CSR 矩阵中的所有列求和(在您的情况下为x)。

    代码:

    import numpy as np
    
    term_to_sum = 'sentence'    
    index_term = vectorizer.get_feature_names().index(term_to_sum)
    
    s = np.sum(x[:, index_term])  # here you get the sum
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 2014-12-29
      • 2021-05-11
      相关资源
      最近更新 更多