Word Embeddings: Word2Vec, GloVe, and FastText
What You'll Learn
- 1Derive the skip-gram objective and explain its O(V) softmax cost
- 2Replace the softmax with negative sampling and the 3/4 noise exponent
- 3Explain the GloVe least squares objective and fastText subword sum
- 4Compute cosine similarity and diagnose out of vocabulary behaviour
Static embeddings map every word to one fixed vector, so a training run over a billion tokens yields arithmetic like king minus man plus woman. The three classic objectives, skip-gram, GloVe, and fastText, turn raw co-occurrence counts into geometry along different routes. This lesson derives those objectives, the negative sampling trick that made them tractable, and the cost of their vocabularies.
Skip-Gram with Negative Sampling
Mikolov, Chen, Corrado, and Dean (2013) trained skip-gram on Google News, releasing 3,000,000 words and phrases in 300 dimensions. The ideal objective scores a true context word above all others with a softmax:
The denominator runs over the whole vocabulary, so each gradient step costs operations and a 400,000 word vocabulary makes training impossible. The skip-gram objective sums the log probability of every context word within a window of radius around each center word. Negative sampling replaces the denominator with a small sampled set of noise words, giving a logistic objective on one positive and negatives:
Each step now costs with between 5 and 20. The noise distribution is the unigram corpus distribution raised to an exponent :
GloVe and the Counting View
GloVe (Pennington, Socher, and Manning, 2014) skips the prediction loop and factorizes the co-occurrence matrix directly, weighting each pair by a function that saturates for very frequent pairs:
with for counts below and otherwise, using and . Zero co-occurrences contribute nothing while pairs counted at least 100 times reach full weight. fastText (Bojanowski, Joulin, Lopez-Paz, and Szlam, 2017) adds character n-grams so each word vector is a sum of its parts:
where holds the word itself plus n-grams of length 3 to 6, which makes unseen words encodable for the first time.
| Model | Corpus and vocabulary | Dim | Out of vocabulary | Memory at 300d |
|---|---|---|---|---|
| word2vec (2013) | Google News, 3,000,000 words and phrases | 300 | unknown token | 3.6 GB |
| GloVe 840B (2014) | Common Crawl, 2,200,000 word types | 300 | unknown token | 2.6 GB |
| GloVe 6B (2014) | Wikipedia plus Gigaword, 400,000 types | 300 | unknown token | 480 MB |
| fastText (2017) | Wikipedia, 1,000,000 types, n-grams 3 to 6 | 300 | composes from n-grams | 1.2 GB |
Memory is vocabulary times dimension times 4 bytes: 400,000 x 300 x 4 = 480,000,000 bytes, which is why truncated vocabularies matter on edge devices.
Similarity and Factorization
Cosine similarity ignores magnitude and measures the angle between two vectors:
Levy and Goldberg (2014) showed that skip-gram with negative sampling approximately factorizes the shifted positive pointwise mutual information matrix, with entries equal to the maximum of zero and , which is why linear offsets such as king minus man plus woman survive.
Worked Examples
Worked Code
import numpy as np
class SkipGramNegSampling:
def __init__(self, vocab, dim=64, lr=0.05, k=5):
self.idx = {w: i for i, w in enumerate(vocab)}
self.dim, self.lr, self.k = dim, lr, k
self.W_in = np.random.randn(len(vocab), dim) * 0.01
self.W_out = np.random.randn(len(vocab), dim) * 0.01
def train_pair(self, center, context, noise_p, rng):
neg = rng.choice(len(noise_p), size=self.k, p=noise_p)
h = self.W_in[center]
pos = self.W_out[context] @ h
neg_scores = self.W_out[neg] @ h
s_pos = 1.0 / (1.0 + np.exp(-pos))
s_neg = 1.0 / (1.0 + np.exp(-neg_scores))
g_out_pos = (s_pos - 1.0) * h
g_out_neg = s_neg[:, None] * h
g_in = ((s_pos - 1.0) * self.W_out[context]
+ (s_neg[:, None] * self.W_out[neg]).sum(axis=0))
self.W_out[context] -= self.lr * g_out_pos
self.W_out[neg] -= self.lr * g_out_neg
self.W_in[center] -= self.lr * g_in
def cosine(self, a, b):
va, vb = self.W_in[self.idx[a]], self.W_in[self.idx[b]]
return float(va @ vb / (np.linalg.norm(va) * np.linalg.norm(vb)))
vocab = ["king", "queen", "man", "woman", "prince"]
counts = np.array([800, 150, 50, 40, 20], dtype=float)
noise_p = counts ** 0.75
noise_p /= noise_p.sum()
model = SkipGramNegSampling(vocab, dim=64, k=5)
rng = np.random.default_rng(0)
pairs = [(0, 1), (0, 3), (1, 3), (2, 3), (3, 4)]
for _ in range(5000):
c, x = pairs[rng.integers(len(pairs))]
model.train_pair(c, x, noise_p, rng)
print("sim(queen, woman):", round(model.cosine("queen", "woman"), 3))
import numpy as np
from gensim.models import FastText, Word2Vec
sentences = [["king", "queen", "man", "woman", "prince", "princess"],
["king", "crown", "queen", "throne", "man", "woman"]]
w2v = Word2Vec(sentences, vector_size=100, window=5, min_count=1, sg=1, seed=42)
print("analogy:", w2v.wv.most_similar(positive=["queen", "king"],
negative=["man"], topn=1))
ft = FastText(vector_size=50, window=3, min_count=1, min_n=3, max_n=6, seed=42)
ft.build_vocab(sentences)
ft.train(sentences, total_examples=len(sentences), epochs=20)
print("OOV vector norm:", round(float(np.linalg.norm(ft.wv["unseenword"])), 4))
Real-World Applications
- Search ranking: embedding cosine similarity scores query to document relevance, and Google reported word2vec style vectors behind its semantic match features from 2013 onward.
- Memory budget: a 400,000 entry, 300 dimensional GloVe matrix is 480 MB in float32, so mobile deployments keep 50,000 to 100,000 entries or quantize to 8 bit.
- Morphology: fastText n-grams raise accuracy on languages with rich inflection, because rare forms still compose from shared subunits.
đĄWord2vec factorizes a PMI matrix
Common Mistakes
Comparing vectors trained on different corpora
Fix: Cosine scores are only comparable inside one model; retrain before mixing.
Using raw frequency as the noise distribution
Fix: Raise counts to the 0.75 power, otherwise rare words rarely appear as negatives.
Expecting static vectors to handle word sense
Fix: bank has one vector, so use contextual models when a word changes meaning by sentence.
Best Practices
- Train on a corpus matched to your domain, since vector geometry tracks the training distribution
- Report vocabulary size and dimension with any cosine threshold, since both change the score distribution
- Downsample frequent words near 1e-4 to 1e-5 so stop words stop dominating the gradient
Key Takeaways
- Negative sampling turns an O(V) softmax into O(k) logistic terms, with k between 5 and 20
- The noise exponent 0.75 lifted a 5 percent word to 8.9 percent of negative samples in the worked counts
- GloVe minimizes a weighted least squares error on log co-occurrence with f(x) = (x/100) raised to 0.75
- Memory equals vocabulary times dimension times 4 bytes: 400,000 by 300 floats costs 480 MB
Frequently Asked Questions
Why does the full softmax not scale?
The denominator sums exponentials for every training pair, so a 400,000 word vocabulary spends 400,000 multiply adds per pair. Negative sampling replaces it with terms, typically 5, cutting that cost by five orders of magnitude.
What is the difference between word2vec and GloVe?
Word2vec predicts context words with stochastic gradient descent over sampled pairs, while GloVe fits the precomputed co-occurrence matrix with weighted least squares. Both land near 0.7 Spearman correlation on word similarity benchmarks, and corpus choice matters more than the objective.
How do fastText and transformer embeddings differ?
fastText builds one static vector per word from character n-grams, so the vector never changes. Transformers produce a contextual vector per occurrence, resolving word sense at the cost of a full forward pass.
Interview Questions
Q1: Why raise word frequencies to the power 0.75?
It flattens the noise distribution: a word with 5 percent raw frequency became 8.9 percent of samples, giving rare words enough gradient to learn useful vectors.
Q2: How much memory does a 300 dimensional embedding table need?
Vocabulary times 300 times 4 bytes: 400,000 entries need 480 MB, while Google News with 3 million phrases needs 3.6 GB.