【问题标题】:Term relative frequency matrix from CountVectorizer来自 CountVectorizer 的术语相对频率矩阵
【发布时间】:2021-09-04 03:20:55
【问题描述】:

有没有办法从绝对频率矩阵开始获取相对频率矩阵(使用CountVectorizer方法获得)?这是使用的代码:

body = [
    'the quick brown fox',
    'the slow brown dog',
    'the quick red dog',
    'the lazy yellow fox'
]

from sklearn.feature_extraction.text import CountVectorizer

vectorizer = CountVectorizer(stop_words='english')
bag_of_words = vectorizer.fit_transform(body)

from sklearn.decomposition import TruncatedSVD

svd = TruncatedSVD(n_components=2)
lsa = svd.fit_transform(bag_of_words) 

我的目标是使用函数fit_transform()(在我的代码的最后一行)不是绝对频率矩阵,而是相对频率矩阵。特别是,我想找到一种方法将矩阵bag_of_words 的每一行除以行本身的总和。这对我来说不是即时的,因为矩阵是稀疏的。

任何意见或建议表示赞赏。谢谢。

【问题讨论】:

    标签: python scikit-learn scipy countvectorizer


    【解决方案1】:

    这可以使用TfidfVectorizer 而不是CountVectorizer 来完成。但是,这需要更改以下默认参数:

    • 您可以删除 tfidf 矢量化器的“idf”部分,只留下词频
    • 默认情况下,计数按 L2 范数进行归一化,您在这里想要的(按所有计数的总和进行归一化)是 L1 范数

    实际上,它看起来像这样:

    from sklearn.feature_extraction.text import TfidfVectorizer
    body = [
        'the quick brown fox',
        'the slow brown dog',
        'the quick red dog',
        'the lazy yellow fox'
    ]
    vectorizer = TfidfVectorizer(use_idf=False, norm="l1")
    X = vectorizer.fit_transform(body)
    print(vectorizer.get_feature_names())
    

    这将返回:

    array([[0.25, 0.  , 0.25, 0.  , 0.25, 0.  , 0.  , 0.25, 0.  ],
           [0.25, 0.25, 0.  , 0.  , 0.  , 0.  , 0.25, 0.25, 0.  ],
           [0.  , 0.25, 0.  , 0.  , 0.25, 0.25, 0.  , 0.25, 0.  ],
           [0.  , 0.  , 0.25, 0.25, 0.  , 0.  , 0.  , 0.25, 0.25]])
    
    ['brown', 'dog', 'fox', 'lazy', 'quick', 'red', 'slow', 'the', 'yellow']
    

    【讨论】:

      猜你喜欢
      • 2015-10-16
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 2013-05-28
      • 2016-11-27
      • 1970-01-01
      相关资源
      最近更新 更多