Embeddings: Words as Coordinates

Chapter 3 · Applied Natural Language Processing

Dr. Batuhan Bardak

After this lecture you can

  • turn the distributional hypothesis into a matrix, reweight it with PPMI and compress it with truncated SVD
  • write skip-gram with negative sampling from scratch and explain how two vector tables are learned together under a logistic loss
  • choose between word2vec, GloVe, fastText and doc2vec for a given problem, and defend the choice
  • examine how the space is not spread evenly over directions (anisotropy), how frequency affects the representation, and how cosine reflects relations broader than synonymy
  • explain the context-independent representation of static embeddings and discuss why the contextual representations of Chapter 7 are needed

The problem, in one sentence

  • Chapter 2 built document vectors that work — and word vectors that do not
  • Every word was a one-hot column: pump, pumps and impeller are three mutually orthogonal directions
  • The cosine between two different one-hots is exactly zero
  • In a linear model that uses only word counts, pump and pumps are separate features: train on the pump failed, test on the pumps failed, and the weight learned for pump does not carry over to pumps by itself

In linear-algebra terms: multiply the one-hot vectors by a learned matrix. Each word gets 100 or 300 numbers, and we aim for words used in similar ways to end up close. That short, dense vector is an embedding.

Three kinds of embedding, one chapter

Kind Example Does a word get the same vector everywhere?
Static word embedding word2vec, GloVe, fastText Yes — one vector per word form
Contextual token embedding BERT No — each token’s vector is computed from its context in the sequence; one word can be several tokens
Sentence / document embedding SBERT and similar One vector for the whole sentence or document

This chapter is about static word embeddings, with a short introduction to document vectors. Contextual representations belong to Chapter 7, and the use of sentence and document representations in retrieval to Chapter 19.

The distributional hypothesis

“You shall know a word by the company it keeps.” — J.R. Firth, 1957

  • Harris (1954) had already put the working version: the meaning of a word can be recovered from the distribution of contexts it appears in
  • Words that fill the same blanks — the ___ failed, replaced the , pressure — mean something similar
  • Not a theorem: a hypothesis tested against data. Shared contexts help identify topical or functional closeness; they do not by themselves identify synonymy — hot and cold share many contexts too
  • No hand-labelled examples are needed: the training signal is derived from the contexts in raw text

That makes it possible to learn representations from large unlabelled corpora.

Count first: co-occurrence, PPMI, SVD

Ten sentences

corpus = [
    "the king rules the castle",
    "the queen rules the castle",
    "the king eats an apple",
    "the queen eats a banana",
    "the royal castle is grand",
    "a banana is sweet fruit",
    "an apple is sweet fruit",
    "the man eats an apple",
    "the woman eats a banana",
    "the king and queen are royal",
]

Step 1 · count within ±2 tokens

eats rules royal sweet the
king 1 1 0 0 4
queen 1 1 1 0 3
apple 2 0 0 1 0
banana 2 0 0 1 0
  • king ≈ queen and apple ≈ banana: the hypothesis is already working
  • The largest count in the king row is the. Raw counts are affected by the association and also by how frequent the words are overall.

Step 2 · PMI is observed ÷ expected

\[\mathrm{PMI}(w, c) = \log \frac{P(w, c)}{P(w)\,P(c)}\]

  • Ratio 1: the observed probability of the pair equals what the independence model predicts, PMI 0 — that does not mean there is no semantic relationship
  • Above 1: more often than expected, positive. Below 1: less often than expected, negative
  • For rare words, a few co-occurrences may not be enough to estimate a negative association reliably
  • Positive PMI (PPMI) sets negative values to zero; a useful representational choice, not a claim that every negative value is meaningless:

\[\mathrm{PPMI}(w, c) = \max\!\left(0,\ \log \frac{c_{wc}\, N}{c_{w\ast}\, c_{\ast c}}\right)\]

Work one cell by hand

All four numbers are read off \(C\): the pair count \(c_{wc}\), the row total \(c_{w\ast}\), the column total \(c_{\ast c}\) and \(N = 144\) — not the 51 tokens but all (word, neighbour) pairs.

pair observed expected ratio PMI
apple–sweet 1 \(7 \times 6 / 144 = 0.29\) 3.43 1.23
king–the 4 \(9 \times 22 / 144 = 1.38\) 2.91 1.07
  • The pair observed once gets the higher PMI, because its observed-to-expected ratio is larger
  • The expectations do not say how much of what we observed is “explained”; PMI compares two relative frequencies
  • The transformation does not guarantee that an association resting on a single observation is reliable

Quick check · PPMI

