TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Word Embeddings: PPMI, SVD and Word2Vec

Word Embeddings: PPMI, SVD and Word2Vec

Bag of words and TF-IDF give every word its own column. "Doctor" and "nurse" are as different as "doctor" and "banana": the vectors are orthogonal, so a classifier trained on reviews that say "superb" learns nothing about "excellent". What we want is a dense vector per word, a few dozen to a few hundred numbers, in which words used the same way sit close together.

The idea behind every method in this lesson is the distributional hypothesis: a word is characterised by the company it keeps. If "cat" and "dog" both appear next to "eats", "runs" and "field", they should get similar vectors. Embedding Layers already trained skip-gram with negative sampling (word2vec) in PyTorch. This lesson builds the older count-based route from scratch, shows that the two routes are close relatives, and then looks at what word vectors can and cannot do: analogies, bias, and words with more than one meaning.

A corpus with known structure

To judge an embedding, it helps to know the right answer. The corpus below is generated from templates with a fixed seed: people words that differ in gender (he/she, his/her) and status (royal places versus houses and schools), animals that eat grass and sleep in barns, fruit that is sweet or ripe, and four job words whose pronoun is deliberately skewed: "the nurse said she was busy" 85 % of the time, "the engineer said he was busy" 85 % of the time. The skew is the planted bias we will look for later.

Counting co-occurrences

Slide a window of ±4\pm 4 words over every sentence and count how often each word ww appears with each context word cc. The result is a V×VV \times V matrix CC with CwcC_{wc} = number of times cc was within the window of ww.

Raw counts are dominated by frequent words: every noun co-occurs with "the". Pointwise mutual information asks instead whether ww and cc appear together more often than they would by chance:

PMI⁡(w,c)=log⁡P(w,c)P(w) P(c),P(w,c)=Cwc∑w′,c′Cw′c′,P(w)=∑cP(w,c),P(c)=∑wP(w,c)\operatorname{PMI}(w, c) = \log \frac{P(w, c)}{P(w)\,P(c)}, \qquad P(w, c) = \frac{C_{wc}}{\sum_{w', c'} C_{w'c'}}, \quad P(w) = \sum_c P(w, c), \quad P(c) = \sum_w P(w, c)

PMI is 0 when ww and cc are independent, positive when they attract and negative (down to −∞-\infty for pairs never seen) when they repel. Negative values estimated from small counts are noisy, so the usual choice is positive PMI:

PPMI⁡(w,c)=max⁡(PMI⁡(w,c), 0)\operatorname{PPMI}(w, c) = \max\bigl(\operatorname{PMI}(w, c),\ 0\bigr)
python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
people = {"man": "he common", "woman": "she common", "king": "he royal", "queen": "she royal",
          "boy": "he young", "girl": "she young", "prince": "he royal", "princess": "she royal"}
places = {"common": ["house", "street", "office"], "royal": ["palace", "throne", "crown"],
          "young": ["school", "garden", "toys"]}
jobs = {"doctor": 0.8, "engineer": 0.85, "teacher": 0.3, "nurse": 0.15}   # share of "he" in the corpus

def sentence():
    r = rng.random()
    if r < 0.45:                                   # people: gender and status
        p = str(rng.choice(list(people))); pron, kind = people[p].split()
        poss, place, t = {"he": "his", "she": "her"}[pron], rng.choice(places[kind]), rng.integers(3)
        return [f"the {p} said {pron} was tired", f"the {p} went to {poss} {place}",
                f"{pron} is the {p} of the {place}"][t]
    if r < 0.6:                                    # jobs: a skewed pronoun
        j = str(rng.choice(list(jobs)))
        return f"the {j} said {'he' if rng.random() < jobs[j] else 'she'} was busy"
    if r < 0.8:
        return f"the {rng.choice(['cat', 'dog', 'horse', 'cow'])} " + rng.choice(
            ["runs in the field", "eats grass", "sleeps in the barn"])
    return f"the {rng.choice(['apple', 'pear', 'plum', 'banana'])} " + rng.choice(
        ["is sweet", "is ripe", "fell from the tree"])

