首页 > 解决方案 > TfidfVectorizer toarray() 和 HashingVectorizer 的含义

问题描述

我正在尝试理解 python 中的矢量化器。我正在使用这个示例代码:

from sklearn.feature_extraction.text import TfidfVectorizer
# list of text documents
text = ["The quick brown fox jumped over the lazy dog.", "The dog.", "The fox"]
print(text)
# create the transform
vectorizer = TfidfVectorizer()
# tokenize and build vocab
vectorizer.fit(text)
# summarize
print(vectorizer.idf_)
# encode document
vector = vectorizer.transform([text[0]])
# summarize encoded vector
print(vector.shape)
print(vector.toarray())
print(vectorizer.vocabulary_)

输出是这样的:

['The quick brown fox jumped over the lazy dog.', 'The dog.', 'The fox']
[1.69314718 1.28768207 1.28768207 1.69314718 1.69314718 1.69314718
1.69314718 1.        ]
(1, 8)
[[0.36388646 0.27674503 0.27674503 0.36388646 0.36388646 0.36388646
0.36388646 0.42983441]]
{'the': 7, 'quick': 6, 'brown': 0, 'fox': 2, 'jumped': 3, 'over': 5, 
'lazy': 4, 'dog': 1}

我不明白为什么 vector.toarray() 会为不同的单词产生重复的数字..例如有 0.36388646 四次..和 0.27674503 两次..这个数字是什么?神经网络用来训练自己的数字是用vectorizer.vocabulary_打印的数字吗?

使用散列矢量化器,我有以下代码:

from sklearn.feature_extraction.text import HashingVectorizer
# list of text documents
text = ["The quick brown fox jumped over the lazy dog."]
# create the transform
vectorizer = HashingVectorizer(n_features=20)
# encode document
vector = vectorizer.fit_transform(text)
# summarize encoded vector
print(vector.shape)
print(vector.toarray())

这就是输出:

(1, 20)
[[ 0.          0.          0.          0.          0.          0.33333333
 0.         -0.33333333  0.33333333  0.          0.          0.33333333
 0.          0.          0.         -0.33333333  0.          0.
-0.66666667  0.        ]]

是否使用了 0. 值?什么礼物?为什么即使在那里打印重复值?(0.3333333 和 -0.33333333)

标签: pythonmachine-learningscikit-learn

解决方案


  • 在第一种情况下,您会看到重复的数字,因为您的“语料库”中有多个具有相同 IDF(逆文档频率)的单词。例如,单词dogfox在您的文本中具有完全相同的出现模式,因此它们具有相同的 IDF;这两个由 1.28768207 值表示。单词the出现在每个文本中,因此由 1 表示。词汇表中的其余单词在第一个文本中出现一次,而不在其他两个文本中出现,因此它们都具有完全相同的 IDF。您可以看到哪个特征对应于哪个单词vectorizer.get_feature_names()
  • 使用 HashingVectorizer,您选择的特征数为 20,但文本中唯一单词的总数少于 20,因此您将有很多为 0 的特征。您得到的非零元素少于 8 个因为有一些散列冲突 - 那是因为 20 是太少的功能,以避免冲突(考虑默认为 2^20)。如果您选择更高的n_features,您将获得正好 8 个非零元素。您有重复的值,因为几乎所有特征在该文本中具有相同的频率。
  • 对于您标题中的问题,该toarray()方法将 sklearn 使用的稀疏矩阵的有效表示转换为您的普通可读密集 ndarray 表示。

推荐阅读