Contents Meaning as Geometry Code Course home

Chapter 9Learned Word Embeddings

After this chapter you will be able to

  • count the training examples skip-gram and CBOW draw from a sentence, and say which suits rare words;

  • derive the softmax gradient as prediction minus target, and say why the full softmax is too costly;

  • carry out one negative sampling update by hand, moving both the context vectors and the centre vector;

  • say what GloVe and FastText change, and why skip-gram with negative sampling factorises a shifted PMI matrix;

  • run an analogy and a bias test on an embedding space, and state what each does and does not show.

This chapter builds on Chapters 6 and 7, which counted what this chapter learns, and Chapter 8, which supplies the learning machine.

From counting to learning

Part II opened with the distributional hypothesis, in Firth’s slogan that “you shall know a word by the company it keeps”, and we turned it into geometry by counting co-occurrences and reducing the matrix with an SVD. Those count-based vectors work, and they also carry the whole matrix’s baggage, being large, being sparse, and having to be rebuilt from scratch whenever the corpus changes.

Around 2013 a different idea took over, and every modern system inherits it. Do not count contexts and then compress, but learn a small dense vector for each word directly by training a model to predict context.

The distributional hypothesis is unchanged and only the machinery is new. That machinery is faster and smaller, and it produces geometry with structure that no one specified.

word2vec

The canonical method is word2vec, from Mikolov and colleagues in 2013, which trains vectors through a deliberately trivial prediction task. There are two formulations and they are mirror images of each other.

Table 9.1. The three word2vec formulations side by side, following Rong (2014). Only the first row differs in substance: CBOW averages the context vectors into hh while skip-gram takes the centre word alone, and everything below follows from that one choice. Skip-gram’s extra sums are its CC separate predictions being accumulated, so it costs more per centre word.
one word CBOW skip-gram
h=vwIh = v_{w_I} h=1C∑c=1CvwI,ch = \dfrac{1}{C}\displaystyle\sum_{c=1}^{C} v_{w_{I,c}} h=vwIh = v_{w_I}
uj=vwj′⊤hu_j = {v'_{w_j}}^{\!\top} h uj=vwj′⊤hu_j = {v'_{w_j}}^{\!\top} h uc,j=vwj′⊤hu_{c,j} = {v'_{w_j}}^{\!\top} h, c=1…Cc = 1 \dots C
vwj′←vwj′−ηejhv'_{w_j} \leftarrow v'_{w_j} - \eta\, e_j\, h vwj′←vwj′−ηejhv'_{w_j} \leftarrow v'_{w_j} - \eta\, e_j\, h vwj′←vwj′−ηEIjhv'_{w_j} \leftarrow v'_{w_j} - \eta\, \mathrm{EI}_j\, h,
where EIj=∑c=1Cec,j\mathrm{EI}_j = \sum_{c=1}^{C} e_{c,j}
vwI←vwI−ηEH⊤v_{w_I} \leftarrow v_{w_I} - \eta\, \mathrm{EH}^{\!\top} vwI,c←vwI,c−ηCEH⊤v_{w_{I,c}} \leftarrow v_{w_{I,c}} - \dfrac{\eta}{C}\, \mathrm{EH}^{\!\top} vwI←vwI−ηEH⊤v_{w_I} \leftarrow v_{w_I} - \eta\, \mathrm{EH}^{\!\top},
where EHi=∑j=1|V|EIjwij′\mathrm{EH}_i = \sum_{j=1}^{|V|} \mathrm{EI}_j\, w'_{ij}
E=−uj*E = -u_{j^*}
+log⁡∑j′exp⁡(uj′)\quad + \log \sum_{j'} \exp(u_{j'})
E=−uj*E = -u_{j^*}
+log⁡∑j′exp⁡(uj′)\quad + \log \sum_{j'} \exp(u_{j'})
E=−∑c=1Cujc*E = -\sum_{c=1}^{C} u_{j^*_c}
+Clog⁡∑j′exp⁡(uj′)\quad + C \log \sum_{j'} \exp(u_{j'})

Skip-gram

Slide a window across the corpus, take the word at the centre, then try to predict each of the words around it one at a time. This is the entire supervised signal, with a centre word in and one context word out, and no labels are needed because the corpus labels itself. Formally, for a corpus w1,…,wTw_1, \ldots, w_T and a window of CC words on each side, skip-gram maximises

1T∑t=1T∑−C≤c≤Cc≠0log⁡P(wt+c∣wt).(9.1)\begin{equation} \frac{1}{T}\sum_{t=1}^{T} \sum_{\substack{-C \le c \le C \\ c \neq 0}} \log P(w_{t+c} \mid w_t). \label{eq:skipgram-objective} \quad\text{(9.1)} \end{equation}

Figure 9.1. Skip-gram. One centre word enters, and the same network is asked to produce each surrounding word in turn. The input layer is one hot, so the hidden layer is a row lookup from WW.

CBOW

CBOW, for continuous bag of words, reverses every arrow by taking the surrounding words and predicting the one in the middle. The context words are combined before they reach the hidden layer, and the combination is a simple average:

h=12C∑−C≤c≤Cc≠0vwt+c.(9.2)\begin{equation} h \;=\; \frac{1}{2C}\sum_{\substack{-C \le c \le C \\ c \neq 0}} v_{w_{t+c}} . \label{eq:cbow-hidden} \quad\text{(9.2)} \end{equation}

That average is where the name comes from, because the context is a bag and order inside the window is discarded. So the cat sat and sat cat the give the same hidden vector.

Figure 9.2. CBOW. Several context words enter, their vectors are averaged into one hidden vector, and the network predicts the word that was removed from the middle.

The same sentence, both ways

Take “the quick brown fox jumps” with a window of two words on each side. Both formulations see the same windows and make different training data from them.

centre context words skip-gram pairs CBOW example
the quick, brown (the, quick), (the, brown) (quick ++ brown) →\to the
quick the, brown, fox (quick, the), (quick, brown), … (the ++ brown ++ fox) →\to quick
brown the, quick, fox, jumps (brown, the), (brown, quick), … (the ++ quick ++ fox ++ jumps) →\to brown
fox quick, brown, jumps (fox, quick), (fox, brown), … (quick ++ brown ++ jumps) →\to fox
jumps brown, fox (jumps, brown), (jumps, fox) (brown ++ fox) →\to jumps

The counts differ, and that difference explains everything else about the two. Skip-gram produces 14 training pairs from this one sentence, one per centre and context combination, while CBOW produces 5, one per centre word.

Which to use

CBOW Skip-gram
direction context →\to centre centre →\to context
examples per centre 1 up to 2C2C
speed faster slower
rare words weaker stronger
context handling averaged into one each predicted separately