corpus = [sentence().split() for _ in range(3000)]
vocab = sorted({w for s in corpus for w in s})
idx = {w: i for i, w in enumerate(vocab)}

def cooc(corpus, window=4):
    C = np.zeros((len(vocab), len(vocab)))
    for s in corpus:
        for i, w in enumerate(s):
            for j in range(max(0, i - window), min(len(s), i + window + 1)):
                if j != i:
                    C[idx[w], idx[s[j]]] += 1
    return C

def ppmi(C):
    pwc = C / C.sum()
    pw, pc = pwc.sum(1, keepdims=True), pwc.sum(0, keepdims=True)
    with np.errstate(divide="ignore"):
        return np.maximum(np.log(pwc / (pw * pc)), 0)

C = cooc(corpus)
P = ppmi(C)
print("sentences:", len(corpus), "| vocabulary:", len(vocab), "| context pairs:", int(C.sum()))
print("examples:", " / ".join(" ".join(s) for s in corpus[:3]))
for w in ["king", "nurse", "cat"]:
    i = idx[w]
    by_count = [vocab[k] for k in np.argsort(-C[i], kind="stable")[:4]]
    by_ppmi = [(vocab[k], round(float(P[i, k]), 2)) for k in np.argsort(-P[i], kind="stable")[:4]]
    print(f"{w:6s} counts: {by_count}")
    print(f"{'':6s} PPMI:   {by_ppmi}")
print("PPMI cells that are zero:", f"{(P == 0).mean():.0%}")
sentences: 3000 | vocabulary: 54 | context pairs: 77488
examples: the horse runs in the field / the man said he was tired / the banana is ripe
king   counts: ['the', 'he', 'is', 'of']
       PPMI:   [('palace', 1.87), ('throne', 1.86), ('crown', 1.63), ('his', 1.43)]
nurse  counts: ['busy', 'said', 'the', 'was']
       PPMI:   [('busy', 2.18), ('she', 1.52), ('said', 1.28), ('was', 1.28)]
cat    counts: ['the', 'in', 'eats', 'grass']
       PPMI:   [('eats', 2.45), ('grass', 2.45), ('field', 2.17), ('runs', 1.95)]
PPMI cells that are zero: 81%

By raw count, "king" is closest to "the", "he", "is" and "of", which says nothing about kings. After PPMI the top contexts are "palace", "throne" and "crown", and for "nurse" the word "she" appears in second place: the planted skew is already visible in a single row. The matrix is also sparse: 81 % of the PPMI cells are zero, and with a real vocabulary of 100,000 words it would be almost entirely zeros.

From sparse rows to dense vectors: truncated SVD

A PPMI row is a VV-dimensional vector. To compress it, take the singular value decomposition M=UΣV⊤M = U \Sigma V^\top and keep the kk largest singular values:

M≈UkΣkVk⊤,word vectors W=UkΣk∈RV×kM \approx U_k \Sigma_k V_k^\top, \qquad \text{word vectors } W = U_k \Sigma_k \in \mathbb{R}^{V \times k}

By the Eckart-Young theorem this is the best rank-kk approximation in the least-squares sense, so words whose PPMI rows are similar get similar kk-dimensional vectors even when they never share an exact context column. Similarity between words is the cosine cos⁡(u,v)=u⋅v∥u∥ ∥v∥\cos(u, v) = \frac{u \cdot v}{\lVert u \rVert\,\lVert v \rVert}; normalising every vector to unit length turns it into a dot product. (Levy, Goldberg and Dagan found that UkΣkpU_k \Sigma_k^{p} with p=0.5p = 0.5 or p=0p = 0 often works better than p=1p = 1 on real corpora; it is a hyperparameter.)

Analogies by vector offset. If one direction in the space encodes gender and another encodes status, then king−man+woman\text{king} - \text{man} + \text{woman} should land near "queen". The test takes the word whose vector has the highest cosine with b−a+cb - a + c:

