FeatureHasher与DictVectorizer的比较¶
通过同时使用FeatureHasher和DictVectorizer对文本文档进行矢量化来进行比较。
该示例仅演示语法和速度。 它实际上对提取的向量没有任何帮助。 有关实际学习文本文档的信息,请参见示例脚本{document_classification_20newsgroups,clustering} .py。
由于哈希冲突,预计DictVectorizer和FeatureHasher报告的术语数量会有差异。
输出:
Usage: /home/circleci/project/examples/text/plot_hashing_vs_dict_vectorizer.py [n_features_for_hashing]
The default number of features is 2**18.
Loading 20 newsgroups training data
3803 documents - 6.245MB
DictVectorizer
done in 1.313812s at 4.753MB/s
Found 47928 unique terms
FeatureHasher on frequency dicts
done in 0.842164s at 7.415MB/s
Found 43873 unique terms
FeatureHasher on raw tokens
done in 0.792912s at 7.876MB/s
Found 43873 unique terms
输入:
# Author: Lars Buitinck
# License: BSD 3 clause
from collections import defaultdict
import re
import sys
from time import time
import numpy as np
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction import DictVectorizer, FeatureHasher
def n_nonzero_columns(X):
"""返回CSR矩阵X中非零列的数量"""
return len(np.unique(X.nonzero()[1]))
def tokens(doc):
"""从文档中提取出符号(tokens)。
在这里我们使用一个简单的正则表达式将字符串分解为符号。
对于更多原则性方法,请参见CountVectorizer或TfidfVectorizer。
"""
return (tok.lower() for tok in re.findall(r"\w+", doc))
def token_freqs(doc):
'''从doc中提取一个将令牌映射到其频率的字典。'''
freq = defaultdict(int)
for tok in tokens(doc):
freq[tok] += 1
return freq
categories = [
'alt.atheism',
'comp.graphics',
'comp.sys.ibm.pc.hardware',
'misc.forsale',
'rec.autos',
'sci.space',
'talk.religion.misc',
]
# 下面这行取消注释以使用更大的注释集(超过11k个文档)
# categories = None
print(__doc__)
print("Usage: %s [n_features_for_hashing]" % sys.argv[0])
print(" The default number of features is 2**18.")
print()
try:
n_features = int(sys.argv[1])
except IndexError:
n_features = 2 ** 18
except ValueError:
print("not a valid number of features: %r" % sys.argv[1])
sys.exit(1)
print("Loading 20 newsgroups training data")
raw_data, _ = fetch_20newsgroups(subset='train', categories=categories,
return_X_y=True)
data_size_mb = sum(len(s.encode('utf-8')) for s in raw_data) / 1e6
print("%d documents - %0.3fMB" % (len(raw_data), data_size_mb))
print()
print("DictVectorizer")
t0 = time()
vectorizer = DictVectorizer()
vectorizer.fit_transform(token_freqs(d) for d in raw_data)
duration = time() - t0
print("done in %fs at %0.3fMB/s" % (duration, data_size_mb / duration))
print("Found %d unique terms" % len(vectorizer.get_feature_names()))
print()
print("FeatureHasher on frequency dicts")
t0 = time()
hasher = FeatureHasher(n_features=n_features)
X = hasher.transform(token_freqs(d) for d in raw_data)
duration = time() - t0
print("done in %fs at %0.3fMB/s" % (duration, data_size_mb / duration))
print("Found %d unique terms" % n_nonzero_columns(X))
print()
print("FeatureHasher on raw tokens")
t0 = time()
hasher = FeatureHasher(n_features=n_features, input_type="string")
X = hasher.transform(tokens(d) for d in raw_data)
duration = time() - t0
print("done in %fs at %0.3fMB/s" % (duration, data_size_mb / duration))
print("Found %d unique terms" % n_nonzero_columns(X))
脚本的总运行时间:0分3.296秒。