Two words each occur 10 times in a million-token corpus and never co-occur. Why clip the negative PMI values instead of keeping them?

  • Counting only the tokens immediately to the left and right, the expected directed co-occurrence count is about \(2 \times 10 \times 10 / 10^6 = 0.0002\); observing zero is unsurprising
  • Widening the window to two tokens on each side roughly doubles the expectation
  • The PMI of a zero count goes to \(-\infty\); the finite value obtained with smoothing depends on the method chosen
  • The negative PMI estimates of rare pairs can be strongly affected by sampling uncertainty; clipping at zero leaves those values out of the representation and makes the matrix sparser

Step 3 · Truncated SVD

  • The PPMI rows already behave sensibly: king → queen 0.55. But apple → man 0.79: the two rows carry high weights in the an and eats columns, and man occurs in a single sentence
  • Keep only the \(d\) directions with the largest singular values — the best rank-\(d\) approximation in the Frobenius norm:

\[\mathrm{PPMI} \approx U_d \Sigma_d V_d^\top, \qquad \text{embedding} = U_d \Sigma_d\]

  • Here five components carry 65.4% of the sum of squares — not of the variance, since PPMI is never centred
  • Truncation can reduce some accidental detail, and it can also lose useful distinctions; what is kept is decided by the singular-value structure, not by how often something repeats

What the compression actually did

word pair PPMI rows, 19-D SVD, 5-D what happened
apple – banana 0.40 1.00 never share a sentence; shared contexts link them, and compression makes the link decisive
king – queen 0.55 0.90 already right, and got stronger
apple – man 0.79 0.85 the one-sentence accident — not deleted, but no longer first

SVD does not break the wrong link; it strengthens the right one enough to overtake it. The ordering improves; the absolute values do not.

Deerwester et al. 1990 — latent semantic analysis, more than twenty years before word2vec

Ten sentences, two coordinates

dimension 2 dimension 3 royalty people food king queen royal castle rules man woman eats apple banana fruit sweet
  • Royalty words on the left, food words on the right
  • man and woman are close in this view; their contexts are not identical
  • The first coordinate is negative for every word (−0.70 … −2.14): a shared direction, which is why we plot dimensions 2 and 3
  • Not spread evenly over directions: anisotropy, measured on GloVe later