d∗=arg⁡max⁡d∉{a,b,c}cos⁡(vd, vb−va+vc)d^\ast = \arg\max_{d \notin \{a, b, c\}} \cos\bigl(v_d,\ v_b - v_a + v_c\bigr)
python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
people = {"man": "he common", "woman": "she common", "king": "he royal", "queen": "she royal",
          "boy": "he young", "girl": "she young", "prince": "he royal", "princess": "she royal"}
places = {"common": ["house", "street", "office"], "royal": ["palace", "throne", "crown"],
          "young": ["school", "garden", "toys"]}
jobs = {"doctor": 0.8, "engineer": 0.85, "teacher": 0.3, "nurse": 0.15}   # share of "he" in the corpus

def sentence():
    r = rng.random()
    if r < 0.45:                                   # people: gender and status
        p = str(rng.choice(list(people))); pron, kind = people[p].split()
        poss, place, t = {"he": "his", "she": "her"}[pron], rng.choice(places[kind]), rng.integers(3)
        return [f"the {p} said {pron} was tired", f"the {p} went to {poss} {place}",
                f"{pron} is the {p} of the {place}"][t]
    if r < 0.6:                                    # jobs: a skewed pronoun
        j = str(rng.choice(list(jobs)))
        return f"the {j} said {'he' if rng.random() < jobs[j] else 'she'} was busy"
    if r < 0.8:
        return f"the {rng.choice(['cat', 'dog', 'horse', 'cow'])} " + rng.choice(
            ["runs in the field", "eats grass", "sleeps in the barn"])
    return f"the {rng.choice(['apple', 'pear', 'plum', 'banana'])} " + rng.choice(
        ["is sweet", "is ripe", "fell from the tree"])

corpus = [sentence().split() for _ in range(3000)]
vocab = sorted({w for s in corpus for w in s})
idx = {w: i for i, w in enumerate(vocab)}

def cooc(corpus, window=4):
    C = np.zeros((len(vocab), len(vocab)))
    for s in corpus:
        for i, w in enumerate(s):
            for j in range(max(0, i - window), min(len(s), i + window + 1)):
                if j != i:
                    C[idx[w], idx[s[j]]] += 1
    return C

def ppmi(C):
    pwc = C / C.sum()
    pw, pc = pwc.sum(1, keepdims=True), pwc.sum(0, keepdims=True)
    with np.errstate(divide="ignore"):
        return np.maximum(np.log(pwc / (pw * pc)), 0)

P = ppmi(cooc(corpus))
U, S, Vt = np.linalg.svd(P)
k = 20
E = U[:, :k] * S[:k]                              # one 20-d vector per word
E /= np.linalg.norm(E, axis=1, keepdims=True)     # unit length: dot product = cosine

def nearest(v, exclude=(), n=3):
    sims = E @ (v / np.linalg.norm(v))
    order = [i for i in np.argsort(-sims, kind="stable") if vocab[i] not in exclude][:n]
    return [(vocab[i], round(float(sims[i]), 2)) for i in order]

print("singular values:", np.round(S[:6], 1).tolist(), "...", round(float(S[k - 1]), 1))
for w in ["king", "cat", "apple", "nurse"]:
    print(f"{w:6s}", nearest(E[idx[w]], exclude=[w]))
a, b, c = "man", "king", "woman"
q = E[idx[b]] - E[idx[a]] + E[idx[c]]
print("king - man + woman:", nearest(q, exclude=[a, b, c]))
print("  without excluding the inputs:", nearest(q))
q = E[idx["prince"]] - E[idx["boy"]] + E[idx["girl"]]
print("prince - boy + girl:", nearest(q, exclude=["prince", "boy", "girl"]))

