Feature hashing

From HandWiki
Short description: Vectorizing features using a hash function

In machine learning, feature hashing, also known as the hashing trick (by analogy to the kernel trick), is a fast and space-efficient way of vectorizing features, i.e. turning arbitrary features into indices in a vector or matrix.[1][2] It works by applying a hash function to the features and using their hash values as indices directly (after a modulo operation), rather than looking the indices up in an associative array. In addition to its use for encoding non-numeric values, feature hashing can also be used for dimensionality reduction.[2]

This trick is often attributed to Weinberger et al. (2009),[2] but there exists a much earlier description of this method published by John Moody in 1989.[1]

Motivation

Motivating example

In a typical document classification task, the input to the machine learning algorithm (both during learning and classification) is free text. From this, a bag of words (BOW) representation is constructed: the individual tokens are extracted and counted, and each distinct token in the training set defines a feature (independent variable) of each of the documents in both the training and test sets.

Machine learning algorithms, however, are typically defined in terms of numerical vectors. Therefore, the bags of words for a set of documents is regarded as a term-document matrix where each row is a single document, and each column is a single feature/word; the entry i, j in such a matrix captures the frequency (or weight) of the j'th term of the vocabulary in document i. (An alternative convention swaps the rows and columns of the matrix, but this difference is immaterial.) Typically, these vectors are extremely sparse—according to Zipf's law.

The common approach is to construct, at learning time or prior to that, a dictionary representation of the vocabulary of the training set, and use that to map words to indices. Hash tables and tries are common candidates for dictionary implementation. E.g., the three documents

  • John likes to watch movies.
  • Mary likes movies too.
  • John also likes football.

can be converted, using the dictionary

Term Index
John 1
likes 2
to 3
watch 4
movies 5
Mary 6
too 7
also 8
football 9

to the term-document matrix

[math]\displaystyle{ \begin{pmatrix} \textrm{John} & \textrm{likes} & \textrm{to} & \textrm{watch} & \textrm{movies} & \textrm{Mary} & \textrm{too} & \textrm{also} & \textrm{football} \\ 1 & 1 & 1 & 1 & 1 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 1 & 1 & 1 & 0 & 0 \\ 1 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 1 \end{pmatrix} }[/math]

(Punctuation was removed, as is usual in document classification and clustering.)

The problem with this process is that such dictionaries take up a large amount of storage space and grow in size as the training set grows.[3] On the contrary, if the vocabulary is kept fixed and not increased with a growing training set, an adversary may try to invent new words or misspellings that are not in the stored vocabulary so as to circumvent a machine learned filter. To address this challenge, Yahoo! Research attempted to use feature hashing for their spam filters.[4]

Note that the hashing trick isn't limited to text classification and similar tasks at the document level, but can be applied to any problem that involves large (perhaps unbounded) numbers of features.

Mathematical motivation

Mathematically, a token is an element [math]\displaystyle{ t }[/math] in a finite (or countably infinite) set [math]\displaystyle{ T }[/math]. Suppose we only need to process a finite corpus, then we can put all tokens appearing in the corpus into [math]\displaystyle{ T }[/math], meaning that [math]\displaystyle{ T }[/math] is finite. However, suppose we want to process all possible words made of the English letters, then [math]\displaystyle{ T }[/math] is countably infinite.

Most neural networks can only operate on real vector inputs, so we must construct a "dictionary" function [math]\displaystyle{ \phi: T\to \R^n }[/math].

When [math]\displaystyle{ T }[/math] is finite, of size [math]\displaystyle{ |T| = m \leq n }[/math], then we can use one-hot encoding to map it into [math]\displaystyle{ \R^n }[/math]. First, arbitrarily enumerate [math]\displaystyle{ T = \{t_1, t_2, .., t_m\} }[/math], then define [math]\displaystyle{ \phi(t_i) = e_i }[/math]. In other words, we assign a unique index [math]\displaystyle{ i }[/math] to each token, then map the token with index [math]\displaystyle{ i }[/math] to the unit basis vector [math]\displaystyle{ e_i }[/math].

One-hot encoding is easy to interpret, but it requires one to maintain the arbitrary enumeration of [math]\displaystyle{ T }[/math]. Given a token [math]\displaystyle{ t\in T }[/math], to compute [math]\displaystyle{ \phi(t) }[/math], we must find out the index [math]\displaystyle{ i }[/math] of the token [math]\displaystyle{ t }[/math]. Thus, to implement [math]\displaystyle{ \phi }[/math] efficiently, we need a fast-to-compute bijection [math]\displaystyle{ h: T\to \{1, ..., m\} }[/math], then we have [math]\displaystyle{ \phi(t) = e_{h(t)} }[/math].

