Search

Search papers and lessons

One-Hot Encoding

Level 1 · 10 min read

One-hot encoding turns a category into a vector with a single 1 in the slot for that category and 0s everywhere else, so a model can read names as numbers.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Probability
  • Representation learning
  • Linear algebra
  • ReadReady to readNot yet

TL;DR

One-hot encoding represents a category as a vector that has a single 1 in the slot for that category and 0s in every other slot. A model that works only with numbers can then read names such as colours, words or breeds. Every pair of different categories ends up the same distance apart, which is both its use and its main limit.

Builds on: Vector, Indicator Variable · Leads to: Embedding Layer, Softmax

Where it's used

Tables with category columns. A dataset of houses has a column "neighbourhood" with values such as North, South and Central. A regression cannot multiply by the word North. Each neighbourhood becomes a column of 0s and 1s, as in the linear regression of prices, and the model learns one effect per column.

Image labels. The standard image benchmark ImageNet has 1000 classes. The label for a picture of a dog is a vector of length 1000 with a 1 at the dog's position and 999 zeros. A classifier is trained to produce a Probability for each of the 1000 slots, and the one-hot label tells it which slot should be high.

Words in language models. A language model reads text as a sequence of tokens from a fixed vocabulary, often tens of thousands long. Each token's position in the vocabulary gives its one-hot vector. The first layer of the model then turns that vector into a learned embedding, which is the real input to the rest of the network.

How it works

Take a tiny example with three colours: red, green and blue. Each step adds one idea.

flowchart LR
  A["Category: green"] --> B["Slot number: 2"]
  B --> C["Zeros: 0, 0, 0"]
  C --> D["Set slot 2 to 1: 0, 1, 0"]
  1. Fix an order. Number the categories: red is slot 1, green is slot 2, blue is slot 3. Check: the order is arbitrary, but it must stay the same for every example.

  2. Make a vector of zeros. Start with three zeros, (0,0,0)(0, 0, 0). Check: the vector has one slot per category.

  3. Put a 1 in the right slot. For green, the slot is 2, so set it to 1: (0,1,0)(0, 1, 0). Check: exactly one entry is 1.

  4. Do the same for every colour. Red becomes (1,0,0)(1, 0, 0) and blue becomes (0,0,1)(0, 0, 1). Check: the three vectors are three different positions on a grid of unit steps.

  5. Feed the vectors to the model. A linear model multiplies inputs by weights and adds them up. For a one-hot input, this sum picks out one weight per output, because every other input is multiplied by 0. Check: with input (0,1,0)(0, 1, 0), only the weight in slot 2 contributes.

  6. Check the distances. Compare red and green by Euclidean distance: (1,0,0)−(0,1,0)=(1,−1,0)(1, 0, 0) - (0, 1, 0) = (1, -1, 0), whose length squared is 12+(−1)2=21^2 + (-1)^2 = 2. Red and blue are the same distance apart, and so are green and blue. Check: every pair of different colours is equally far apart.

Step 6 is the hidden cost. Red is no more like green than it is like blue. If the categories have a real order or similarity, such as sizes small, medium and large, one-hot throws that information away. Embeddings are the usual fix, and they start from this encoding.

The math

Definition: One-hot vector

Let a category set have KK members, numbered 11 to KK. The one-hot vector for member kk is the vector ek∈RKe_k \in \mathbb{R}^K whose kk-th entry is 1 and whose other entries are 0. Written out, eke_k has KK entries and exactly one of them is nonzero.

Step 1 in symbols: the order

Give each member a number kk from 11 to KK. The encoding c↦ek(c)c \mapsto e_{k(c)} maps a category cc to the vector for its number k(c)k(c). The map is a bijection, so no two categories share a vector.

Step 3 in symbols: the vector

For K=3K = 3 and the colours, e1=(1,0,0)e_1 = (1, 0, 0), e2=(0,1,0)e_2 = (0, 1, 0), e3=(0,0,1)e_3 = (0, 0, 1). These are the standard basis vectors of R3\mathbb{R}^3 (see Vector). Each has length 1, and any two are perpendicular, which is why every pair is the same distance apart.

Step 5 in symbols: picking a row

Let WW be a K×dK \times d Matrix of weights, with one row per category. For a one-hot input eke_k, the matrix product is

ek⊤W=Wk,⋅,e_k^{\top} W = W_{k,\cdot},

the kk-th row of WW. The sum over slots is ∑j(ek)j Wj,⋅\sum_{j} (e_k)_j\, W_{j,\cdot}, and every term with j≠kj \neq k has factor 0, so only the kk-th row survives. The multiplication is a lookup. This is the reason one-hot inputs and learned embedding tables are the same idea.

Step 6 in symbols: the distance

For two different categories j≠kj \neq k, the squared Euclidean distance is

∥ej−ek∥2=12+(−1)2=2,\lVert e_j - e_k \rVert^2 = 1^2 + (-1)^2 = 2,

and it is 2 for every pair. In general the squared distance between any two different one-hot vectors is 2. A distance that is the same for every pair says nothing about which categories are similar.

Worked examples

Example
Example 1: tiny, three colours

Categories: red, green, blue, numbered 1, 2, 3.

  1. Red: slot 1, so the vector is (1,0,0)(1, 0, 0).
  2. Blue: slot 3, so the vector is (0,0,1)(0, 0, 1).
  3. Dot product of red and blue: 1⋅0+0⋅0+0⋅1=01 \cdot 0 + 0 \cdot 0 + 0 \cdot 1 = 0. The dot product of a vector with a different one-hot vector is 0.
  4. Dot product of blue with itself: 0⋅0+0⋅0+1⋅1=10 \cdot 0 + 0 \cdot 0 + 1 \cdot 1 = 1.
  5. Interpretation: the dot product is 1 for the same category and 0 for different ones, so it measures "same or not".
