ArticleslgStudy

computer science

Feature hashing

Feature hashing is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Feature hashing rather than just read about it. In short: 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. 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.

Key takeaways

  • Feature hashing belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Feature hashing to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Feature hashing from memory before moving on to harder problems.

Reference excerpt

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. 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. This trick is often attributed to Weinberger et al. (2009), but there exists a much earlier description of this method published by John Moody in 1989.

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

to the term-document matrix

(JohnlikestowatchmoviesMarytooalsofootball111110000010011100110000011) (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. 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. 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 t in a finite (or countably infinite) set T. Suppose we only need to process a finite corpus, then we can put all tokens appearing in the corpus into T, meaning that T is finite. However, suppose we want to process all possible words made of the English letters, then T is countably infinite. Most neural networks can only operate on real vector inputs, so we must construct a "dictionary" function ϕ:T→ℝn. When T is finite, of size |T|=m≤n, then we can use one-hot encoding to map it into ℝn. First, arbitrarily enumerate T={t1,t2,..,tm}, then define ϕ(ti)=ei. In other words, we assign a unique index i to each token, then map the token with index i to the unit basis vector ei. One-hot encoding is easy to interpret, but it requires one to maintain the arbitrary enumeration of T. Given a token t∈T, to compute ϕ(t), we must find out the index i of the token t. Thus, to implement ϕ efficiently, we need a fast-to-compute bijection h:T→{1,...,m}, then we have ϕ(t)=eh(t). In fact, we can relax the requirement slightly: It suffices to have a fast-to-compute injection h:T→{1,...,n}, then use ϕ(t)=eh(t). In practice, there is no simple way to construct an efficient injection h:T→{1,...,n}. However, we do not need a strict injection, but only an approximate injection. That is, when t≠t′, we should probably have h(t)≠h(t′), so that probably ϕ(t)≠ϕ(t′). At this point, we have just specified that h should be a hashing function. Thus 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) is defined as follows. First, one specifies two hash functions: the kernel hash h:T→{1,2,...,n}, and the sign hash ζ:T→{−1,+1}. Next, one defines the feature hashing function:ϕ:T→ℝn,ϕ(t)=ζ(t)eh(t)Finally, extend this feature hashing function to strings of tokens byϕ:T∗→ℝn,ϕ(t1,...,tk)=∑j=1kϕ(tj)where T∗ is the set of all finite strings consisting of tokens in T. Equivalently,ϕ(t1,...,tk)=∑j=1kζ(tj)eh(tj)=∑i=1n(∑j:h(tj)=iζ(tj))ei

Geometric properties We want to say something about the geometric property of ϕ, but T, 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 T→ℝT, and lift ϕ from ϕ:T→ℝn to ϕ:ℝT→ℝn by linear extension: ϕ((xt)t∈T)=∑t∈Txtζ(t)eh(t)=∑i=1n(∑t:h(t)=ixtζ(t))eiThere 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 ℝT to contain only vectors with finite support: ∀(xt)t∈T∈ℝT, only finitely many entries of (xt)t∈T are nonzero. Define an inner product on ℝT in the obvious way: ⟨et,et′⟩={1, if t=t′,0, else.⟨x,x′⟩=∑t,t′∈Txtxt′⟨et,et′⟩As a side note, if T is infinite, then the inner product space ℝT is not complete. Taking its completion would get us to a Hilbert space, which allows well-behaved infinite sums.

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Feature hashing

Start with the simplest possible case. Write down what Feature hashing claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Feature hashing before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Feature hashing ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Feature hashing

In research
Feature hashing appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Feature hashing in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Feature hashing is common in secondary-school and first-year university syllabi. It links to neighbouring topics Hashing, Machine learning, so understanding it makes those chapters shorter.
In everyday life
Look for Feature hashing outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Feature hashing” →

How to study Feature hashing in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Feature hashing means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Feature hashing out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Feature hashing in simple terms?

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. It works by applying a hash function to the features and using their…

Why does Feature hashing matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Feature hashing?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Feature hashing.

Tags

  • Hashing
  • Machine learning

Keep exploring