代码之家  ›  专栏  ›  技术社区  ›  Mittenchops

将X.toarray反转为sklearn中的CountVectorizer

  •  0
  • Mittenchops  · 技术社区  · 5 年前

    我在这里提供以下文档:

    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。有没有一种方法可以让我使用一个count数组+一个dictionary,并将这个函数的一些逆函数作为构造函数来获得经过fit\u变换的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
    
    
    0 回复  |  直到 5 年前
        1
  •  2
  •   Arne    5 年前

    这个 X 建设单位: CountVectorizer 是中的稀疏矩阵 SciPy 压缩稀疏行(csr) 总体安排因此,您可以使用适当的SciPy函数直接从任何字数矩阵构造它:

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

    现在 V 十、 是相等的,尽管这可能并不明显,因为 V == X 将为您提供另一个稀疏矩阵(或者更确切地说,投诉矩阵不是稀疏的,尽管其格式是预期的,请参阅 this question ). 但你可以这样检查:

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

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

    推荐文章