From counting to predicting

  • Scalability was an important factor: ten billion possible cells at 100,000 words; batch PPMI–SVD counts first and factorizes afterwards
  • word2vec (Mikolov et al. 2013): learns vectors from local training pairs without building the matrix explicitly
  • In skip-gram, a shallow network: the centre word’s one-hot → that row of \(\mathbf{W}\) (a lookup, no activation) → \(\mathbf{W}'\) scores candidate contexts. In CBOW the context vectors are combined first
  • Mostly \(\mathbf{W}\) is kept; not a requirement

We set up the prediction task to learn vectors we can reuse. A transformer’s input embedding table (Chapter 7) works similarly; its rows belong to tokens.

CBOW and skip-gram: arrows reversed

One window on the pump failed during the night shift: centre failed, width 2.

CBOW · context → centre

the pump during the → average → failed

  • One training example per window
  • Usually faster; combines the context vectors

Skip-gram · centre → context

failed → its own vector → the pump during the

  • Four training examples per window
  • More training pairs; can help on rare words

Both learn \(\mathbf{W}\) (word → vector) and \(\mathbf{W}'\) (scores partners); the pretrained vectors you download are mostly rows of \(\mathbf{W}\). The rest of the chapter follows skip-gram, which is also what negative sampling is most often paired with.

Negative sampling with a logistic loss

  • The full softmax computes and normalizes \(V\) context scores for every training pair: about \(O(Vd)\). Negative sampling changes the objective; the scoring cost is about \(O((K+1)d)\)
  • The new question: did this training example come from the observed pairs (\(y=1\)) or from the noise sampler (\(y=0\))? The same pair can be produced either way. For each observed pair, \(K\) contexts are drawn from a noise distribution \(q\)

\[P(y = 1 \mid w, c;\, K, q) = \sigma(\mathbf{v}_w \cdot \mathbf{u}_c), \qquad \sigma(z) = \frac{1}{1 + e^{-z}}\]

\[\mathcal{L} = -\log \sigma(\mathbf{v}_w \cdot \mathbf{u}_c) - \sum_{k=1}^{K} \log \sigma(-\mathbf{v}_w \cdot \mathbf{u}_{n_k})\]

  • The positive pair’s term falls as the dot product grows; a negative sample’s term falls as its dot product shrinks
  • \(K = 5\), \(V = 400{,}000\): six dot products per pair in place of 400,000 — about 67,000 times fewer; the actual speed-up depends on hardware and implementation

Mikolov et al. 2013

Work one update by hand

Four dimensions in place of 300. Centre failed: \(\mathbf{v} = (0.4,\ -0.2,\ 0.7,\ 0.1)\). Positive context pump: \(\mathbf{u} = (0.5,\ 0.1,\ 0.6,\ -0.3)\). Sampled negative opera: \(\mathbf{u} = (-0.3,\ 0.6,\ -0.2,\ 0.4)\).

pair \(y\) \(\mathbf{v} \cdot \mathbf{u}\) \(\sigma(\mathbf{v} \cdot \mathbf{u})\) loss \(\sigma - y\)
failed–pump 1 0.57 0.639 0.448 −0.361
failed–opera 0 −0.34 0.416 0.538 0.416
  • The derivative of one labelled term with respect to the dot product is \(\sigma(z) - y\): prediction minus target
  • Update only \(\mathbf{v}\) at learning rate 0.05: failed·pump 0.570 → 0.590; failed·opera −0.340 → −0.359
  • Update the context vectors too: 0.603 and −0.374 — the same directions, roughly 1.7 times as far

One pair touches at most seven rows

\[\frac{\partial \mathcal{L}}{\partial \mathbf{v}_w} = \bigl(\sigma(z) - y\bigr)\,\mathbf{u}_c, \qquad \frac{\partial \mathcal{L}}{\partial \mathbf{u}_c} = \bigl(\sigma(z) - y\bigr)\,\mathbf{v}_w\]

  • The gradient of each vector is the scalar error \(\sigma(z) - y\) times the other vector. When the correct label gets a high probability the scalar error is small; that alone does not guarantee stable training
  • One pair with \(K = 5\): one row of \(\mathbf{W}\) and \(1 + K\) rows of \(\mathbf{W}'\) — at most seven distinct rows
  • The remaining rows do not enter this pair’s data loss; their gradients are zero. Under SGD with no momentum and no weight decay those rows do not change
  • The model we train from scratch has 37,354 rows; seven is about 0.019%. A full softmax affects 18,678 rows, 2,668 times as many — a ratio of rows, not of running time

Four training choices that decide how well word2vec works

choice what it sets typical value effect
Number of negatives (\(K\)) negatives per positive pair 5–20 for a small corpus, 2–5 for a large one in the original work changes the balance between cost and training signal
Context window candidate neighbours and weighting by distance for example at most 5, with a dynamic window narrow windows can bring out functional relations more, wide ones topical relations
Subsampling (\(t\)) probability of keeping very frequent tokens for example \(t = 10^{-3}\) reduces the share of frequent words in training
Noise distribution probability of drawing each negative \(q(w) \propto f(w)^{0.75}\) raises the relative sampling share of rare words

The update itself is simple. What decides quality: which pairs you show, how often, and against what.

Two of the choices, in numbers: subsampling and the 0.75 exponent

Subsampling

share of corpus example kept discarded
5% the 0.16 84%
1% of, and 0.42 58%
0.1% (\(= t\)) mid-frequency 1.00 0%
0.01% and below the tail 1.00 0%

In our run 26.6% of the in-vocabulary tokens go: 6,397,826 → 4,698,743.

Negatives are drawn with \(f(w)^{0.75}\)

  • A word 5,000 times more frequent is only about 595 times more likely to be drawn — the gap narrows about eightfold
  • The exponent raises the relative share of rare contexts; it adds no new kind of signal
  • An empirical choice, not a theoretical optimum

Levy et al. (2015): hyperparameters of this kind can affect comparison results substantially.

Writing it from scratch

NumPy, no framework; trained on the first 40 million characters of text8. The update step:

v = Wc[c]                                              # (B, D)
u = Wo[targets]                                        # (B, K+1, D)
score = sigmoid(np.einsum("bkd,bd->bk", u, v))         # (B, K+1)
err = (score - labels).astype(np.float32)              # predicted − observed
gv = np.einsum("bk,bkd->bd", err, u)
gu = err[:, :, None] * v[:, None, :]
np.clip(gv, -1.0, 1.0, out=gv)
np.clip(gu, -1.0, 1.0, out=gu)
np.add.at(Wc, c, -lr * gv)
np.add.at(Wo, targets.ravel(), (-lr * gu).reshape(-1, D))

err = score - labels is predicted minus observed; every gradient is that difference times the other vector. After three epochs: monday → friday 0.87, france → spain 0.79, physics → mechanics 0.82.

The link between counting and predicting

Levy and Goldberg (2014): how skip-gram with negative sampling relates to matrix factorization.

\[\mathbf{v}_w \cdot \mathbf{u}_c = \mathrm{PMI}(w, c) - \log K\]

  • The conditions: negatives come from the context marginal and every dot product can be chosen independently; then this is the optimal target for pairs with a positive count
  • Not every version of word2vec is identical to PPMI–SVD: shared low-dimensional vectors may not meet all the optima, and the 0.75 exponent changes the target
  • For an explicit matrix: SPPMI \(= \max(\mathrm{PMI} - \log K,\ 0)\)

Levy et al. (2015): with matched hyperparameters, on the tasks they examined, the performance gap largely closes.

Baroni et al. 2014 · Levy & Goldberg 2014 · Levy, Goldberg & Dagan 2015

Where the −log K comes from

Fix one pair and treat \(z = \mathbf{v}_w \cdot \mathbf{u}_c\) as a free number. If the negatives are drawn from the context marginal \(P(c)\), the pair’s contribution to the objective to be maximized is:

\[P(w,c)\,\log \sigma(z) \;+\; K\,P(w)P(c)\,\log \sigma(-z)\]

Set the derivative to zero, \(P(w,c)\bigl(1 - \sigma(z)\bigr) = K\,P(w)P(c)\,\sigma(z)\), and solve:

\[z = \log \frac{P(w,c)}{K\,P(w)P(c)} = \mathrm{PMI}(w,c) - \log K\]

The derivation assumes negatives drawn from \(P(c)\) and a \(z\) that can be chosen independently for every pair. In the actual model the dot products are built from shared vectors; SGNS minimizes a sampling-weighted logistic loss, PPMI–SVD the squared error of a clipped matrix. Both the losses and the targets can differ.

GloVe: counting, with a loss function

\[\mathcal{L} = \sum_{(w,c)\,:\,X_{wc} > 0} f(X_{wc}) \left(\mathbf{v}_w \cdot \mathbf{u}_c + b_w + b_c - \log X_{wc}\right)^2\]

  • Accumulates co-occurrence counts explicitly; learns vectors and biases with a count-weighted squared error
  • Why \(\log X\)? Counts span a wide range; logs turn ratios into differences
  • Why the biases? They can model overall usage tendencies; the dot products are not exactly PMI
  • Why \(f\)? Down-weights rare pairs, capped at 1 for \(x \geq 100\); zero counts are outside the sum

\(f(x) = (x/x_{\max})^{3/4}\) for \(x < x_{\max} = 100\), else 1

\(X_{wc}\) \(f(X_{wc})\)
1 0.03
10 0.18
100 1.00
100,000 1.00

Pennington et al. 2014

What a word is now

Pretrained GloVe: 400,000 vectors, 100 dimensions, trained on Wikipedia 2014 + Gigaword 5 (6 billion tokens).

query nearest neighbours what it shows
king prince 0.77, queen 0.75, son 0.70 —
pump pumps 0.84, pumping 0.77, pumped 0.71 pumps is a neighbour, not an orthogonal axis
turkey ankara 0.75, turkish 0.72, greece 0.71 words about the country stand out
python monty 0.69, php 0.59, perl 0.58, flipper 0.51 neighbours from different usages together
bank banks 0.81, banking 0.75, credit 0.70 words about finance stand out

The defining limitation of a static embedding: one vector per word form, whatever the context. That limitation is one of the important reasons for the context-dependent token representations of Chapter 7.

king − man + woman ≈ queen?

Inputs removed

word cosine
queen 0.7699
monarch 0.6843
throne 0.6756
daughter 0.6595
princess 0.6521

The same scores, unfiltered

word cosine
king 0.8361
queen 0.7699
monarch 0.6843
throne 0.6756
daughter 0.6595

gensim normalizes the inputs and removes them from the candidates. With the scores fixed, the unfiltered nearest neighbour is king; queen is first only without the inputs. The candidate set is part of the task.

Evaluating analogies

  • The scoring is called 3CosAdd: it combines the candidate’s cosines with the three inputs using two plus signs and one minus. Excluding the inputs is a separate evaluation rule. 3CosMul (Levy and Goldberg 2014) gives better results in some evaluations
  • Linzen (2016): a nearest-neighbour baseline that ignores the relation reaches a large share of the reported accuracy in some categories
  • In five of the book’s eight selected examples the unfiltered nearest candidate is an input; that proportion does not measure analogy accuracy in general
  • mice − mouse + goose: the expected geese is third in the unfiltered list and second, behind cows, once the inputs are removed
  • madrid − spain + germany: munich comes ahead of berlin. The expected answer is not first; that does not prove the model carries no information about the capital relation

Turkish makes more than twice the word forms

Two Wikipedia samples of comparable size:

Turkish English
tokens 1,458,213 1,828,840
distinct word forms 138,578 78,140
forms seen after 1 million tokens 112,644 52,347
forms seen exactly once (hapax) 50.0% 46.7%
test tokens outside the training vocabulary 7.33% 4.72%

ev, evim, evimde, evimdeki, evlerimizdekiler are five separate vocabulary entries. In the held-out Turkish portion about one token in fourteen falls outside the training vocabulary. The numbers belong to one sample and one tokenization choice.

fastText: a word is built from its pieces

\[\mathbf{v}_w = \mathbf{1}_{\{w \in \mathcal{V}\}}\,\mathbf{z}_w + \sum_{g \in G(w)} \mathbf{z}_g\]

  • The separate whole-word component exists only for words in the vocabulary; an out-of-vocabulary word is built from its subword components
  • Shared character n-grams receive updates from examples in different words: <pu inside pump, pumps, pumped, pumping, punch … Not every piece is learned from plentiful data; the n-grams are mapped to a fixed number of hash buckets

pumps, seen in training: <pu pum ump mps ps> <pumps>

pumpage, never seen: <pu pum ump mpa pag age ge> — word2vec: KeyError

Drawn with 3-grams so it stays readable; fastText’s default is every n-gram of length 3 to 6, so a real pumpage decomposes into 22 pieces, not 7.

What subwords buy

Out-of-vocabulary words: two Turkish forms the Turkish Wikipedia sample never contained, then two typos. word2vec raises KeyError; fastText still gives a vector:

word fastText’s nearest neighbours
kitaplarımızdaki kitapları 0.91, kitapların 0.91, kitaplıkları 0.90
bilgisayarcılık bilgisayara 0.96, bilgisayarlı 0.96, bilgisayar 0.96
philosphy philosophy 0.96, philosophie 0.95, philosophies 0.94
governmentt government 0.98, governments 0.94, governmental 0.93

Shared character pieces help with some typos as well: in these examples the out-of-vocabulary forms get vectors close to the expected words. That result is not guaranteed for every typo.

What subwords cost

query fastText word2vec
kitap (book) kitapta 0.96, kitaba 0.95, kitab 0.94 eseri 0.81, makale 0.80, eseriyle 0.80
yaz (summer; also “write”) yao 0.78, yağ 0.77, yağdı 0.77 kış 0.86, olimpiyatları 0.84, aylarında 0.83
cosine of kitap–kitle 0.667 0.446
  • kitap: inflections or semantic neighbours? It depends on your task. yaz: spelling neighbours come to the front in fastText
  • The ratio of 0.667 to 0.446 cannot be read as “half again as similar”: the cosine distributions of the two spaces can differ

fastText is a strong candidate where out-of-vocabulary forms and inflection matter. Character sharing can also create unwanted closeness: evaluate by coverage and task performance.

Documents as vectors

Chapter 2’s four 20 Newsgroups categories, same split, same logistic regression on top:

representation accuracy dimensions
TF-IDF (Ch. 2 baseline) 0.853 32,014
averaged GloVe 0.820 100
idf-weighted averaged GloVe 0.822 100
doc2vec (PV-DBOW, 40 epochs) 0.839 100
averaged GloVe + doc2vec 0.845 200

On this split TF-IDF has the highest accuracy. In the paired test its gap to averaged GloVe is hard to explain by chance: 135 documents against 84, p = 0.0007.

The standard error of one accuracy (≈ 0.010) is not that of the difference between two models. The two GloVe averages: 66 against 63 (p = 0.86). No such calculation for the doc2vec rows: their predictions cannot be reproduced exactly.

What averaging destroys

  • Coverage: GloVe covers 98.6% of the tokens and 84.5% of the types; the uncovered forms are 1.4% of the token mass, and averaging leaves them out
a = "the pump failed and the valve is fine"
b = "the valve failed and the pump is fine"
  • Cosine of the two averaged vectors: 1.0000. The same tokens occur the same number of times, so the unordered mean is mathematically the same vector
  • In floating point the order of addition produces small differences: np.allclose is True, the bit-level comparison is False (largest difference \(1.2 \times 10^{-7}\))

Averaging does not keep the word order that determines which part failed: chapter 2’s bag-of-words problem, now in 100 dimensions. Word order needs a model that reads the sequence (Chapters 6 and 7).

In this space, cosine reflects relatedness more than similarity

pair cosine
good – bad 0.770
hot – cold 0.725
increase – decrease 0.881
cat – dog 0.880
cat – car 0.311
teacher – student 0.808
  • The antonym pair gets a high cosine too — the antonym problem; the gap between 0.881 and 0.880 is not a meaningful ordering
  • The model sees a word’s surroundings: hot and cold appear next to the same words
  • In this space cosine mostly reflects relatedness

Do not read the raw cosine of static vectors directly as a measure of sentiment or polarity.

The space is not isotropic

4,000 unit vectors from the top 50,000 GloVe words

statistic value
mean cosine, random pairs 0.029
standard deviation 0.119
pairs with cosine > 0 56.9%
norm of the mean vector 0.171
mean cosine after centring −0.000
  • Isotropic = the same in every direction. Anisotropic = not; a shift toward a common direction is one form, not a requirement
  • Mean cosine and mean-vector norm are one piece of evidence: \(\bar{c} = (n\lVert\bar{v}\rVert^2 - 1)/(n-1) \approx 0.029\)
  • Random pairs show how unusual a score is; a fixed 0.3 does not by itself mean a semantic relation
  • Centring removes the mean direction, not all anisotropy. All-but-the-top (Mu, Bhat and Viswanath 2018): measure on the task

Frequency leaks in; your domain lives in the tail

Frequent words have longer vectors on average: mean norm 6.19 for the top 100 words, 3.62 for ranks 100,000–400,000.

term rank nearest neighbours
water 430 natural 0.70, dry 0.68, salt 0.68
turbine 15,747 turbines 0.80, compressor 0.78, generator 0.72
cavitation 109,044 aliasing 0.56, barotrauma 0.54, attenuation 0.54
impeller 124,835 armature 0.62, evaporator 0.61, nozzle 0.60
eutectic 159,022 azeotrope 0.61, azeotropic 0.55, tiwai 0.54

Evaluate domain terms separately. Neighbour lists are a good first check; choose the method by comparing pretrained, domain-adapted and subword representations with task metrics.

Arbitrary coordinates, variable runs

Same corpus, same settings, two seeds (text8, 6,794,527 tokens)

measurement value
same word, raw coordinates: mean cosine −0.016
after orthogonal (Procrustes) alignment +0.951
top-10 neighbour overlap, 1,000 most frequent 62.2%
top-10 neighbour overlap, 1,000 rarest 46.6%
largest cosine change under an orthogonal map 5.5 × 10⁻⁷
  • Multiply both tables by the same orthogonal \(R\): \((WR)(UR)^\top = WU^\top\) — every coordinate changes, no dot product does
  • A coordinate’s meaning in one run may not survive a change of coordinates
  • +0.951: the coordinates explain much of the difference, not all — the neighbour overlaps show local differences remain

Same corpus + different seed → geometrically different, functionally similar spaces. Do not argue from one neighbour list of one run.

Bias is in the data, and the geometry records it

Projection onto woman − man

word projection
homemaker +0.363
nurse +0.329
receptionist +0.281
teacher +0.152
doctor +0.109
scientist −0.046
programmer −0.083
engineer −0.123

The sign shows the direction of the projection on the chosen axis; it does not measure all of social bias.

  1. Usually not a training error — associations in the data carry over into the geometry; what you measure depends on the corpus, the model and the axis
  2. It can carry over into decisions — depending on the downstream objective, inputs and decision rule; evaluate the application’s outputs too
  3. One intervention does not remove every indicator — gender-related information can remain (Gonen & Goldberg 2019)

Bolukbasi et al. 2016 · Caliskan et al. 2017 · Gonen & Goldberg 2019

How do you know an embedding is any good?

  • Intrinsic: does the space agree with human judgements — similarity ratings, analogies? Fast; needs no real task
  • Extrinsic: does it improve the thing you care about? Slow, but the evaluation that measures the contribution directly
  • The same GloVe vectors: WordSim-353 Spearman 0.533; SimLex-999 0.296. The coverage of the sets and their kinds of judgement differ too; the gap cannot be explained by antonymy alone
  • Intrinsic scores are useful for comparing properties and eliminating candidates; for choosing what to deploy, performance and cost on the target task decide (Schnabel et al. 2015)

Google analogies: 0.633 overall

category accuracy
capital-common-countries 0.939
capital-world 0.889
nationality-adjective 0.879
family 0.816
city-in-state 0.308
opposite 0.201
currency 0.152

The same dataset, different evaluated examples

GloVe · 6 billion tokens from scratch · 6.8 million tokens
WordSim-353 0.533 · 0.0% skipped 0.627 · 11.9% skipped
the 311 common pairs 0.549 0.627
Analogies, questions scored 0.633 · 19,486 0.200 · 9,282
Analogies, all 19,544 questions 0.631 0.095
  • WordSim: the small model is ahead on the common pairs too — here coverage does not close the gap. Analogies: counting skipped questions as wrong (dummy4unknown=True) halves the small model’s score
  • All 58 questions GloVe skips contain denar: in the vocabulary (rank 394,434), outside the default limit of 300,000

Give the coverage and the number of examples scored together with the score. The direction of the effect of skipped examples depends on which examples are skipped.

Choosing between them

method reach for it when watch for
PPMI + SVD you want to inspect the steps of the computation, or set up a count-based baseline on a modest vocabulary sparse count matrix, low-rank factors and solver memory; no row for out-of-vocabulary forms
word2vec you want to learn word vectors from a domain corpus — measuring against fastText performance depends on sampling, settings and coverage; the final vectors alone are not enough to continue training
GloVe you want a quick start with released vectors that cover the language and domain you need training needs the co-occurrence data prepared; coverage of a released vocabulary varies with language and domain
fastText the OOV rate, inflectional variety or spelling variability is high the subword table needs extra memory; similar spelling can create unwanted closeness (kitap/kitle 0.667)

Evaluate the coverage gain on task performance and hard negatives (the measurement in Chapter 4). For documents: on the single split of this experiment none of the dense methods beat the TF-IDF row; that finding does not cover every classification or retrieval task.

Applications in production systems

  • Airbnb search ranking — listing embeddings from skip-gram on click sessions: session = sentence, listing = word, the booked listing as global context (Grbovic & Cheng 2018)
  • YouTube recommendations — the embeddings of watched videos and of search tokens are averaged separately and passed, with other user information, to a deep candidate-generation network; the network’s output is the user representation (Covington et al. 2016)
  • Item2vec — skip-gram-like objectives can be applied to item co-occurrences such as purchase baskets; not every *2vec uses the same objective (Barkan & Koenigstein 2016)
  • fastText for classification — the vectors of word and word n-gram features with a linear output layer on top (Joulin et al. 2017); not the same unit as character n-grams
  • Retrieval with vectors — some of the systems in Chapters 19 and 20 represent texts as vectors; RAG can also be built on lexical or hybrid retrieval

An embedding layer maps discrete identities to learnable continuous vectors. What is differentiated is not the identity itself but the vector parameters that stand for it.

What static embeddings cannot do

limitation evidence from this chapter common way to address or mitigate it
One static vector per form python: neighbours from different usages representations computed from context (Ch. 7)
Unordered combination same tokens, different order → same mean sequence models (Ch. 6)
Vocabulary coverage KeyError; OOV 7.3% on the Turkish sample subword representations
Similarity and oppositeness mixed increase/decrease 0.881 evaluation with task-suited labels
Uneven directions mean cosine 0.029 (top-50,000 sample) testing centring on the task
Rare / out-of-domain words neighbours of some domain terms domain evaluation, adaptation
Social associations homemaker +0.363 several metrics; testing interventions

A static embedding is a type-level lookup table: word form → one vector. A contextual model computes the token’s representation from the surroundings it can access.

Intuition check 1 of 6

Your embedding has 300 dimensions. Why 300 and not 30 or 3,000?

  • There is no universal optimum at 300
  • With fewer dimensions the capacity of the representation can be limited; with more, memory and computation cost rise, and how well detail learned from little data generalizes is assessed separately
  • A low dimension does not force unrelated words onto the same point; a high dimension does not necessarily produce noise
  • GloVe 50 → 100 dimensions: WordSim 0.503 → 0.533, SimLex 0.263 → 0.296, analogy 0.464 → 0.633
  • On the real task, compare the dimension options for performance, memory and latency

Intuition check 2 of 6

Why negative sampling instead of a softmax over the vocabulary?

  • Scoring cost: about \(O(Vd)\) per pair for the full softmax, \(O((K+1)d)\) with \(K\) negatives. The sampler has a cost too: the binary search used here takes \(O(\log V)\) per sample
  • Not merely a faster computation: the training objective changes
  • With \(q = P(c)\) and free dot products the target is shifted PMI (Levy and Goldberg 2014)
  • Hierarchical softmax: a normalized probability through decisions along a tree path; about \(O(d \log V)\) for a balanced tree

Intuition check 3 of 6

You have 50,000 support tickets in Turkish. word2vec or fastText?

  • Measure first: the number of tokens and types in the tickets and the OOV rate on a train/test split
  • The inflectional variety of Turkish makes fastText a strong candidate; but the 7.3% OOV rate on Wikipedia is not a lower bound for support tickets — the vocabulary of a narrow, repetitive domain can be smaller, too
  • Compare the two under the same preprocessing and evaluation conditions
  • Weigh the coverage gain together with unwanted spelling-based closeness (kitap/kitle)

Intuition check 4 of 6

Cosine similarity between two documents’ averaged vectors is 0.95. Are they about the same thing?

  • That does not follow from 0.95 alone. Averaging loses order; opposite relations can be built from the same words
  • We measured it: over the chapter’s 2,248 Newsgroups documents, random pairs have mean cosine 0.944 and median 0.961; 65.6% of the pairs are above 0.95
  • Even among pairs from different newsgroups, 63.8%
  • Evaluate the decision threshold with pairs labelled as similar, unrelated and hard negatives; a percentile is not by itself a probability of semantic equivalence

Intuition check 5 of 6

Should you fine-tune pretrained embeddings on your own corpus, or train from scratch?

  • Look at two axes: the size of your domain corpus, and how well the pretrained vocabulary covers your terms
  • Small corpus, high coverage: use the pretrained vectors. Small corpus, low coverage: a subword model or a contextual encoder
  • Medium–large corpus: test continuing from pretrained; with low coverage, consider domain-adaptive training or training from scratch
  • Separate two operations: giving released vectors to a downstream model as its initialization, and continuing the original embedding training. The second may require the output parameters and the training state, not only the KeyedVectors

Intuition check 6 of 6

“Embeddings replaced TF-IDF.” True or false?

  • It depends on the task. On the single split here TF-IDF had the highest accuracy (0.853); its gap to averaged GloVe is hard to explain by chance in the paired test
  • Lexical retrieval (BM25, for example) can be useful for exact term matching, dense retrieval for relations between different wordings
  • Hybrid retrieval combines the two kinds of information; its performance has to be evaluated
  • Embedding vectors do not remove every use of TF-IDF or of one-hot encoding: selecting an embedding row can be written as a matrix product with a one-hot vector

Interview-style questions for discussion

Three of the chapter’s twelve questions: one on the objective, one on the geometry, one on system design.

  1. Explain word2vec to someone who knows regression but not neural networks.
  2. Two unrelated words have cosine 0.3. Is that high or low?
  3. You have 100,000 items and click logs. Design an item embedding.

General preparation resources: Huyen 2021 and the AIMLInterviews repository

What a strong answer names

  1. Skip-gram with negative sampling — observed pairs positive, pairs from the noise sampler negative. The score is the dot product of two vectors, the probability \(\sigma(v \cdot u)\), the derivative of one term \(\sigma(v \cdot u) - y\). The form of the loss is shared with logistic regression; both tables are learned, so the problem is not convex. Then the \(\mathrm{PMI} - \log K\) connection, with its conditions
  2. A reference distribution — in the sample from the first 50,000 GloVe words the mean is 0.029 and the standard deviation 0.119; 0.3 is about 2.3 standard deviations up. High relative to the sample; no normal distribution, p-value or guaranteed semantic relation is implied. Look at the percentiles of your own data and at labelled pairs
  3. Skip-gram on sessions — session = sequence of items. Airbnb: the booked listing as an additional positive context; within-market negatives added to the general ones (Grbovic & Cheng 2018). Session boundaries, the definition of a negative and the time split have to be explicit. Cold start: content features such as title and category

Exercises

  1. Compare the small example for windows 1 and 4. Which neighbourhoods change? Report it if the expected tendency does not show
  2. Limits of analogies: three that give the expected answer, three that do not; normalization and filter fixed; compare with the nearest-neighbour baseline
  3. Audit your own domain: twenty terms; criterion fixed in advance; Spearman between grades and frequency rank
  4. Vocabulary coverage: OOV learning curves in Turkish and English with fixed test sets
  1. The limit of averaging: two sentences with the same tokens in a different order; which relation is lost?
  2. TF-IDF and dense representations: choose settings on validation data, test only at the end; discuss it if there is no gain
  3. Implement CBOW yourself: extend the NumPy example; same data and budget, compared by frequency group
  4. Explore an association direction: fix pairs and terms in advance; compare the structure after removing the direction

Where to go deeper

resource why
Mikolov et al. 2013a, 2013b skip-gram and CBOW; then negative sampling and subsampling — read the second alongside the chapter’s code
Rong 2014 · Goldberg & Levy 2014 the gradients derived step by step; the reasoning behind the negative-sampling objective
Levy & Goldberg 2014 · Levy et al. 2015 the SGNS–PMI relation and the effect of hyperparameters
Bolukbasi et al. 2016, then Gonen & Goldberg 2019 read together: the proposed operations, then an examination of what remains
Jurafsky & Martin, Chapter 5 word representations in the August 19, 2026 draft; Appendix J for PPMI; free
Stanford CS224N notes of the word-vectors lecture; the assignments change from year to year
Elena Voita, NLP Course For You skip-gram and negative sampling, with visuals
fastText pretrained vectors released vectors for 157 languages including Turkish