Sub topic 1
Why one-hot vectors are not enough
Prerequisites
You should be comfortable with basic Python and NumPy, dot products and vector norms, and splitting text into tokens (words or punctuation marks).
Why one-hot vectors are not enough
A one-hot vector gives each word in a vocabulary of size V its own dimension. If the vocabulary is [cat, dog, mat], then "cat" is [1, 0, 0] and "dog" is [0, 1, 0]. Any two different words have a dot product of 0, so the vectors carry no information about similarity. "cat" is as far from "dog" as it is from "carburetor". A real vocabulary of 100,000 words also means 100,000 mostly-zero dimensions.
You shall know a word by the company it keeps
The distributional hypothesis says that words used in similar contexts tend to have similar meanings. J. R. Firth put it this way in 1957: "You shall know a word by the company it keeps." "Cat" and "dog" both appear near "feed", "pet", and "sits", so a model can learn that they are related from text alone.
Dense embeddings: words as points in a vector space
A dense embedding is a short vector of real numbers, usually 50 to 300 dimensions, learned from data. Related words end up near each other in this space. Word2vec and GloVe both produce dense embeddings.
Measuring similarity with cosine
Cosine similarity compares the direction of two vectors and ignores their length:
cos(u, v) = (u · v) / (‖u‖ ‖v‖)
import numpy as np
def cosine(u, v):
return float(np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v)))
a = np.array([1.0, 0.0])
b = np.array([1.0, 1.0])
print(cosine(a, b)) # 0.7071..., the cosine of a 45 degree angleContext windows and (word, context) pairs
A context window of size k marks the k words on each side of a center word. Word2vec turns each window into training pairs. The diagram shows the pairs for the center word "sits" in the sentence "the cat sits on the mat" with window size 2.
word2vec: learning embeddings by prediction
word2vec is a family of models that learn embeddings by predicting words. Skip-gram predicts context words from a center word. CBOW predicts a center word from its context. Neither task is the goal itself. The embedding is the weight matrix the model learns while it gets better at the prediction. Later sections cover how that training works.
Exercise
The vocabulary has 5 words. What is the cosine similarity between the one-hot vectors for two different words?
Show answer
0. Their dot product is 0, so the cosine is 0 for every pair of distinct words.