Example
Example 2: the standard case, a lookup table

Three animals: cat, dog, fish, numbered 1, 2, 3. Weights WW with one row per animal, two numbers each:

W=(0.5−120−0.51).W = \begin{pmatrix} 0.5 & -1 \\ 2 & 0 \\ -0.5 & 1 \end{pmatrix}.
  1. The one-hot vector for dog is e2=(0,1,0)e_2 = (0, 1, 0).
  2. Multiply on the left: e2⊤W=0⋅(0.5,−1)+1⋅(2,0)+0⋅(−0.5,1)e_2^{\top} W = 0 \cdot (0.5, -1) + 1 \cdot (2, 0) + 0 \cdot (-0.5, 1).
  3. Add the terms: (0,0)+(2,0)+(0,0)=(2,0)(0, 0) + (2, 0) + (0, 0) = (2, 0).
  4. Compare with the row: row 2 of WW is (2,0)(2, 0). They match.
  5. Interpretation: the multiplication selected the dog's row. A model with one-hot inputs therefore learns a separate vector for each animal, by adjusting only the row that was selected.
Example
Example 3: realistic, a vocabulary of 50,000 words

A language model has a vocabulary of 50,000 words and turns each word into a vector of 768 numbers, which is a common size for a small model. The first layer is a Matrix EE with one row per word.

  1. Count the entries of the matrix: 50,000×768=38,400,00050{,}000 \times 768 = 38{,}400{,}000 numbers.
  2. Build a one-hot vector for the word with index 4,201: a vector of length 50,000 with a 1 in position 4,201 and 49,999 zeros.
  3. Multiply: e4201⊤Ee_{4201}^{\top} E returns row 4,201 of EE, which is 768 numbers.
  4. Compare the cost: the full product would multiply 50,000 numbers per output entry, almost all by 0. Reading the row directly needs only 768 numbers.
  5. Interpretation: the one-hot view explains the model, and the lookup is how it runs efficiently. The 768 numbers are the learned embedding of that word.

Try it: a vocabulary of 10,000 words with 300-dimensional embeddings. How many numbers are in the matrix EE, and how many numbers does a single lookup read? Answer: 10,000×300=3,000,00010{,}000 \times 300 = 3{,}000{,}000 numbers in the matrix, and a lookup reads one row, which is 300 numbers.

Common mistakes and tradeoffs

It is tempting to think that numbering the categories 1, 2, 3 is the same as one-hot encoding. In fact a single number per category suggests that category 2 lies between 1 and 3 and that 3 is three times 1. One-hot removes that false order, because each category gets its own slot and no slot is "bigger".

It is tempting to think one-hot encoding is compact. In fact the vector has one entry per category, so a vocabulary of 50,000 words gives vectors of length 50,000, almost all zeros. Storage grows with the number of categories, and new categories need a new slot.

It is tempting to think all categories are equally different. In fact one-hot says they are all equally far apart, which is true only in the encoding and usually false in the world. Shoes and boots are closer than shoes and bread, and one-hot cannot say so.

One-hot encoding is a good choice when there are few categories, when no order or similarity is known, and when a linear model or a lookup is the goal. It is a poor choice when there are many categories, when categories are related, or when new categories appear often. Alternatives include learned embeddings, which give each category a short dense vector that is trained to reflect similarity, and target encoding, which replaces each category with a summary of the outcome.

History

Using one wire or one bit per state is a classic trick in digital circuit design, and one-hot state encodings were used there to make circuits faster to decode. Statistics developed the same idea as dummy variables in regression, where each category becomes an indicator, and that name is older than the machine-learning term.

The term one-hot became common in machine learning as neural networks began to take words and labels as input. Word embeddings in the early 2010s, such as the models of Mikolov and colleagues in 2013, learned a dense vector for each word from a one-hot starting point, so one-hot is often the first step in describing a text pipeline.

Recap

  • A one-hot vector has a single 1 in the slot for its category and 0s elsewhere.
  • Multiplying a one-hot vector by a weight matrix selects one row, which is a lookup.
  • Any two different one-hot vectors are the same distance apart, so the encoding carries no similarity.
  • The main cost is length: one slot per category.
  • Read next: Embedding Layer for the learned dense version, and Softmax for how a model's output is read as one-hot-style probabilities.

Check yourself

QuestionWrite the one-hot vector for the third of four categories, and say how many zeros it has.Show answer

The vector has length 4 with a 1 in slot 3, so it is (0,0,1,0)(0, 0, 1, 0). It has three zeros.

QuestionUsing the weight matrix in Example 2, what vector does the one-hot input for cat, (1,0,0)(1, 0, 0), produce?Show answer

Multiplying gives the first row of WW, which is (0.5,−1)(0.5, -1). The one-hot input selects row 1, the cat row.

QuestionWhy does one-hot encoding fail to tell the model that two similar categories are similar?Show answer

Every pair of different one-hot vectors has squared distance 2 and dot product 0. The encoding gives every pair the same geometry, so nothing in the vectors reflects how similar the categories are in the world. A learned embedding can place similar categories close together, which one-hot cannot.

QuestionA dataset has 2,000 product categories. How long is each one-hot vector, and what does that imply for a model with a 64-number embedding per category?Show answer

Each one-hot vector has length 2,000. The embedding replaces it with 64 numbers, so the embedding table has 2,000×64=128,0002{,}000 \times 64 = 128{,}000 learned numbers, far fewer per category than the 2,000 slots of the one-hot vector.

Sources