In fact, we can relax the requirement slightly: It suffices to have a fast-to-compute injection [math]\displaystyle{ h: T\to \{1, ..., n\} }[/math], then use [math]\displaystyle{ \phi(t) = e_{h(t)} }[/math].

In practice, there is no simple way to construct an efficient injection [math]\displaystyle{ h: T\to \{1, ..., n\} }[/math]. However, we do not need a strict injection, but only an approximate injection. That is, when [math]\displaystyle{ t\neq t' }[/math], we should probably have [math]\displaystyle{ h(t) \neq h(t') }[/math], so that probably [math]\displaystyle{ \phi(t) \neq \phi(t') }[/math].

At this point, we have just specified that [math]\displaystyle{ h }[/math] should be a hashing function. Thus, ineluctably, we reach the idea of feature hashing.

Algorithms

Feature hashing (Weinberger et al. 2009)

The basic feature hashing algorithm presented in (Weinberger et al. 2009)[2] is defined as follows.

First, one specifies two hash functions: the kernel hash [math]\displaystyle{ h: T\to \{1, 2, ..., n\} }[/math], and the sign hash [math]\displaystyle{ \zeta: T\to \{-1, +1\} }[/math]. Next, one defines the feature hashing function:[math]\displaystyle{ \phi: T\to \R^n, \quad \phi(t) = \zeta(t) e_{h(t)} }[/math]Finally, extend this feature hashing function to strings of tokens by[math]\displaystyle{ \phi: T^* \to \R^n, \quad \phi(t_1, ..., t_k) =\sum_{j=1}^k \phi(t_j) }[/math]where [math]\displaystyle{ T^* }[/math] is the set of all finite strings consisting of tokens in [math]\displaystyle{ T }[/math].

Equivalently,[math]\displaystyle{ \phi(t_1, ..., t_k) = \sum_{j=1}^k \zeta(t_j) e_{h(t_j)} = \sum_{i=1}^n \left(\sum_{j: h(t_j)=i} \zeta(t_j)\right) e_i }[/math]

Geometric properties

We want to say something about the geometric property of [math]\displaystyle{ \phi }[/math], but [math]\displaystyle{ T }[/math], by itself, is just a set of tokens, we cannot impose a geometric structure on it except the discrete topology, which is generated by the discrete metric. To make it nicer, we lift it to [math]\displaystyle{ T\to \R^T }[/math], and lift [math]\displaystyle{ \phi }[/math] from [math]\displaystyle{ \phi: T \to \R^n }[/math] to [math]\displaystyle{ \phi: \R^T \to \R^n }[/math] by linear extension: [math]\displaystyle{ \phi((x_t)_{t\in T}) = \sum_{t\in T} x_t \zeta(t) e_{h(t)} = \sum_{i=1}^n \left(\sum_{t: h(t)=i} x_t \zeta(t)\right) e_i }[/math]There is an infinite sum there, which must be handled at once. There are essentially only two ways to handle infinities. One may impose a metric, then take its completion, to allow well-behaved infinite sums, or one may demand that nothing is actually infinite, only potentially so. Here, we go for the potential-infinity way, by restricting [math]\displaystyle{ \R^T }[/math] to contain only vectors with finite support: [math]\displaystyle{ \forall (x_t)_{t\in T} \in \R^T }[/math], only finitely many entries of [math]\displaystyle{ (x_t)_{t\in T} }[/math] are nonzero.

Define an inner product on [math]\displaystyle{ \R^T }[/math] in the obvious way: [math]\displaystyle{ \langle e_t, e_{t'} \rangle = \begin{cases} 1, \text{ if }t=t', \\ 0, \text{ else.} \end{cases} \quad \langle x, x'\rangle = \sum_{t, t'\in T} x_t x_{t'} \langle e_t, e_{t'} \rangle }[/math]As a side note, if [math]\displaystyle{ T }[/math] is infinite, then the inner product space [math]\displaystyle{ \R^T }[/math] is not complete. Taking its completion would get us to a Hilbert space, which allows well-behaved infinite sums.


Now we have an inner product space, with enough structure to describe the geometry of the feature hashing function [math]\displaystyle{ \phi: \R^T \to \R^n }[/math].

First, we can see why [math]\displaystyle{ h }[/math] is called a "kernel hash": it allows us to define a kernel [math]\displaystyle{ K: T\times T \to \R }[/math] by[math]\displaystyle{ K(t, t') = \langle e_{h(t)}, e_{h(t')}\rangle }[/math]In the language of the "kernel trick", [math]\displaystyle{ K }[/math] is the kernel generated by the "feature map" [math]\displaystyle{ \varphi : T \to \R^n, \quad \varphi(t) = e_{h(t)} }[/math]Note that this is not the feature map we were using, which is [math]\displaystyle{ \phi(t) = \zeta(t) e_{h(t)} }[/math]. In fact, we have been using another kernel [math]\displaystyle{ K_{\zeta}: T\times T \to \R }[/math], defined by [math]\displaystyle{ K_\zeta (t, t') = \langle \zeta(t)e_{h(t)}, \zeta(t')e_{h(t')}\rangle }[/math]The benefit of augmenting the kernel hash [math]\displaystyle{ h }[/math] with the binary hash [math]\displaystyle{ \zeta }[/math] is the following theorem, which states that [math]\displaystyle{ \phi }[/math] is an isometry "on average".

Theorem (intuitively stated) — If the binary hash [math]\displaystyle{ \zeta }[/math] is unbiased (meaning that it takes value [math]\displaystyle{ -1, +1 }[/math] with equal probability), then [math]\displaystyle{ \phi: \R^T \to \R^n }[/math] is an isometry in expectation:[math]\displaystyle{ \mathbb{E}[\langle \phi(x), \phi(x') \rangle] = \langle x, x' \rangle. }[/math]


The above statement and proof interprets the binary hash function [math]\displaystyle{ \zeta }[/math] not as a deterministic function of type [math]\displaystyle{ T\to \{-1, +1\} }[/math], but as a random binary vector [math]\displaystyle{ \{-1, +1\}^T }[/math] with unbiased entries, meaning that [math]\displaystyle{ Pr(\zeta(t) = +1) = Pr(\zeta(t) = -1) = \frac 1 2 }[/math] for any [math]\displaystyle{ t\in T }[/math].

This is a good intuitive picture, though not rigorous. For a rigorous statement and proof, see [2]

Pseudocode implementation

Instead of maintaining a dictionary, a feature vectorizer that uses the hashing trick can build a vector of a pre-defined length by applying a hash function h to the features (e.g., words), then using the hash values directly as feature indices and updating the resulting vector at those indices. Here, we assume that feature actually means feature vector.

function hashing_vectorizer(features : array of string, N : integer):
     x := new vector[N]
     for f in features:
         h := hash(f)
         x[h mod N] += 1
     return x

Thus, if our feature vector is ["cat","dog","cat"] and hash function is [math]\displaystyle{ h(x_f)=1 }[/math] if [math]\displaystyle{ x_f }[/math] is "cat" and [math]\displaystyle{ 2 }[/math] if [math]\displaystyle{ x_f }[/math] is "dog". Let us take the output feature vector dimension (N) to be 4. Then output x will be [0,2,1,0]. It has been suggested that a second, single-bit output hash function ξ be used to determine the sign of the update value, to counter the effect of hash collisions.[2] If such a hash function is used, the algorithm becomes

function hashing_vectorizer(features : array of string, N : integer):
     x := new vector[N]
     for f in features:
         h := hash(f)
         idx := h mod N
         if ξ(f) == 1:
             x[idx] += 1
         else:
             x[idx] -= 1
     return x

The above pseudocode actually converts each sample into a vector. An optimized version would instead only generate a stream of [math]\displaystyle{ (h, \zeta) }[/math] pairs and let the learning and prediction algorithms consume such streams; a linear model can then be implemented as a single hash table representing the coefficient vector.

Extensions and variations

Learned feature hashing

Feature hashing generally suffers from hash collision, which means that there exist pairs of different tokens with the same hash: [math]\displaystyle{ t\neq t', \phi(t) = \phi(t') = v }[/math]. A machine learning model trained on feature-hashed words would then have difficulty distinguishing [math]\displaystyle{ t }[/math] and [math]\displaystyle{ t' }[/math], essentially because [math]\displaystyle{ v }[/math] is polysemic.

If [math]\displaystyle{ t' }[/math] is rare, then performance degradation is small, as the model could always just ignore the rare case, and pretend all [math]\displaystyle{ v }[/math] means [math]\displaystyle{ t }[/math]. However, if both are common, then the degradation can be serious.

To handle this, one can train supervised hashing functions that avoids mapping common tokens to the same feature vectors.[5]

Applications and practical performance

Ganchev and Dredze showed that in text classification applications with random hash functions and several tens of thousands of columns in the output vectors, feature hashing need not have an adverse effect on classification performance, even without the signed hash function.[3]

Weinberger et al. (2009) applied their version of feature hashing to multi-task learning, and in particular, spam filtering, where the input features are pairs (user, feature) so that a single parameter vector captured per-user spam filters as well as a global filter for several hundred thousand users, and found that the accuracy of the filter went up.[2]

Chen et al. (2015) combined the idea of feature hashing and sparse matrix to construct "virtual matrices": large matrices with small storage requirements. The idea is to treat a matrix [math]\displaystyle{ M\in \R^{n\times n} }[/math] as a dictionary, with keys in [math]\displaystyle{ n\times n }[/math], and values in [math]\displaystyle{ \R }[/math]. Then, as usual in hashed dictionaries, one can use a hash function [math]\displaystyle{ h: \N\times \N\to m }[/math], and thus represent a matrix as a vector in [math]\displaystyle{ \R^m }[/math], no matter how big [math]\displaystyle{ n }[/math] is. With virtual matrices, they constructed HashedNets, which are large neural networks taking only small amounts of storage.[6]

Implementations

Implementations of the hashing trick are present in:

See also

References

  1. 1.0 1.1 Moody, John (1989). "Fast learning in multi-resolution hierarchies". Advances in Neural Information Processing Systems. http://papers.nips.cc/paper/175-fast-learning-in-multi-resolution-hierarchies.pdf. 
  2. 2.0 2.1 2.2 2.3 2.4 2.5 2.6 Kilian Weinberger; Anirban Dasgupta; John Langford; Alex Smola; Josh Attenberg (2009). "Feature Hashing for Large Scale Multitask Learning". Proc. ICML. http://alex.smola.org/papers/2009/Weinbergeretal09.pdf. 
  3. 3.0 3.1 K. Ganchev; M. Dredze (2008). "Small statistical models by random feature mixing". Proc. ACL08 HLT Workshop on Mobile Language Processing. http://www.cs.jhu.edu/~mdredze/publications/mobile_nlp_feature_mixing.pdf. 
  4. Josh Attenberg; Kilian Weinberger; Alex Smola; Anirban Dasgupta; Martin Zinkevich (2009). "Collaborative spam filtering with the hashing trick". Virus Bulletin. https://www.virusbulletin.com/virusbulletin/2009/11/collaborative-spam-filtering-hashing-trick. 
  5. Bai, B.; Weston J.; Grangier D.; Collobert R.; Sadamasa K.; Qi Y.; Chapelle O.; Weinberger K. (2009). "Supervised semantic indexing". CIKM. pp. 187–196. http://www.cs.cornell.edu/~kilian/papers/ssi-cikm.pdf. 
  6. Chen, Wenlin; Wilson, James; Tyree, Stephen; Weinberger, Kilian; Chen, Yixin (2015-06-01). "Compressing Neural Networks with the Hashing Trick" (in en). International Conference on Machine Learning (PMLR): 2285–2294. https://proceedings.mlr.press/v37/chenc15.html. 
  7. Owen, Sean; Anil, Robin; Dunning, Ted; Friedman, Ellen (2012). Mahout in Action. Manning. pp. 261–265. 
  8. "gensim: corpora.hashdictionary – Construct word<->id mappings". Radimrehurek.com. http://radimrehurek.com/gensim/corpora/hashdictionary.html. Retrieved 2014-02-13. 
  9. "4.1. Feature extraction — scikit-learn 0.14 documentation". Scikit-learn.org. http://scikit-learn.org/stable/modules/feature_extraction.html#feature-hashing. Retrieved 2014-02-13. 
  10. "sofia-ml - Suite of Fast Incremental Algorithms for Machine Learning. Includes methods for learning classification and ranking models, using Pegasos SVM, SGD-SVM, ROMMA, Passive-Aggressive Perceptron, Perceptron with Margins, and Logistic Regression". https://code.google.com/p/sofia-ml/. Retrieved 2014-02-13. 
  11. "Hashing TF". https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.mllib.feature.HashingTF. Retrieved 4 September 2015. "Maps a sequence of terms to their term frequencies using the hashing trick." 
  12. "FeatureHashing: Creates a Model Matrix via Feature Hashing With a Formula Interface". https://cran.r-project.org/web/packages/FeatureHashing/index.html. 
  13. "tf.keras.preprocessing.text.hashing_trick — TensorFlow Core v2.0.1". https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/text/hashing_trick. Retrieved 2020-04-29. "Converts a text to a sequence of indexes in a fixed-size hashing space." 
  14. "dask_ml.feature_extraction.text.HashingVectorizer — dask-ml 2021.11.17 documentation". https://ml.dask.org/modules/generated/dask_ml.feature_extraction.text.HashingVectorizer.html#dask_ml.feature_extraction.text.HashingVectorizer. 

External links