The averaging in Equation (9.2) is what costs CBOW its accuracy on rare words. A rare word in a context of four is one quarter of one hidden vector, and the three common words beside it smooth its contribution away. Skip-gram gives that rare word its own training pair with every neighbour, so it gets 2C2C chances to shape its own vector, and it pays for this in time, since more pairs means more updates. The rule of thumb is CBOW for large corpora where speed matters, and skip-gram when the tail matters.

What the model actually holds

The model holds nothing but vectors, one per word or, strictly, two per word. Every word ww has an input vector vwv_w, a row of WW, used when ww is the centre or context being fed in. It also has an output vector vw′v'_w, a column of W′W', used when ww is the word being predicted. Training nudges those vectors so that words appearing in similar contexts end up with similar vectors, and when training finishes the output vectors are usually thrown away, leaving the input matrix WW as what people mean by “the embeddings”.

The network, written out

word2vec is a neural network with one hidden layer and no nonlinearity in it, and writing it out properly takes four steps. Let the vocabulary be size VV and the embedding size NN, with two weight matrices, where WW is V×NV \times N and holds the input vectors while W′W' is N×VN \times V and holds the output, or context, vectors.

Step 1: the hidden layer is a lookup.

The input xx is one hot for the centre word wIw_I. So

h=W⊤x=vwI,(9.3)\begin{equation} h \;=\; W^{\!\top} x \;=\; v_{w_I}, \label{eq:w2v-hidden} \quad\text{(9.3)} \end{equation}

which is just row wIw_I of WW. No arithmetic happens here, because multiplying a one-hot vector by a matrix selects a row, and that row is the word’s embedding.

Step 2: score every word.

For each candidate output word wjw_j, take the dot product of the hidden vector with that word’s context vector:

uj=vwj′⊤h.(9.4)\begin{equation} u_j \;=\; {v'_{w_j}}^{\!\top} h . \label{eq:w2v-score} \quad\text{(9.4)} \end{equation}

Step 3: softmax.

Turn the VV scores into a distribution:

yj=exp⁡(uj)∑j′=1Vexp⁡(uj′)=exp⁡(vwj′⊤vwI)∑j′=1Vexp⁡(vwj′′⊤vwI).(9.5)\begin{equation} y_j \;=\; \frac{\exp(u_j)}{\sum_{j'=1}^{V} \exp(u_{j'})} \;=\; \frac{\exp\!\big({v'_{w_j}}^{\!\top} v_{w_I}\big)} {\sum_{j'=1}^{V} \exp\!\big({v'_{w_{j'}}}^{\!\top} v_{w_I}\big)} . \label{eq:w2v-softmax} \quad\text{(9.5)} \end{equation}

Step 4: the loss.

We want to maximise the probability of the true context word wj*w_{j^*}, so we minimise its negative log probability, which is cross entropy against a one-hot target:

E=−log⁡yj*=−uj*+log⁡∑j=1Vexp⁡(uj).(9.6)\begin{equation} E \;=\; -\log y_{j^*} \;=\; -u_{j^*} + \log \sum_{j=1}^{V} \exp(u_j). \label{eq:w2v-loss} \quad\text{(9.6)} \end{equation}

The two terms pull in opposite directions, pushing up the score of the right word while pushing down the total of all scores. Together they make the loss a contest between one word and all the rest.

The gradients

Everything now follows from the chain rule, and the first derivative is the one you already know from Chapter 8. Let tjt_j be the target, 11 for the true context word and 00 otherwise, and differentiating Equation (9.6) gives the prediction minus target rule again:

∂E∂uj=yj−tj=ej.(9.7)\begin{equation} \frac{\partial E}{\partial u_j} \;=\; y_j - t_j \;=\; e_j . \label{eq:w2v-error} \quad\text{(9.7)} \end{equation}

That eje_j is the error at output unit jj, and every remaining gradient is eje_j multiplied by whatever it was attached to.

