【问题标题】:Don't understand the HashingVectorizer from sklearn不了解 sklearn 的 HashingVectorizer
【发布时间】:2019-10-10 01:20:42
【问题描述】:

我正在使用 sklearn.feature_extraction.text 中的 HashingVectorizer 函数,但我不明白它是如何工作的。

我的代码

from sklearn.feature_extraction.text import HashingVectorizer
corpus = [ 'This is the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?']
vectorizer = HashingVectorizer(n_features=2**3)
X = vectorizer.fit_transform(corpus)
print(X)

我的结果

(0, 0)        -0.8944271909999159
(0, 5)        0.4472135954999579
(0, 6)        0.0
(1, 0)        -0.8164965809277261
(1, 3)        0.4082482904638631
(1, 5)        0.4082482904638631
(1, 6)        0.0
(2, 4)        -0.7071067811865475
(2, 5)        0.7071067811865475
(2, 6)        0.0
(3, 0)        -0.8944271909999159
(3, 5)        0.4472135954999579
(3, 6)        0.0

我读了很多关于 Hashing Trick 的论文,比如这篇文章 https://medium.com/value-stream-design/introducing-one-of-the-best-hacks-in-machine-learning-the-hashing-trick-bf6a9c8af18f

我理解这篇文章,但看不出与上面得到的结果的关系。

你能用简单的例子解释一下HashingVectorizer是如何工作的吗

【问题讨论】:

    标签: python-3.x scikit-learn nlp vectorization text-classification


    【解决方案1】:

    我认为由于负值和默认标准化,结果没有意义。

    如果你这样做:

    vectorizer = HashingVectorizer(n_features=2**3,norm=None,alternate_sign=False)
    

    您应该会看到原始计数,结果应该开始有意义了。如果你想要标准化的词频,那么设置norm='l2'

    您打印的结果本质上是(document_id,position_in_matrix) counts

    有关更多信息,请参阅HashingVectorizer vs. CountVectorizer 上的这篇文章。

    【讨论】:

      【解决方案2】:

      结果是矩阵的sparse 表示(大小为 4x8)。

      print(X.toarray())
      

      输出:

      [[-0.89442719  0.          0.          0.          0.          0.4472136
         0.          0.        ]
       [-0.81649658  0.          0.          0.40824829  0.          0.40824829
         0.          0.        ]
       [ 0.          0.          0.          0.         -0.70710678  0.70710678
         0.          0.        ]
       [-0.89442719  0.          0.          0.          0.          0.4472136
         0.          0.        ]]
      

      为了得到一个标记的向量,我们计算它的哈希并得到矩阵中的列索引。该列是令牌的向量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-21
        • 2020-08-28
        • 2016-03-31
        • 2022-01-09
        • 1970-01-01
        • 2019-05-15
        • 1970-01-01
        • 2018-04-16
        相关资源
        最近更新 更多