LESSON 7.03 · 6 STAGES · 3 CONTROLS · 3 CHECKS
Word2Vec and GloVe
Watch words turn into vectors, so words used in the same places land close.
EXPLAINER · 7.03 · EMBEDDING BAY
01
Stage 1 of 6 · Context window
A context window of 2 pairs each word with its neighbours. The corpus gives 88 pairs.
Explain it simply
Each row is one sentence of a tiny corpus. The dashed box is the window around one word. Every other word inside the box makes a pair with the centre word. Both models learn only from these pairs.
Eight sentences in rows. A dashed box marks the window around cat. The corpus gives 88 pairs.
words and countsword vectorsscores and fitslosswindow, zero count
Toy: 8 sentences, 13 words, 3 numbers per word
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
2 words
Words on each side of the centre word.
5
Random words pushed down for each pair.
cat
The word whose neighbours the diagram shows.
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
Each word pairs with every word up to m places away.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import math
CORPUS = ["the cat is a pet", "the dog is a pet", "the cat has fur", "the dog has fur", "the tea is hot", "the coffee is hot", "a cup of tea", "a cup of coffee"]
WINDOW, NEG, QUERY = 2, 5, "cat"
DIM, SEED = 3, 703
def mulberry32(seed):
a, M = seed, 0xFFFFFFFF
def rand():
nonlocal a
a = (a + 0x6D2B79F5) & M
t = ((a ^ (a >> 15)) * (1 | a)) & M
t = ((t + (((t ^ (t >> 7)) * (61 | t)) & M)) & M) ^ t
return ((t ^ (t >> 14)) & M) / 2**32
return rand
sents = [s.split() for s in CORPUS]
vocab = list(dict.fromkeys(w for s in sents for w in s))
V, ix = len(vocab), {w: i for i, w in enumerate(vocab)}
dot = lambda a, b: sum(x * y for x, y in zip(a, b))
pow34 = lambda x: math.sqrt(x) * math.sqrt(math.sqrt(x))
# Word2Vec: skip-gram with negative sampling
pairs = [(ix[s[t]], ix[s[j]]) for s in sents for t in range(len(s))
for j in range(t - WINDOW, t + WINDOW + 1) if j != t and 0 <= j < len(s)]
print(len(pairs), "pairs") # 88 pairs
r = mulberry32(SEED)
v = [[(r() - 0.5) / DIM for _ in range(DIM)] for _ in range(V)]
u = [[0.0] * DIM for _ in range(V)]
counts = [sum(s.count(w) for s in sents) for w in vocab]
pw = [pow34(c) for c in counts]
z = sum(pw)
def draw():
x = r() * z
for i in range(V):
x -= pw[i]
if x < 0: return i
return V - 1
EPOCHS, LR = 300, 0.025
total, n = EPOCHS * len(pairs), 0
for epoch in range(EPOCHS):
for c, o in pairs:
lr = max(LR * (1 - n / total), LR * 1e-4)
n += 1
targets = [(o, 1)]
for _ in range(NEG):
w = draw()
if w != o: targets.append((w, 0))
e1 = [0.0] * DIM
for w, label in targets:
g = lr * (label - 1 / (1 + math.exp(-dot(u[w], v[c]))))
for d in range(DIM):
e1[d] += g * u[w][d]
u[w][d] += g * v[c][d]
for d in range(DIM):
v[c][d] += e1[d]
# GloVe: count, then fit log counts (AdaGrad)
X = [[0.0] * V for _ in range(V)]
for s in sents:
for t in range(len(s)):
for d in range(1, WINDOW + 1):
if t + d < len(s):
a, b = ix[s[t]], ix[s[t + d]]
X[a][b] += 1 / d
X[b][a] += 1 / d
XMAX, EPOCHS, LR = 1, 1000, 0.05
r = mulberry32(SEED + 1)
W = [[(r() - 0.5) / DIM for _ in range(DIM)] for _ in range(V)]
Wt = [[(r() - 0.5) / DIM for _ in range(DIM)] for _ in range(V)]
b = [(r() - 0.5) / DIM for _ in range(V)]
bt = [(r() - 0.5) / DIM for _ in range(V)]
gW, gWt = [[1.0] * DIM for _ in range(V)], [[1.0] * DIM for _ in range(V)]
gb, gbt = [1.0] * V, [1.0] * V
cells = [(i, j) for i in range(V) for j in range(V) if X[i][j] > 0]
for k in range(len(cells) - 1, 0, -1): # shuffle once
m = math.floor(r() * (k + 1))
cells[k], cells[m] = cells[m], cells[k]
for epoch in range(EPOCHS):
for i, j in cells:
f = pow34(X[i][j] / XMAX) if X[i][j] < XMAX else 1
fd = f * (dot(W[i], Wt[j]) + b[i] + bt[j] - math.log(X[i][j]))
for d in range(DIM):
t1, t2 = fd * Wt[j][d], fd * W[i][d]
W[i][d] -= LR * t1 / math.sqrt(gW[i][d])
Wt[j][d] -= LR * t2 / math.sqrt(gWt[j][d])
gW[i][d] += t1 * t1
gWt[j][d] += t2 * t2
b[i] -= LR * fd / math.sqrt(gb[i])
bt[j] -= LR * fd / math.sqrt(gbt[j])
gb[i] += fd * fd
gbt[j] += fd * fd
glove = [[W[i][d] + Wt[i][d] for d in range(DIM)] for i in range(V)]
def nearest(vecs, q, k=3):
cos = lambda a, b: dot(a, b) / math.sqrt(dot(a, a) * dot(b, b))
out = sorted((w for w in range(V) if w != ix[q]), key=lambda w: -cos(vecs[ix[q]], vecs[w]))
return [(vocab[w], round(cos(vecs[ix[q]], vecs[w]), 2)) for w in out[:k]]
print(nearest(v, QUERY)) # [('dog', 1.0), ('has', 0.99), ('is', 0.76)]
print(nearest(glove, QUERY)) # [('dog', 1.0), ('the', 1.0), ('tea', 0.84)]
Copy it into a file and run it. It trains both models on the toy corpus.
Common mix-ups
MYTHClose vectors mean the two words appear side by side.
FIXCat and dog never share a sentence, so their count is 0. They share every neighbour, so their cosine is 1.00.
MYTHWord2Vec needs only the true pairs.
FIXWith 0 negative samples, every score can reach 1 if all vectors turn one way. The mean cosine rises from 0.51 to 0.96.
Predict, then reveal
0 / 3 REVEALEDQ01With 5 negatives and a 1-word window, is cat's second nearest word in Word2Vec a drink or a pet word?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02With a 2-word window, does Word2Vec's cosine of cat and tea go up or down from 5 to 0 negatives?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03With a 2-word window and 5 negatives, which word is nearest to tea in both models?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Takeaways
- Words that share neighbours get vectors that point the same way.
- Word2Vec learns from one pair at a time; GloVe fits the whole count table.
- Negative samples stop all vectors from turning one way.