Sub topic 1
Why One-Hot Vectors Are Not Enough
This chapter shows why the simplest way to represent words as numbers fails for language tasks. It also sets up the problem that word2vec and GloVe solve in later chapters.
Prerequisites
This chapter assumes you know the following:
- Basic Python and NumPy, including array creation and indexing.
- Vectors, dot products and norms.
- Basic text preprocessing, meaning you can split a sentence into tokens.
You do not need any machine learning knowledge yet.
The one-hot representation
A model cannot read words. It needs numbers. The most direct choice is a one-hot vector. Build a vocabulary of V distinct words, give each word an index from 0 to V-1, and represent a word as a vector of length V with a 1 at its index and 0 everywhere else.
import numpy as np
vocab = ["cat", "dog", "mat", "sits", "the"]
index = {w: i for i, w in enumerate(vocab)}
def one_hot(word):
v = np.zeros(len(vocab))
v[index[word]] = 1.0
return v
print(one_hot("cat")) # [1. 0. 0. 0. 0.]
print(one_hot("dog")) # [0. 1. 0. 0. 0.]This is a sparse representation: almost every entry is zero. It is easy to build, it is exact, and it needs no data beyond the vocabulary. It also has three serious problems.
Problem 1: no notion of similarity
Compare two one-hot vectors with a dot product. Two different words always give 0, because their 1s sit at different positions. A word compared with itself gives 1.
print(np.dot(one_hot("cat"), one_hot("dog"))) # 0.0
print(np.dot(one_hot("cat"), one_hot("mat"))) # 0.0
print(np.dot(one_hot("cat"), one_hot("cat"))) # 1.0Under this representation, "cat" is exactly as far from "dog" as it is from "mat". Every pair of distinct words is orthogonal, so the Euclidean distance between any two different words is the same value, the square root of 2. The vectors carry identity and nothing else.
This matters in practice. Suppose a classifier has seen "The movie was excellent" labelled positive, and it later meets "The movie was superb". With one-hot inputs, "superb" is an unrelated dimension. Nothing learned about "excellent" transfers to it. The model must see every word, in enough examples, to learn anything about it.
Problem 2: dimensionality grows with the vocabulary
A one-hot vector has V entries. Realistic vocabularies are large:
| Vocabulary | Typical size V | Entries per word vector |
|---|---|---|
| Small domain corpus | 10,000 | 10,000 |
| General English text | 100,000 to 400,000 | 100,000 to 400,000 |
| Large web corpus | over 1,000,000 | over 1,000,000 |
Two consequences follow.
- Parameters. If the first layer of a neural network takes a one-hot input and maps it to H hidden units, that layer has V x H weights. With V = 400,000 and H = 300, that is 120 million weights, and most training examples touch only a few of them.
- Data sparsity. Each word has its own weights, and rare words appear too seldom to train them well. Most of the vocabulary is rare. In natural text a small set of words accounts for most of the tokens, and a long tail of words appears only a handful of times.
Storing a one-hot vector as a dense array wastes memory. Sparse formats, such as scipy.sparse, store only the nonzero positions and fix the memory problem. They do not fix the similarity problem.
from scipy.sparse import csr_matrix
# Three words from a 400,000-word vocabulary, stored sparsely.
rows = [0, 1, 2]
cols = [17, 52031, 399999]
X = csr_matrix(([1.0, 1.0, 1.0], (rows, cols)), shape=(3, 400_000))
print(X.nnz) # 3 stored values
print(X.shape) # (3, 400000)Problem 3: sentence vectors inherit the same flaws
Adding or averaging one-hot vectors gives a bag-of-words vector for a sentence. It is a reasonable baseline, but it keeps the same limitation. Two sentences that mean the same thing with different words, such as "a cheap flight" and "an inexpensive plane ticket", share no nonzero positions apart from function words. Their bag-of-words vectors look unrelated.
import numpy as np
vocab = ["a", "an", "cheap", "inexpensive", "flight", "plane", "ticket"]
index = {w: i for i, w in enumerate(vocab)}
def bag(sentence):
v = np.zeros(len(vocab))
for w in sentence.split():
v[index[w]] += 1
return v
s1 = bag("a cheap flight")
s2 = bag("an inexpensive plane ticket")
print(np.dot(s1, s2)) # 0.0, although the meanings are closeWhat we want instead
Look at what a better representation would do:
- Give similar words similar vectors, so that "cat" is closer to "dog" than to "mat".
- Use a fixed, small number of dimensions, such as 50 to 300, regardless of vocabulary size.
- Be learned from raw text, without hand-built dictionaries of synonyms.
A vector with these properties is a dense embedding. Its entries are real numbers, most of them nonzero, and the geometry of the space carries meaning. The next chapters explain where that meaning comes from and how to learn it.
Common errors and edge cases
- Treating sparse storage as a fix. Sparse matrices reduce memory use only. Every pair of distinct words is still orthogonal.
- Unknown words. A one-hot vector cannot represent a word missing from the vocabulary. The usual workaround is a shared
<UNK>token, which merges all unseen words into one identity. Dense embeddings share this weakness unless extra techniques are used, and a later chapter returns to it. - Index order is arbitrary. The index of a word carries no meaning. Sorting a vocabulary alphabetically or by frequency changes the vectors but not the information in them, so never feed a raw index into a model as if it were a number with magnitude.
- Stop words dominate counts. In bag-of-words vectors, words such as "the" and "of" take up large counts and can swamp the informative words. Weighting schemes such as TF-IDF reduce this, but they do not add similarity between different words.
- Confusing the lookup with the matrix product. Multiplying a one-hot vector by a weight matrix just selects one row of that matrix. Embedding layers in neural networks use this fact: they skip the multiplication and look the row up directly.
The last point is the bridge to what comes next. If the rows of that weight matrix are learned so that useful words get useful rows, the matrix becomes an embedding table.
import numpy as np
V, H = 5, 3
W = np.arange(V * H, dtype=float).reshape(V, H) # a toy weight matrix
x = np.zeros(V)
x[2] = 1.0 # one-hot vector for the word at index 2
print(x @ W) # [6. 7. 8.]
print(W[2]) # [6. 7. 8.], the same row, found by lookupSummary
One-hot vectors make all distinct words equally unrelated, grow with the vocabulary, and prevent a model from carrying knowledge from one word to another. A good representation needs low dimension, meaningful distance, and learnability from text. The next chapter introduces the idea that makes this possible: a word's meaning can be read from the words around it.
Exercise
A vocabulary has 200,000 words. A model's first layer maps a one-hot input to 100 hidden units. (a) How many weights does this layer have, ignoring biases? (b) What is the cosine similarity between the one-hot vectors for "good" and "great", and why does it limit the model?
Show answer
(a) 200,000 x 100 = 20,000,000 weights. (b) The cosine similarity is 0, because two distinct one-hot vectors have their 1s at different positions, so their dot product is 0. The model sees "good" and "great" as completely unrelated, so it cannot transfer what it learned about one word to the other.
Exercise
Multiplying a one-hot vector x by a weight matrix W of shape (V, H) gives x @ W. What does the result equal, and why does this make embedding layers cheap?
Show answer
The result equals the single row of W at the index of the 1 in x. A framework can therefore skip the V x H multiplication and read that row directly, which costs time proportional to H instead of V x H.