【问题标题】:Inverse X.toarray into a CountVectorizer in sklearn将 X.toarray 反转为 sklearn 中的 CountVectorizer
【发布时间】:2021-05-29 11:13:14
【问题描述】:

我在这里关注文档:

https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html

>>> from sklearn.feature_extraction.text import CountVectorizer
>>> corpus = [
...     'This is the first document.',
...     'This document is the second document.',
...     'And this is the third one.',
...     'Is this the first document?',
... ]
>>> vectorizer = CountVectorizer()
>>> X = vectorizer.fit_transform(corpus)
>>> print(vectorizer.get_feature_names())
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
>>> print(X.toarray())
[[0 1 1 1 0 0 1 0 1]
 [0 2 0 1 0 1 1 0 1]
 [1 0 0 1 1 0 1 1 1]
 [0 1 1 1 0 0 1 0 1]]

假设我已经有一个类似X.toarray() 中给出的词频矩阵,但我没有使用 CountVectorizer 来获取它。

我想对这个矩阵应用一个 TfIDF。有没有办法让我获取一个计数数组 + 一个字典并应用这个函数的一些逆作为构造函数来获得一个 fit_transformed X?

我正在寻找...

>>> print(X.toarray())
[[0 1 1 1 0 0 1 0 1]
 [0 2 0 1 0 1 1 0 1]
 [1 0 0 1 1 0 1 1 1]
 [0 1 1 1 0 0 1 0 1]]


>>> V = CountVectorizerConstructorPrime(array=(X.toarray()), 
                                        vocabulary=['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this'])

这样:

>>> V == X
True

【问题讨论】:

    标签: scikit-learn


    【解决方案1】:

    CountVectorizer 构造的XSciPy压缩稀疏行(csr) 格式的稀疏矩阵。因此,您可以使用适当的 SciPy 函数直接从任何字数矩阵构造它:

    from scipy.sparse import csr_matrix
    
    V = csr_matrix(X.toarray())
    

    现在VX 是相等的,尽管这可能不明显,因为V == X 会给你另一个稀疏矩阵(或者更确切地说,尽管使用了预期的格式,矩阵并不稀疏,请参阅this question )。但是你可以这样检查:

    (V != X).toarray().any()
    
    False
    

    请注意,不需要单词列表,因为矩阵只编码所有不同单词的频率,无论它们是什么。

    【讨论】:

      猜你喜欢
      • 2018-03-25
      • 2018-03-20
      • 1970-01-01
      • 2018-05-05
      • 2020-07-15
      • 2021-07-17
      • 2019-12-11
      • 2017-09-14
      • 2020-08-06
      相关资源
      最近更新 更多