from sklearn.decomposition import TruncatedSVD      # the library version, also takes sparse input
Z = TruncatedSVD(n_components=k, algorithm="arpack", random_state=0).fit_transform(P)
Z /= np.linalg.norm(Z, axis=1, keepdims=True)
print("same cosines as NumPy's SVD:", np.allclose(Z @ Z.T, E @ E.T, atol=1e-6))
singular values: [15.4, 13.9, 12.6, 8.9, 8.7, 8.7] ... 3.1
king   [('prince', 1.0), ('queen', 0.78), ('princess', 0.77)]
cat    [('horse', 1.0), ('dog', 1.0), ('cow', 0.99)]
apple  [('plum', 1.0), ('pear', 1.0), ('banana', 1.0)]
nurse  [('teacher', 0.99), ('doctor', 0.89), ('engineer', 0.89)]
king - man + woman: [('queen', 0.99), ('princess', 0.98), ('prince', 0.82)]
  without excluding the inputs: [('queen', 0.99), ('princess', 0.98), ('king', 0.84)]
prince - boy + girl: [('queen', 0.99), ('princess', 0.98), ('king', 0.86)]
same cosines as NumPy's SVD: True

The neighbours are what the templates planted: animals with animals, fruit with fruit, jobs with jobs. "king - man + woman" gives "queen" (0.99). But look at the two warning signs:

  • The excluded inputs. Without the d∉{a,b,c}d \notin \{a, b, c\} rule, "king" itself is third (0.84). In embeddings trained on real text the nearest vector to b−a+cb - a + c is very often bb or cc, and the published analogy accuracies depend on removing them. The offset moves the query only a little away from bb; the exclusion does much of the work.
  • The analogy the corpus cannot answer. "prince - boy + girl" should give "princess", but "queen" wins (0.99 against 0.98). In this corpus "prince" is used in exactly the same royal contexts as "king", nothing says "prince = young royal", so the vectors cannot encode that relation. An analogy only works when the relation is a consistent offset in the data, and many real relations (country to capital, singular to plural for irregular nouns) are not.

The last line checks the library version: sklearn.decomposition.TruncatedSVD gives the same cosines. It also accepts a sparse matrix, which is what you would use for a real vocabulary (the full SVD of a 100,000×100,000100{,}000 \times 100{,}000 dense matrix would not fit in memory).

word2vec, GloVe and fastText

Skip-gram with negative sampling (SGNS, Mikolov et al. 2013) trains a word vector ww and a context vector cc so that σ(w⋅c)\sigma(w \cdot c) is high for observed pairs and low for kk random "negative" contexts drawn from the unigram distribution raised to the power 0.750.75. You trained it in Embedding Layers. Levy and Goldberg (2014) showed that, at its optimum, SGNS factorises a shifted PMI matrix:

w⋅c=PMI⁡(w,c)−log⁡kw \cdot c = \operatorname{PMI}(w, c) - \log k

So count-based PPMI + SVD and prediction-based word2vec are two ways to factorise the same kind of statistics. In practice SGNS handles huge corpora by streaming, and its tricks (subsampling frequent words, the 0.750.75 power on context counts) can be transplanted into the count-based version and close most of the gap.

GloVe (Pennington, Socher and Manning 2014) fits the logarithm of the counts directly with a weighted least-squares loss over the non-zero cells of XX (the co-occurrence count matrix):