gradient chain rule result
output weights ∂E∂uj⋅∂uj∂wij′\dfrac{\partial E}{\partial u_j} \cdot \dfrac{\partial u_j}{\partial w'_{ij}} ejhie_j \, h_i
hidden layer ∑j=1V∂E∂uj⋅∂uj∂hi\displaystyle\sum_{j=1}^{V} \dfrac{\partial E}{\partial u_j} \cdot \dfrac{\partial u_j}{\partial h_i} ∑j=1Vejwij′=EHi\displaystyle\sum_{j=1}^{V} e_j \, w'_{ij} \;=\; \mathrm{EH}_i
input weights ∂E∂hi⋅∂hi∂wki\dfrac{\partial E}{\partial h_i} \cdot \dfrac{\partial h_i}{\partial w_{ki}} EHixk\mathrm{EH}_i \, x_k

Two consequences follow. The output gradient ejhie_j h_i touches every word in the vocabulary, because eje_j is nonzero for all jj, and that is the cost we are about to attack. The input gradient is multiplied by the input xx, which is one hot, so only one row of WW moves per training example and the centre word’s embedding is updated while no other is.

The obstacle

Count the work. Equation (9.5) has a denominator summing over the whole vocabulary, and Equation (9.7) produces an error for every one of those words, so with VV in the hundreds of thousands and billions of training examples this is ruinous. Both fixes below attack the same denominator.

Hierarchical softmax

The first fix changes the shape of the output layer. It replaces the VV independent output units by a binary tree whose leaves are the words, so that reaching any word takes log⁡2V\log_2 V binary decisions, about twenty for a million words, and not VV comparisons. Each internal node carries its own vector, the probability of a word is a product of sigmoids along the path to it, and the probabilities of all the leaves sum to one without a normalising sum ever being computed. Only the nodes on the path are updated, and in practice the tree is a Huffman tree built from word frequencies, so that frequent words sit on short paths. The full construction, with a worked path through a tree of eight words, the loss and its gradients, is in Appendix C. Negative sampling, the second fix, is what most systems use, and the rest of the chapter needs only the idea that the cost can be cut from VV to log⁡2V\log_2 V.

Negative sampling

The output layer is the problem, because predicting a context word means a softmax over the entire vocabulary, and with a vocabulary in the hundreds of thousands computing that denominator for every training example is ruinous. word2vec’s decisive trick is negative sampling, which does not ask which of all VV words is the context but instead asks a handful of much easier yes or no questions. Is this the observed context word? Yes. Is this randomly drawn word? No, it is a negative.

Train the vectors to say yes to true pairs and no to a few random ones, and a VV-way softmax becomes a handful of binary decisions per example. This is what made word2vec fast enough to train on billions of words on one machine.

Where the 0.75 comes from

Chapter 7 promised this exponent would return, so here it is. The negatives come from the counts of single words (the unigram counts) raised to the power 0.750.75, rather than uniformly or from the raw unigram distribution:

q(w)=count⁡(w)0.75∑w′count⁡(w′)0.75.(9.8)\begin{equation} q(w) \;=\; \frac{\operatorname{count}(w)^{0.75}} {\sum_{w'} \operatorname{count}(w')^{0.75}}. \label{eq:negsampling-dist} \quad\text{(9.8)} \end{equation}

Why bend the distribution at all? Draw negatives from the raw counts and nearly every negative is the, which teaches the model almost nothing, while drawing them uniformly makes rare words appear as negatives far more often than they ever appear as observed words. The 0.750.75 power sits between the two, and here is what it does to a five word vocabulary.

word count p(w)p(w) count⁡0.75\operatorname{count}^{0.75} q(w)q(w) q/pq/p
the 1000 0.5910 177.8 0.5301 ×0.90\times 0.90
of 600 0.3546 121.2 0.3614 ×1.02\times 1.02
dog 50 0.0296 18.8 0.0561 ×1.90\times 1.90
cat 40 0.0236 15.9 0.0474 ×2.01\times 2.01
aardvark 2 0.0012 1.7 0.0050 ×4.24\times 4.24

In the last column the most frequent word is sampled slightly less than its share and the rarest more than four times its share. Raising counts to a power below one compresses the range, which lifts the tail and trims the head. The same exponent did the same job for PMI in Chapter 7, where it smoothed the context distribution to stop rare words earning inflated scores. Two methods share one correction by design, since word2vec can be shown to be implicitly factorising a shifted PMI matrix.

One training step, by hand

The update is the prediction minus target rule from Chapter 8 applied to a dot product, and nothing new is needed. Take a centre word cat with vector v=(0.5,−0.2)v = (0.5, -0.2), the true context word sat with vector u+=(0.4,0.1)u^{+} = (0.4, 0.1), and one sampled negative the with u−=(−0.3,0.6)u^{-} = (-0.3, 0.6), at a learning rate of η=0.1\eta = 0.1. For each pair the model scores z=v⋅uz = v \cdot u, squashes it with a sigmoid, then compares with the label, which is 11 for the true context and 00 for a negative.

pair z=v⋅uz = v \cdot u σ(z)\sigma(z) label gradient σ(z)−y\sigma(z) - y
cat, sat (positive) +0.180+0.180 0.54490.5449 1 −0.4551-0.4551
cat, the (negative) −0.270-0.270 0.43290.4329 0 +0.4329+0.4329

The signs carry the lesson. The positive pair gets a negative gradient, which pulls the two vectors together, while the negative pair gets a positive one, which pushes them apart. Both sides of every pair move, so there are two update rules and not one. Each context vector is pulled towards or away from the centre word,

u←u−η(σ(z)−y)v,(9.9)\begin{equation} u \;\leftarrow\; u - \eta\,(\sigma(z) - y)\,v , \label{eq:negsampling-update-u} \quad\text{(9.9)} \end{equation}

and the centre word is moved once, by the sum of the pulls from every pair it took part in,

v←v−η∑pairs(σ(z)−y)u.(9.10)\begin{equation} v \;\leftarrow\; v - \eta \sum_{\text{pairs}} (\sigma(z) - y)\,u . \label{eq:negsampling-update-v} \quad\text{(9.10)} \end{equation}

Forgetting the second rule is the usual slip, and it changes the answer below. Check both rules before trusting an implementation.

vector arithmetic new value
u+u^{+} (0.4,0.1)−0.1(−0.4551)(0.5,−0.2)(0.4, 0.1) - 0.1(-0.4551)(0.5, -0.2) (0.4228,0.0909)(0.4228, 0.0909)
u−u^{-} (−0.3,0.6)−0.1(+0.4329)(0.5,−0.2)(-0.3, 0.6) - 0.1(+0.4329)(0.5, -0.2) (−0.3216,0.6087)(-0.3216, 0.6087)
vv (0.5,−0.2)−0.1[(−0.4551)(0.4,0.1)+(0.4329)(−0.3,0.6)](0.5, -0.2) - 0.1\big[(-0.4551)(0.4, 0.1) + (0.4329)(-0.3, 0.6)\big] (0.5312,−0.2214)(0.5312, -0.2214)

The centre word’s own gradient is (−0.3119,+0.2142)(-0.3119, +0.2142), the sum of the positive context pulling it one way and the negative pushing it the other. Did it work? Recompute both scores with all three updated vectors.

before after
σ(v⋅u+)\sigma(v \cdot u^{+}), want it up 0.54490.5449 0.5509\mathbf{0.5509}
σ(v⋅u−)\sigma(v \cdot u^{-}), want it down 0.43290.4329 0.4242\mathbf{0.4242}

True pairs were pulled together and random pairs pushed apart. Repeat that a few billion times and the geometry of Part II falls out.

Figure 9.3. Which weights move on one negative sampling step. Only the centre word’s vector and the handful of sampled context vectors are touched. The rest of the vocabulary is untouched, so the method is fast.

Run it. code/worked_examples/word2vec.py prints both tables above. --exponent lets you change the 0.750.75 and watch the sampling distribution flatten or sharpen.

Run it

The negative sampling objective

Written out, the loss for one centre word with kk negatives is

E=−[log⁡σ(zpos)+∑i=1klog⁡(1−σ(znegi))],(9.11)\begin{equation} E \;=\; -\Big[\, \log \sigma(z_{\text{pos}}) \;+\; \sum_{i=1}^{k} \log\big(1 - \sigma(z_{\text{neg}_i})\big) \,\Big], \label{eq:negsampling-loss} \quad\text{(9.11)} \end{equation}

where z=vw′⊤hz = {v'_w}^{\!\top} h is the score of a candidate word. Apply Equation (see the appendix) and the second term becomes ∑ilog⁡σ(−znegi)\sum_i \log \sigma(-z_{\text{neg}_i}), the form usually printed. Both say the same thing: make the true pair score high and the sampled pairs score low. Compare this with the full softmax loss of Equation (9.6), where the sum over VV has become a sum over kk, and kk is typically 5 to 20.

What each fix costs

Put the three side by side. Let TT be the corpus size, NN the embedding dimension, and CC the window size.

method cost
Full softmax O(T⋅N⋅C⋅V)O(T \cdot N \cdot C \cdot V)
Hierarchical softmax O(T⋅N⋅C⋅log⁡V)O(T \cdot N \cdot C \cdot \log V)
Negative sampling O(T⋅N⋅C⋅k)O(T \cdot N \cdot C \cdot k)

For V=106V = 10^6 the full softmax costs a million operations per prediction, hierarchical softmax costs about twenty, and negative sampling costs kk, which does not grow with the vocabulary at all. Both fixes are approximations and they approximate different things. Hierarchical softmax still computes a genuine probability distribution, merely factored over a tree, whereas negative sampling abandons the distribution entirely and solves a set of binary classification problems instead. In practice negative sampling won, because it is simpler and trains faster on frequent words.

Negative sampling is also a pattern this book meets again, in the form of pulling true pairs together and pushing random pairs apart. The contrastive training behind dense retrieval in Chapter 22 is the same idea one level up, with positive and negative pairs shaping a representation.

Vectors for cat, sat and the rotating after one negative-sampling update
One word2vec update pulls the vectors of a real neighbour pair closer and pushes a sampled non-neighbour apart. Training is this single step repeated over a corpus.
Random 2-D word and context vectors moving into two clusters as training reduces the loss
Meaning emerges from many small updates. Words that share contexts are pulled together step by step, so animal words and vehicle words separate into groups.
Sampling probabilities for five words at exponents 1, 0.75 and 0.5
Sampling negatives by raw frequency would mostly draw the commonest words. Raising counts to the power 0.75 flattens the draw so rare words appear as negatives more often.

The analogy surprise

Something unplanned fell out of these vectors. Take the vector for king, subtract man, add woman, and the nearest vector to the result is queen.

The relationship from male to female is, approximately, a direction in the space, and the same displacement carries uncle to aunt and he to she, while plural formation is another direction and capital of country is another. Nobody designed this. It emerged because consistent semantic relationships produce consistent contextual differences, and training recorded them as consistent geometric ones, which makes analogy solving arithmetic:

analogy(a,b,c)=nearest⁡(vb−va+vc),(9.12)\begin{equation} \text{analogy}(a, b, c) \;=\; \operatorname*{nearest}\big(v_b - v_a + v_c\big), \label{eq:analogy} \quad\text{(9.12)} \end{equation}

excluding aa, bb and cc themselves from the answer.

The analogy worked out

Take a toy space with three interpretable dimensions, namely how royal a word is, how male and how female. The numbers are invented to make the geometry visible.

word royal male female
king 1.00 0.90 0.10
man 0.10 0.90 0.10
woman 0.10 0.10 0.90
queen 0.95 0.15 0.85
prince 0.90 0.85 0.15
throne 0.80 0.45 0.45
child 0.20 0.50 0.50

Compute the target, where subtracting man from king strips the male component while keeping the royal one, and adding woman puts a female component back:

v𝑘𝑖𝑛𝑔−v𝑚𝑎𝑛+v𝑤𝑜𝑚𝑎𝑛=(1.00,0.10,0.90).v_{\mathit{king}} - v_{\mathit{man}} + v_{\mathit{woman}} = (1.00, 0.10, 0.90).

Rank every word by cosine to that target. The search excludes the three query words themselves.

word cosine
queen 0.9991\mathbf{0.9991} the answer
throne 0.90640.9064 royal, but not gendered
woman 0.74850.7485 query word, must be excluded
child 0.70610.7061
prince 0.66580.6658 royal, but male
king 0.64840.6484 query word, must be excluded
man 0.22780.2278

Queen wins at 0.99910.9991 and the runners up are interpretable, since throne is royal but carries no gender while prince is royal but male. Both are near, and both are wrong for the right reasons.

Note where woman lands, which is third, ahead of four other words. On trained spaces a query word very often comes first, because vb−va+vcv_b - v_a + v_c stays close to vcv_c, so forgetting the exclusion will make your analogy scores look far better than they are. It is a common way to overstate an embedding.

Subtracting a direction: what apple is made of

The analogy above used a famous example on a space built to make it work, so here is a more modest use of the same arithmetic. It doubles as a diagnosis of the corpus. Take a space trained on technology news and ask for the nearest neighbours of apple.

neighbour cosine
mac 0.94030.9403
samsung 0.93880.9388
iphone 0.93830.9383
android 0.93100.9310
orange 0.59150.5915 the first fruit, far behind
juice 0.47710.4771

The top four are technology and the first fruit trails at 0.590.59, and it is orange, which is a phone network as well as a fruit. This tells us something about the corpus, not about English, because apple is overwhelmingly a company here. The fruit sense exists in the vector and is buried under the company sense, since the training text talked about one far more than the other.

Subtract the strongest technology association and see what is left:

d→=𝑎𝑝𝑝𝑙𝑒→−𝑖𝑝ℎ𝑜𝑛𝑒→.(9.13)\begin{equation} \vec{d} \;=\; \vec{\mathit{apple}} - \vec{\mathit{iphone}} . \label{eq:apple-minus-iphone} \quad\text{(9.13)} \end{equation}

Rank every word by cosine to d→\vec{d}.

neighbour of d→\vec{d} cosine
fruit +0.9578+0.9578
banana +0.9556+0.9556
juice +0.9305+0.9305
orange +0.8704+0.8704
mac −0.2201-0.2201 now pointing the other way
samsung −0.2259-0.2259

The list has inverted completely, with fruits filling the top while the technology words have gone negative, meaning they now point away from what is left. Nothing was told to the model about fruit or about companies, and subtracting one word removed a whole semantic dimension so that the sense which had been buried came to the surface.

The reason it works is that a vector is a mixture of the senses and associations the corpus gave the word. Apple carries a large technology component and a smaller fruit one, while iphone carries the technology component and no fruit at all, so subtracting cancels what they share and keeps what only the first has. The technology part very nearly annihilates, the fruit part survives untouched, and the residue is the minority sense.

This is a practical diagnostic and worth more than analogy scores. It reveals the dominant sense of a polysemous word, which is a fact about your training data. If apple comes out as a company your corpus is technology news, and if it comes out as a fruit your corpus is recipes or agriculture. The same probe on bank, java, python or amazon will tell you what your text was about before you read a line of it.

It also shows the limit of a single vector per word, because both senses are jammed into one point and pulling them apart takes arithmetic plus a guess about what to subtract. Chapter 16 solves this properly by letting the sentence decide which sense is present.

Run it. code/worked_examples/word2vec.py --apple prints both tables. --subtract takes any word, so you can strip a different association and see what surfaces.

Run it

Vector arithmetic king minus man plus woman and the cosine ranking of the words
Relations between words can be read as directions in a vector space. Subtracting and adding word vectors lands near the word that completes the analogy, once the query words are excluded.

Bias: the space records the corpus, all of it

The geometry records whatever the corpus contains, including its social regularities. The apple probe above was a mild instance, and what follows is the same fact with higher stakes.

Suppose a body of text systematically places occupation words near one gender’s pronouns, in which case the space will place them near that gender’s vector. No single sentence is biased, and the aggregate association is measurable.

Measuring it needs only cosine, and the tool is the Word Embedding Association Test (Caliskan et al. 2017). In the simplified form this book uses, it scores the differential association of target words TT with two attribute sets AA and BB:

s(T,A,B)=1|T|∑t∈T[meana∈Acos⁡(t,a)−meanb∈Bcos⁡(t,b)].(9.14)\begin{equation} s(T, A, B) \;=\; \frac{1}{|T|}\sum_{t \in T} \Big[\operatorname*{mean}_{a \in A}\cos(t, a) - \operatorname*{mean}_{b \in B}\cos(t, b)\Big]. \label{eq:weat} \quad\text{(9.14)} \end{equation}

A positive ss means the targets sit closer on average to set AA, a negative ss means closer to BB, and the magnitude is the strength. Point it at institutional against narrative vocabulary and it separates registers, while pointing it at gendered attributes exposes occupational stereotypes in web-scale spaces.

The number is only as good as its inputs, so three cautions are in order. It measures the corpus through the model, so change either and ss changes. The word lists are a design choice, so report them with the score or the score means nothing. And a near zero result means these lists do not separate, which is not the same as the space being unbiased. Any system built on these vectors inherits their associations silently, whether search, screening or classification, so measuring them is part of knowing what you have built.

GloVe

word2vec learns from local windows one at a time and never sees the corpus as a whole, so GloVe (Pennington et al. 2014) asks whether that is wasteful, given that the global co-occurrence counts are sitting right there.

Meaning lives in ratios

GloVe’s founding observation concerns ratios of counts, not counts themselves. Let XijX_{ij} be the number of times word jj occurs in the context of word ii, so that the conditional probability is

Pij=P(j∣i)=Xij∑kXik.(9.15)\begin{equation} P_{ij} \;=\; P(j \mid i) \;=\; \frac{X_{ij}}{\sum_k X_{ik}} . \label{eq:glove-prob} \quad\text{(9.15)} \end{equation}

Take a single probability such as P(𝑠𝑜𝑙𝑖𝑑∣𝑖𝑐𝑒)P(\mathit{solid} \mid \mathit{ice}) and it is hard to interpret, because there is nothing to compare 0.000190.00019 against. Now take two words and probe them with a third, comparing P(k∣𝑖𝑐𝑒)P(k \mid \mathit{ice}) against P(k∣𝑠𝑡𝑒𝑎𝑚)P(k \mid \mathit{steam}) for various probe words kk, and the ratio is immediately readable.

probe kk solid gas water fashion
related to ice? yes no both neither
related to steam? no yes both neither
P(k∣𝑖𝑐𝑒)/P(k∣𝑠𝑡𝑒𝑎𝑚)P(k \mid \mathit{ice}) \,/\, P(k \mid \mathit{steam}) large small ≈1\approx 1 ≈1\approx 1

The ratio is large when the probe belongs to the first word, small when it belongs to the second, and near one when it belongs to both or to neither. That is the discrimination raw probabilities could not give. Water and fashion both score near one for opposite reasons, and the ratio quite properly refuses to distinguish them, since neither tells ice from steam.

Figure 9.4. Co-occurrence probabilities and their ratio, from the GloVe paper. The individual probabilities are small and hard to read. The ratio in the last row separates the probes cleanly.

Turning a ratio into an objective

If ratios carry the meaning, the model should predict them. GloVe arranges for the dot product of two word vectors to approximate the log of the co-occurrence count, because differences of logs are ratios.

That gives a weighted least squares problem:

J=∑i,j=1Vf(Xij)(wi⊤w̃j+bi+b̃j−log⁡Xij)2.(9.16)\begin{equation} J \;=\; \sum_{i,j=1}^{V} f(X_{ij}) \Big( w_i^{\!\top} \tilde{w}_j + b_i + \tilde{b}_j - \log X_{ij} \Big)^{2} . \label{eq:glove} \quad\text{(9.16)} \end{equation}

Each piece has a job. Here wiw_i is the vector for the word and w̃j\tilde{w}_j the vector for the context, so every word again gets two as word2vec has input and output vectors, and the final embedding is usually w+w̃w + \tilde{w} since both carry signal.

The biases bib_i and b̃j\tilde{b}_j absorb how common each word is on its own, because without them the model would have to encode raw frequency in the vectors, which is the pollution PMI existed to remove in Chapter 7. The target is log⁡Xij\log X_{ij}, not XijX_{ij}, because a log turns the multiplicative structure of counts into an additive one, so a difference of dot products lands on a ratio of probabilities. This is the whole design.

The weighting function

The last piece is ff, and without it the objective would be dominated by whichever pairs happened to be most frequent.

f(x)={(x/xmax)α,x<xmax1,otherwise,α=0.75,xmax=100.(9.17)\begin{equation} f(x) \;=\; \begin{cases} (x / x_{\max})^{\alpha}, & x < x_{\max} \\ 1, & \text{otherwise,} \end{cases} \qquad \alpha = 0.75, \quad x_{\max} = 100 . \label{eq:glove-weight} \quad\text{(9.17)} \end{equation}

It does three jobs at once. At x=0x = 0 it gives f(0)=0f(0) = 0, so pairs that never co-occur contribute nothing, which matters because log⁡0\log 0 is undefined and most of the matrix is zeros. Between 00 and xmaxx_{\max} it rises, so rarer pairs count less than common ones, which suppresses noise from pairs seen once or twice. Above xmaxx_{\max} it is flat at 11, so a pair seen ten thousand times gets no more weight than one seen a hundred times and the cannot dominate the fit.

That exponent is 0.750.75 for the third time in this book, after PMI smoothing and negative sampling. Three different models, three different mechanisms, and the same correction, which is to compress the range so the head does not swamp the tail.

Where GloVe stands

At release in 2014 it beat the alternatives on three tasks, namely word analogy, word similarity and named entity recognition, and it captured syntactic and semantic relationships equally well. It shares word2vec’s main limitation, though, since GloVe produces static embeddings of one vector per word, and contextual models have since displaced it for most tasks.

FastText

Both models so far treat a word as an atom, so a word is either in the vocabulary with a vector of its own or unknown and has nothing. Chapter 3 showed why that fails, because Heaps’ law guarantees the vocabulary never closes and unknown words keep arriving forever. FastText (Bojanowski et al. 2017) answers the same pressure that subword tokenisation answered in Chapter 5, but at the embedding, not at the tokeniser.

A word is a bag of character n-grams

Break each word into overlapping character n-grams, marking the boundaries with < and > so that a prefix can be told from the same letters appearing mid-word. For apple with n=3n = 3:

<ap app ppl ple le>

FastText normally uses several values of nn together, so here is technical at n=3n = 3 and at n=4n = 4.

3-grams <te, tec, ech, chn, hni, nic, ica, cal, al>
4-grams <tec, tech, echn, chni, hnic, nica, ical, cal>

Every n-gram gets its own learned vector 𝐳g\mathbf{z}_g, and the word’s vector is their sum, with the whole word included in the set as well:

𝐰=∑g∈G(w)𝐳g.(9.18)\begin{equation} \mathbf{w} \;=\; \sum_{g \in G(w)} \mathbf{z}_g . \label{eq:fasttext} \quad\text{(9.18)} \end{equation}

Written out for our example,

𝐰𝑡𝑒𝑐ℎ𝑛𝑖𝑐𝑎𝑙=𝐳<𝚝𝚎+𝐳𝚝𝚎𝚌+𝐳𝚎𝚌𝚑+⋯+𝐳𝚌𝚊𝚕+𝐳𝚊𝚕>+𝐳𝑡𝑒𝑐ℎ𝑛𝑖𝑐𝑎𝑙.(9.19)\begin{equation} \mathbf{w}_{\mathit{technical}} \;=\; \mathbf{z}_{\texttt{<te}} + \mathbf{z}_{\texttt{tec}} + \mathbf{z}_{\texttt{ech}} + \cdots + \mathbf{z}_{\texttt{cal}} + \mathbf{z}_{\texttt{al>}} + \mathbf{z}_{\mathit{technical}} . \label{eq:fasttext-worked} \quad\text{(9.19)} \end{equation}

Everything else is skip-gram with negative sampling, unchanged, and only the definition of a word vector has moved.

What that buys

The first gain is that unknown words get usable vectors. Meet technicality for the first time and FastText still produces something sensible, because its n-grams tec, ech, chn and nic were all trained on technical and its relatives, so the sum lands near them. word2vec and GloVe can only return an unknown token here, whereas FastText returns a vector in roughly the right neighbourhood.

The second is that morphology comes free, since walk, walks, walked and walking share most of their n-grams and their vectors are therefore close by construction, not by luck. This matters far more in some languages than in English. A morphologically rich language such as Tamil, Finnish or Turkish generates enormous numbers of inflected forms, most of them individually rare. Treating each as an unrelated atom wastes almost all the evidence, while sharing subword vectors pools it.

The cost is twofold. The n-gram table is larger than a word table and a word vector must be assembled at query time, not looked up. FastText also cannot separate unrelated words that happen to share spelling, since nothing tells it that ear in earth has no connection to ear in hearing.

The idea outlives the model

FastText itself is little used now, while its central move is everywhere. Every modern tokeniser builds its vocabulary from frequent character sequences instead of whole words, whether BPE in Chapter 5, WordPiece or SentencePiece. All of them answer the open vocabulary problem the same way, by composing rare things from common pieces. FastText made that argument at the embedding layer first.

Counting and learning are the same thing

Part II has now built dense word vectors three separate times. Chapter 7 factored a PPMI matrix with an SVD, and this chapter trained word2vec by gradient descent and then fitted GloVe to global counts.

Three methods, three chapters and three sets of vectors that behave alike, which is not a coincidence, and the reason is worth stating plainly. All three are matrix factorisations of the same co-occurrence statistics, differing in which matrix, which loss and which optimiser, but not differing in kind.

One shape, three fillings

Every method here produces two matrices. They are a word matrix WW of size V×dV \times d and a context matrix CC of the same size, where row ii of WW is the vector wiw_i and row jj of CC is the context vector cjc_j. Every method then asks the dot product of a word and a context to reproduce some association score:

wi⊤cj≈Mij.(9.20)\begin{equation} w_i^{\!\top} c_j \;\approx\; M_{ij}. \label{eq:factorisation} \quad\text{(9.20)} \end{equation}

This is the whole family, so choosing a method means choosing three things: the matrix MM, the weight each cell carries, and how you solve for WW and CC.

SVD of PPMI word2vec (SGNS) GloVe
target MijM_{ij} max⁡(PMI,0)\max(\text{PMI}, 0) PMI−log⁡k\text{PMI} - \log k log⁡Xij−bi−b̃j\log X_{ij} - b_i - \tilde{b}_j
cell weight all cells equal the counts f(Xij)f(X_{ij})
zero cells fitted as 00 pushed down dropped
solved by closed form stochastic gradient gradient on counts
needs the whole matrix a stream of windows the whole matrix

The middle column is the surprising one, because nothing in word2vec’s training loop mentions PMI, and the next subsection shows why PMI turns up anyway.

What word2vec is computing

Recall the negative sampling objective of Equation (9.11), take one word and one context, and write x=w⊤cx = w^{\!\top} c for their dot product. Over the whole corpus that pair is seen #(w,c)\#(w,c) times as an observed pair. It also turns up as a sampled negative. A word ww is the centre of #(w)\#(w) windows, each draws kk negatives, and each negative is cc with probability P(c)P(c), so the pair appears as a negative k⋅#(w)⋅P(c)k \cdot \#(w) \cdot P(c) times in expectation. Collect the two contributions:

ℓ(x)=#(w,c)log⁡σ(x)+k#(w)P(c)log⁡σ(−x).(9.21)\begin{equation} \ell(x) \;=\; \#(w,c)\,\log \sigma(x) \;+\; k\,\#(w)\,P(c)\,\log \sigma(-x). \label{eq:sgns-local} \quad\text{(9.21)} \end{equation}

Differentiate and set the result to zero. Using σ′(x)=σ(x)σ(−x)\sigma'(x) = \sigma(x)\sigma(-x),

∂ℓ∂x=#(w,c)(1−σ(x))−k#(w)P(c)σ(x)=0.(9.22)\begin{equation} \frac{\partial \ell}{\partial x} \;=\; \#(w,c)\big(1 - \sigma(x)\big) \;-\; k\,\#(w)\,P(c)\,\sigma(x) \;=\; 0 . \label{eq:sgns-stationary} \quad\text{(9.22)} \end{equation}

Write a=#(w,c)a = \#(w,c) and b=k#(w)P(c)b = k\,\#(w)\,P(c). Then σ(x)=a/(a+b)\sigma(x) = a / (a + b), and since σ(x)=ex/(1+ex)\sigma(x) = e^{x} / (1 + e^{x}), this gives ex=a/be^{x} = a/b. Substituting P(c)=#(c)/|D|P(c) = \#(c) / |D|, where |D||D| is the number of pairs in the corpus:

w⊤c=log⁡#(w,c)|D|#(w)#(c)−log⁡k=PMI⁡(w,c)−log⁡k.(9.23)\begin{equation} w^{\!\top} c \;=\; \log \frac{\#(w,c)\,|D|}{\#(w)\,\#(c)} \;-\; \log k \;=\; \operatorname{PMI}(w, c) \;-\; \log k . \label{eq:sgns-is-pmi} \quad\text{(9.23)} \end{equation}

This is the result of Levy and Goldberg (2014), that the optimum of skip-gram with negative sampling is a PMI matrix shifted down by log⁡k\log k. Two hundred dimensions of gradient descent, and the answer was in Chapter 7 all along.

The shift has a plain reading, since more negatives means a higher bar. With k=5k=5 every entry moves down by log⁡5≈1.609\log 5 \approx 1.609, so a pair needs stronger evidence before its dot product goes positive.

The claim is checkable on the eight-word matrix of Chapter 7. Train the objective directly, then compare each learned dot product against PMI⁡−log⁡k\operatorname{PMI} - \log k.

pair w⊤cw^{\!\top} c learned PMI⁡−log⁡k\operatorname{PMI} - \log k difference
cat, vet −1.402-1.402 −1.402-1.402 +0.000+0.000
vet, vet −0.223-0.223 −0.223-0.223 +0.000+0.000
dog, fur −0.821-0.821 −0.821-0.821 −0.000-0.000
fuel, tyre −0.533-0.533 −0.533-0.533 +0.001+0.001
vet, feed −1.402-1.402 −1.409-1.409 +0.006+0.006
pet, feed −0.946-0.946 −0.939-0.939 −0.007-0.007

Across all 3232 observed pairs the mean absolute difference is 0.00240.0024 with k=5k = 5, and the largest is 0.00740.0074. The network was never shown a PMI value.

What GloVe is computing

GloVe fits log⁡Xij\log X_{ij} and not an association score, and it looks like a different animal. It is not. Expand PMI in raw counts and it becomes log⁡Xij−log⁡Xi⋅−log⁡X⋅j+log⁡X⋅⋅\log X_{ij} - \log X_{i\cdot} - \log X_{\cdot j} + \log X_{\cdot\cdot}. GloVe’s two bias terms are free to absorb the row and column logarithms, so its dot product fits PMI up to whatever the biases take up. The derivation, and the biases fitted on the eight-word matrix of Chapter 7, are in Appendix C.

Three chapters of machinery converge on one target. SVD fits PPMI, word2vec fits PMI shifted by log⁡k\log k, and GloVe fits PMI with the shift absorbed into two bias terms. That also settles a puzzle from earlier, because the exponent 0.750.75 appears in PMI smoothing, in negative sampling and in GloVe’s weighting function, and it is the same correction applied to the same statistic, three times over.

Where they genuinely differ

Sharing a target does not make three methods interchangeable. The differences sit in the two remaining columns of the table, which are how each cell is weighted and what happens to the zeros.

Weighting first. The SVD minimises squared error over every cell equally, so a pair seen once counts as much as a pair seen ten thousand times. Word2vec weights each pair by how often it occurred, since the objective sums over actual windows, and GloVe states its weighting outright in f(Xij)f(X_{ij}) and can therefore tune it.

The zeros matter more and they are easy to miss. Most of a co-occurrence matrix is zeros, and the three methods treat them in three different ways. PPMI writes an explicit 00 and the SVD fits it like any other cell, while word2vec never fits a zero cell directly. Negative sampling still drags it down, because an unseen pair is drawn as a negative and never as a positive, and GloVe sets f(0)=0f(0) = 0 and drops those cells entirely.

There is a case where that difference bites. Take the matrix from Chapter 7, with four animal words, four vehicle words and no shared context at all, compress it to two dimensions by each method, then ask for nearest neighbours.

query SVD of PPMI word2vec GloVe
dog cat +1.00+1.00 cat +1.00+1.00 truck +0.99+0.99
car truck +1.00+1.00 truck +1.00+1.00 dog +0.80+0.80
vet dog +1.00+1.00 pet +1.00+1.00 fuel +1.00+1.00
fuel car +1.00+1.00 drive +1.00+1.00 vet +1.00+1.00

Two methods get all four right while GloVe gets all four wrong, and it is not a training failure, since its fit to log⁡Xij\log X_{ij} is good at a mean absolute error of 0.0180.018. The explanation is the zeros. On this matrix every fact that separates an animal from a vehicle lives in a cell that is zero, and GloVe drops those cells. It is never shown a single piece of evidence that a dog is unlike a truck. The two groups are fitted on disjoint contexts with nothing tying them together, so their relative positions are left to the initialiser.

Fill each zero with a count of 11 and GloVe recovers all four. Real corpora have almost no structural zeros, because in a large enough corpus most pairs eventually co-occur once, so this never became a practical problem, and the toy exposes the mechanism so cleanly.

The remaining difference is cost. The SVD needs the whole matrix in memory and a full decomposition, which is cubic in the smaller dimension, whereas word2vec needs only a stream of windows and never builds the matrix at all. That, rather than vector quality, is why the learned methods took over in 2013.

Why dd and KK are the same question

The factorisation view also settles what the embedding dimension means. In the SVD picture the top singular values carry most of the semantic structure, and Chapter 7 used their decay to choose KK through the contribution ratio of Equation (7.4).

word2vec’s hidden layer dimension dd plays the identical role, being a budget for how many directions you are willing to keep, and the parallel can be put as one between hidden units and significant eigenvalues. Choosing dd is therefore the bias-variance trade off in disguise. Too few dimensions lose semantic information, and too many fit noise. That predicts something you can check, because raising dd past the number of significant singular values should buy little, and in practice it does. The useful dd tends to land near the count of large singular values, which is what the scree plot of Chapter 7 was showing all along.

Run it. code/worked_examples/factorisation.py produces every number in this section, on the matrix Chapter 7 already used. Run it plain for all four steps. --sgns --k 1 shows the shift vanishing when there is one negative, and --k 15 shows it growing. --compare prints the neighbour table above, and --compare --fill 1 removes the structural zeros and watches GloVe come back into line.

Run it

Reading the geometry

An embedding space is an object you can interrogate, and learning to read one is a practitioner’s core skill. Every question you can ask reduces to one operation, the cosine similarity of Chapter 4:

cos⁡(u,v)=u⋅v‖u‖‖v‖.(9.24)\begin{equation} \cos(u, v) \;=\; \frac{u \cdot v}{\lVert u \rVert\,\lVert v \rVert}. \label{eq:cosine} \quad\text{(9.24)} \end{equation}

It ranges from 11 for the same direction through 00 for orthogonal to −1-1 for opposite. We use the angle, not the raw dot product for a specific reason: vector length in these spaces tracks word frequency more than meaning, while direction is where the semantics live.

From cosine, three tools follow. Nearest neighbours are the words of highest cosine to a target, excluding the target itself, and they reveal what a word means to the space, so the neighbours of bank expose whether your corpus was about rivers or money. Analogies, through Equation (9.12), probe whether a relationship is encoded as a clean direction.

Failures are as informative as successes. On a corpus of a few thousand documents many analogies return nonsense, because the relationship was never witnessed often enough to become a stable direction. Knowing that a bad analogy usually means thin data, not a broken method is the forensic skill that auditing an embedding space requires.

The limit that motivates everything after

For all their elegance, these embeddings share one fatal limitation: each word gets one vector, forever. The bank of a river and the bank that holds money collapse into a single point, and that point is the blurred average of both senses, correct for neither.

A word’s meaning depends on its sentence, and a lookup table cannot represent that because it committed to the vector before the sentence existed. Repairing this is the achievement of the contextual embeddings and transformers of Part IV, which let a word’s representation depend on its context.

The tools you build here do not go away, because cosine, nearest neighbours and association tests are how those larger models are probed and audited. Learning to read a space by hand now is learning to read every space later.

Summary

Word2vec learns a dense vector per word by training a one-hidden-layer network to predict context. Skip-gram predicts each neighbour from the centre word and suits rare words. CBOW predicts the centre from an averaged context and is faster. The full softmax sums over the vocabulary, so training uses a cheaper substitute. Hierarchical softmax costs the path length through a tree. Negative sampling replaces the sum by a few yes-or-no questions, with noise drawn at the 0.750.75 power of frequency. A trained space shows analogies as directions, and also shows the corpus, including its biases, which a WEAT score measures. GloVe fits the logarithm of co-occurrence counts with a weighting function, and FastText builds a word from character n-grams so that unseen words still get vectors. The three count and learn families fit closely related targets, since skip-gram with negative sampling factorises PMI shifted by log⁡k\log k. Every one of them gives a word a single vector, which is the limit the next part removes.

Key terms

word2vec. a method that learns word vectors by predicting context words with a one-hidden-layer network.

skip-gram. the word2vec formulation that predicts each context word from the centre word.

CBOW. the formulation that predicts the centre word from the average of its context vectors.

negative sampling. training with a few sampled noise words per pair instead of a full softmax.

hierarchical softmax. a softmax computed along a path in a binary tree over the vocabulary.

GloVe. a method that fits the logarithm of co-occurrence counts with a weighted least squares objective.

FastText. a model that represents a word as the sum of the vectors of its character n-grams.

analogy. a relation read as a direction, so that king minus man plus woman lands near queen.

WEAT. an association test that measures how strongly two target sets differ in similarity to two attribute sets.

Further reading.

Mikolov et al. (2013) introduce negative sampling. Pennington et al. (2014) on GloVe and Bojanowski et al. (2017) on FastText are the siblings. Caliskan et al. (2017) is the WEAT paper and a model of careful measurement. Rong (2014) explains word2vec’s parameter updates step by step. Le and Mikolov (2014) extends the idea from words to whole sentences and documents. Arora et al. (2016) analyses the linear algebraic structure that lets a single vector encode several senses of a word. Levy and Goldberg (2014) proves that negative sampling factorises a shifted PMI matrix, and Levy et al. (2015) shows that much of word2vec’s reported advantage over counting was down to hyperparameters, not to method. The implementation most people train with is gensim’s Word2Vec, whose arguments are this chapter’s choices under other names, and in any framework the two update rules above are what a single call to backward() produces.

Practice problems

9.1 Count the examples. A sentence has six words and the window is two on each side. How many skip-gram pairs and how many CBOW examples does it produce? Check your method against the five-word sentence of this chapter, which gives 1414 and 55.

9.2 Path length. A vocabulary has one million words. How many binary decisions does a balanced hierarchical softmax tree need per word, and how many dot products does negative sampling with k=5k = 5 need per pair? Compare both with the full softmax and say which you would use when the vocabulary is small.

9.3 Derive the shift. Starting from Equation (9.21), differentiate with respect to x=w⊤cx = w^{\!\top} c and recover Equation (9.23). Then state what happens to the target as kk grows, and why k=1k = 1 makes the shift disappear. Verify one row of the table numerically with factorisation.py --sgns --k 1.

Build and measure

9.4 Build the toolkit. Start from a trained embedding space. PPMI plus SVD over a corpus of your choice works well. Implement three functions: cosine similarity, kk nearest neighbours, and analogy solving. Make sure your analogy function excludes the three query words from the answer. Omitting that exclusion is the most common way to overstate performance.

9.5 The exclusion trap, measured. Run twenty analogies twice, once with the query words excluded and once without. Report how much the score improves when you cheat. Which query word wins most often, and why is it usually cc and not aa or bb?

9.6 Bend the sampling distribution. Using Equation (9.8), recompute the five word table in this chapter with exponents 1.01.0, 0.750.75 and 0.50.5. At which exponent does aardvark get sampled ten times its share? What would go wrong at each extreme?

9.7 Embedding forensics. Take five word vectors, add a little random noise to each, and identify the original words using only cosine and nearest neighbours. Report how much noise your identification survives, and which words are easiest and hardest to recover.

9.8 Break GloVe on purpose. Build a small co-occurrence matrix whose two word groups share no context. Fit GloVe to it and report the nearest neighbours. Explain, using f(0)=0f(0) = 0, why the groups are not separated. Then add a single count to every empty cell and report what changes. Which of SVD and word2vec would you expect to survive the original matrix, and why?

9.9 Autograd will derive your update rules. Build the single training step of this chapter in torch: a centre vector at (0.5,−0.2)(0.5, -0.2) for cat, context vectors for sat and the, and the negative sampling objective over one positive pair and one negative pair. Call backward() and take one step at η=0.1\eta = 0.1. You should land on (0.4228,0.0909)(0.4228, 0.0909), (−0.3216,0.6087)(-0.3216, 0.6087) and a centre vector at (0.5312,−0.2214)(0.5312, -0.2214), all three of which this chapter computes by hand. If your context vectors move and your centre vector does not, you have implemented Equation (9.9) and forgotten Equation (9.10).

In practice

9.10 Audit the analogies. Run twenty analogy queries of your own and record which succeed and which fail. Group the failures and propose an explanation for each group: frequency effects, polysemy, a missing relation direction. Analogies are hit or miss. Your job is to say when and why.

9.11 Measure a bias. Choose two target sets and two attribute sets, for example two families of names against two families of adjectives. Compute a WEAT score with Equation (9.14). Interpret its sign and magnitude, and state one thing the number does not license you to conclude.

9.12 A morphologically rich language. A team has a corpus in Tamil and finds that word2vec gives poor vectors for most inflected forms. Explain why, say which of the models in this chapter addresses it and how, and name one cost of the fix.

Code for this chapter

Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.