J=∑i,j: Xij>0f(Xij)(wi⊤w~j+bi+b~j−log⁡Xij)2,f(x)={(x/xmax⁡)αx<xmax⁡1otherwiseJ = \sum_{i, j:\ X_{ij} > 0} f(X_{ij}) \bigl(w_i^\top \tilde{w}_j + b_i + \tilde{b}_j - \log X_{ij}\bigr)^2, \qquad f(x) = \begin{cases} (x / x_{\max})^{\alpha} & x < x_{\max} \\ 1 & \text{otherwise} \end{cases}

with xmax⁡=100x_{\max} = 100 and α=3/4\alpha = 3/4 in the paper. The weight ff stops rare, noisy pairs from counting as much as frequent ones and caps the influence of the most frequent pairs. The final vector is usually wi+w~iw_i + \tilde{w}_i.

fastText (Bojanowski et al. 2017) changes what gets a vector. A word is wrapped in boundary markers and split into character nn-grams, n=3n = 3 to 66: "where" becomes <wh, whe, her, ere, re>, <whe, … plus the whole word <where>. The word vector is the sum of its nn-gram vectors, and SGNS is trained on those sums. Two consequences: words that share pieces ("teach", "teacher", "teaching") share parameters, and a word never seen in training still gets a vector from its nn-grams. This is the same intuition that leads to the subword tokenizers of the next section.

Bias in embeddings

Embeddings learn whatever the corpus says, including stereotypes. Bolukbasi et al. (2016) found occupations lined up along a he-she direction in word2vec trained on news. We can measure the planted skew the same way: average the differences of the gendered pairs to get a direction gg, and project each word on it.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
people = {"man": "he common", "woman": "she common", "king": "he royal", "queen": "she royal",
          "boy": "he young", "girl": "she young", "prince": "he royal", "princess": "she royal"}
places = {"common": ["house", "street", "office"], "royal": ["palace", "throne", "crown"],
          "young": ["school", "garden", "toys"]}
jobs = {"doctor": 0.8, "engineer": 0.85, "teacher": 0.3, "nurse": 0.15}   # share of "he" in the corpus

def sentence():
    r = rng.random()
    if r < 0.45:                                   # people: gender and status
        p = str(rng.choice(list(people))); pron, kind = people[p].split()
        poss, place, t = {"he": "his", "she": "her"}[pron], rng.choice(places[kind]), rng.integers(3)
        return [f"the {p} said {pron} was tired", f"the {p} went to {poss} {place}",
                f"{pron} is the {p} of the {place}"][t]
    if r < 0.6:                                    # jobs: a skewed pronoun
        j = str(rng.choice(list(jobs)))
        return f"the {j} said {'he' if rng.random() < jobs[j] else 'she'} was busy"
    if r < 0.8:
        return f"the {rng.choice(['cat', 'dog', 'horse', 'cow'])} " + rng.choice(
            ["runs in the field", "eats grass", "sleeps in the barn"])
    return f"the {rng.choice(['apple', 'pear', 'plum', 'banana'])} " + rng.choice(
        ["is sweet", "is ripe", "fell from the tree"])

corpus = [sentence().split() for _ in range(3000)]
vocab = sorted({w for s in corpus for w in s})
idx = {w: i for i, w in enumerate(vocab)}

def cooc(corpus, window=4):
    C = np.zeros((len(vocab), len(vocab)))
    for s in corpus:
        for i, w in enumerate(s):
            for j in range(max(0, i - window), min(len(s), i + window + 1)):
                if j != i:
                    C[idx[w], idx[s[j]]] += 1
    return C

def ppmi(C):
    pwc = C / C.sum()
    pw, pc = pwc.sum(1, keepdims=True), pwc.sum(0, keepdims=True)
    with np.errstate(divide="ignore"):
        return np.maximum(np.log(pwc / (pw * pc)), 0)

U, S, Vt = np.linalg.svd(ppmi(cooc(corpus)))
E = U[:, :20] * S[:20]
E /= np.linalg.norm(E, axis=1, keepdims=True)

pairs = [("man", "woman"), ("king", "queen"), ("boy", "girl"), ("prince", "princess")]
g = sum(E[idx[m]] - E[idx[f]] for m, f in pairs)
g /= np.linalg.norm(g)                            # the "gender direction"
neutral = ["doctor", "engineer", "teacher", "nurse", "cat", "apple"]
print("projection on he-she direction:", {w: round(float(E[idx[w]] @ g), 2) + 0.0 for w in neutral})

# hard debiasing (Bolukbasi et al. 2016): remove the direction from words that should be neutral
D = E.copy()
for w in neutral:
    v = D[idx[w]] - (D[idx[w]] @ g) * g
    D[idx[w]] = v / np.linalg.norm(v)
print("after removing it:            ", {w: round(float(D[idx[w]] @ g), 2) + 0.0 for w in neutral})
sims = D @ D[idx["nurse"]]
print("nurse's neighbours after:", [vocab[i] for i in np.argsort(-sims, kind="stable")[1:4]])
print("cos(nurse, she) before/after:", round(float(E[idx["nurse"]] @ E[idx["she"]]), 2),
      round(float(D[idx["nurse"]] @ D[idx["she"]]), 2))
projection on he-she direction: {'doctor': 0.23, 'engineer': 0.23, 'teacher': -0.11, 'nurse': -0.25, 'cat': 0.0, 'apple': -0.01}
after removing it:             {'doctor': 0.0, 'engineer': 0.0, 'teacher': 0.0, 'nurse': 0.0, 'cat': 0.0, 'apple': 0.0}
nurse's neighbours after: ['teacher', 'engineer', 'doctor']
cos(nurse, she) before/after: 0.46 0.46

"doctor" and "engineer" lean towards "he" (0.23), "nurse" towards "she" (−0.25-0.25), and "cat" and "apple" are neutral, which is the planted skew. Hard debiasing removes the component along gg from words that should be neutral, v←v−(v⋅g) gv \leftarrow v - (v \cdot g)\,g, and after it every projection is 0.00. But the last line shows what Gonen and Goldberg (2019) called "lipstick on a pig": the cosine between "nurse" and "she" is still 0.46. The gender information was not only along gg; it is spread over other dimensions, and a classifier can still recover it. Removing one direction makes a metric look clean, it does not remove the association. The honest fixes are about data (what the corpus over- and under-represents) and about measuring the harm in the downstream task.

Static versus contextual embeddings

Every vector so far is static: one vector per word type. "bank" gets the same vector in "the river bank" and "the bank raised its rate", a compromise between the two senses weighted by how often each occurs. Contextual models (ELMo, then BERT and every transformer) compute a vector per token occurrence, from the whole sentence. The recorded check below uses a tiny BERT (2 layers, hidden size 128): its input embedding table is static, its output is not.

python · try it yourself
import torch
from transformers import AutoTokenizer, AutoModel
from transformers.utils import logging
logging.set_verbosity_error()

name = "google/bert_uncased_L-2_H-128_A-2"
tok, model = AutoTokenizer.from_pretrained(name), AutoModel.from_pretrained(name).eval()
sentences = ["we sat on the bank of the river", "the river bank was muddy after the rain",
             "she paid the cash into the bank", "the bank raised its interest rate"]

static, contextual = [], []
with torch.no_grad():
    for s in sentences:
        enc = tok(s, return_tensors="pt")
        pos = enc.input_ids[0].tolist().index(tok.convert_tokens_to_ids("bank"))
        out = model(**enc)
        static.append(model.embeddings.word_embeddings.weight[enc.input_ids[0, pos]])
        contextual.append(out.last_hidden_state[0, pos])

cos = torch.nn.functional.cosine_similarity
print("static vectors identical:", all(torch.equal(static[0], v) for v in static))
print("contextual cosine of 'bank' (rows/cols = sentences 1-4):")
for i in range(4):
    print(" ", [round(float(cos(contextual[i], contextual[j], dim=0)), 3) for j in range(4)])
static vectors identical: True
contextual cosine of 'bank' (rows/cols = sentences 1-4):
  [1.0, 0.868, 0.853, 0.865]
  [0.868, 1.0, 0.743, 0.843]
  [0.853, 0.743, 1.0, 0.855]
  [0.865, 0.843, 0.855, 1.0]

The four input vectors for "bank" are identical, and the four output vectors are not: no off-diagonal cosine is 1. This 2-layer model separates the senses only weakly. The lowest similarity is between a river sentence and a money sentence (0.743, sentences 2 and 3), but sentence 1 (river) is about as close to sentence 4 (money) as to sentence 2. Full-size models separate senses much more clearly; Inside a Pretrained BERT looks at its layers. Static vectors remain useful when you need something cheap, small and context-free: keyword expansion, features for a linear model, or a first look at a domain's vocabulary.

Pitfalls

  • Window size changes the meaning of "similar". Small windows (±1\pm 1, ±2\pm 2) give syntactic neighbours (words with the same part of speech), large windows give topical ones. With ±2\pm 2 on this corpus, "king"'s top PPMI contexts are function words, because "palace" is three or more words away.
  • PMI overrates rare pairs. A pair seen once with two rare words gets a huge PMI. Raise context counts to the power 0.750.75 before normalising, or ignore words below a minimum count.
  • Analogy scores flatter. Report whether the inputs were excluded, and compare to a baseline that just returns the nearest neighbour of cc.
  • Small corpora give unstable vectors. Different seeds or a few more sentences change the neighbours of rare words. Check stability before drawing conclusions from one word's neighbours.
  • Fit on training text only. Embeddings computed on the test documents leak their vocabulary and co-occurrences into the features, just like a vectorizer fitted on all data.
  • Out-of-vocabulary words get no static vector at all (use fastText-style subwords or a subword tokenizer).

Practice

  1. Two words ww and cc each appear in 1 % of all context pairs, and they appear together in 0.04 % of them. What are their PMI and PPMI (natural log)?
  2. Why does ppmi in the first example use np.errstate(divide="ignore"), and what value do never-seen pairs end up with?
  3. In the second example, why is "king - man + woman" a fairer test than "prince - boy + girl" on this corpus? Change the templates so that the second one works.
  4. A colleague removes the gender direction from all occupation vectors and reports "bias reduced from 0.25 to 0.00". What would you measure before believing it?
  5. Write the fastText nn-grams with n=3n = 3 for the word "cats" (with boundary markers).
Answers
  1. P(w,c)=0.0004P(w, c) = 0.0004 and P(w)P(c)=0.01⋅0.01=0.0001P(w) P(c) = 0.01 \cdot 0.01 = 0.0001, so PMI⁡=ln⁡4≈1.39\operatorname{PMI} = \ln 4 \approx 1.39; PPMI is the same because it is positive.
  2. Pairs with Cwc=0C_{wc} = 0 give log⁡0=−∞\log 0 = -\infty; NumPy would warn about the division by zero inside the log. np.maximum(-inf, 0) turns them into 0, so never-seen pairs have PPMI 0.
  3. "king" and "man" differ in status, "man" and "woman" in gender, and both are consistent offsets in the templates. "prince" is generated with the same royal places as "king", so "young" is never encoded for it. Give the prince and princess their own place list that mixes royal and young words (for example "palace", "garden", "toys"), and "prince - boy + girl" then gives "princess" first, with a cosine of 0.98 (try it: add a "royalyoung" kind with those three places and use it for the prince and the princess).
  4. Whether the association is still recoverable: the cosine of occupations with "he" and "she", their neighbour lists, and the accuracy of a classifier that predicts the stereotyped gender from the debiased vectors. Above all, the bias metric of the actual downstream task (for example, ranking quality for CVs that differ only in gender words).
  5. <ca, cat, ats, ts>, plus the whole-word token <cats> (fastText also adds n=4,5,6n = 4, 5, 6 by default).

Test yourself

Why is PPMI usually better than raw co-occurrence counts for word vectors?

  1. It removes all function words from the vocabulary
  2. It measures how much more often two words co-occur than chance predicts, so frequent words like 'the' stop dominating
  3. It makes the matrix dense
  4. It is required by the SVD

Levy and Goldberg showed that skip-gram with kk negative samples, at its optimum, factorises which matrix?

  1. The raw count matrix
  2. PMI⁡(w,c)−log⁡k\operatorname{PMI}(w, c) - \log k
  3. The TF-IDF matrix
  4. The identity

What lets fastText give a vector to a word it never saw in training?

  1. It falls back to a random vector
  2. The word vector is a sum of character n-gram vectors, and the n-grams were seen in other words
  3. It uses the nearest word by edit distance
  4. It cannot

In the debiasing example the gender projection of 'nurse' becomes 0.00. What does the last line show?

  1. The bias is gone
  2. The cosine between 'nurse' and 'she' is still 0.46: the association survives outside the removed direction
  3. The vectors are now all identical
  4. Debiasing broke the neighbours

What is the key difference between a static embedding and BERT's output vectors?

  1. Static embeddings are larger
  2. BERT computes one vector per token occurrence from the whole sentence; a static table has one vector per word type
  3. BERT has no embedding table
  4. Static embeddings cannot be used with cosine similarity