Sub topic 13
Building a co-occurrence matrix
This chapter assumes you know basic Python and NumPy, dot products and norms, and tokenization. It also assumes you have met context windows from the previous chapters. Here you will turn a corpus into a word co-occurrence matrix. That matrix is the raw input to GloVe, and it also shows what word2vec sees implicitly.
What the matrix records
A co-occurrence matrix X has one row and one column for each vocabulary word. The entry X[i][j] measures how often word j appears in the context window of word i. A context window is the set of words within a fixed distance of a center word.
The matrix is built once, in a single pass over the corpus. After that, training works on the table and does not need to reread the text. This is the main practical difference from word2vec, which streams over the text on every epoch.
Take the sentence "the cat sits on the mat" with a window of 2. For the center word "sits", the context words are "the", "cat", "on" and "the". Each pair adds to a count.
Choices that change the counts
Three decisions shape the matrix. Different settings give different embeddings, so record them.
- Window size. Small windows (1 to 2) capture syntactic similarity, such as which words can fill the same grammatical slot. Large windows (5 to 10) capture topical similarity, such as words about the same subject. GloVe's published vectors used windows of about 10.
- Symmetric or asymmetric. A symmetric matrix counts context on both sides of the word, so X[i][j] equals X[j][i]. An asymmetric one counts only the words to the left, or only those to the right. GloVe uses the symmetric form.
- Weighting by distance. A plain count treats a neighbor 1 word away the same as one 10 words away. GloVe instead adds 1/d for a pair at distance d, so close neighbors count more.
Building it in Python
The function below follows GloVe's weighting. It looks only at words to the left of each position and adds the weight to both (w, c) and (c, w). That keeps the table symmetric and counts every pair once.
from collections import defaultdict
def cooccurrence(sentences, window=2):
counts = defaultdict(float)
for sent in sentences:
for i, w in enumerate(sent):
for j in range(max(0, i - window), i):
c = sent[j]
weight = 1.0 / (i - j)
counts[(w, c)] += weight
counts[(c, w)] += weight
return counts
sentences = [["the", "cat", "sits", "on", "the", "mat"]]
X = cooccurrence(sentences, window=2)
print(X[("cat", "the")])The output is 1.0. The only pair of "cat" and "the" within two words is at positions 0 and 1, at distance 1, so it adds 1/1. Note that the second "the" is 4 positions from "cat", outside the window.
Now check a pair that occurs at two distances. The word "the" appears twice, so the pair ("the", "on") gets two contributions.
print(X[("the", "on")])
print(X[("on", "the")])The first "the" (position 0) is 3 words from "on" (position 3), which is outside the window. The second "the" (position 4) is at distance 1. So both values are 1.0, which also confirms the table is symmetric.
Storing it: sparse, not dense
A vocabulary of 400,000 words would need 400,000 × 400,000 = 1.6 × 10^11 cells as a dense array. At 4 bytes each, that is about 640 GB. Most word pairs never occur together, so the matrix is mostly zeros.
The code above already stores only the nonzero pairs in a dictionary. For larger work, convert to a SciPy sparse matrix, which is faster to slice and multiply.
import numpy as np
from scipy.sparse import coo_matrix
def to_sparse(counts):
vocab = sorted({w for pair in counts for w in pair})
index = {w: i for i, w in enumerate(vocab)}
rows = [index[w] for (w, c) in counts]
cols = [index[c] for (w, c) in counts]
data = np.array(list(counts.values()), dtype=np.float32)
n = len(vocab)
return vocab, coo_matrix((data, (rows, cols)), shape=(n, n)).tocsr()
vocab, M = to_sparse(X)
print(vocab)
print(M.toarray())The dictionary keys and values are read in the same order, so rows, columns and data stay aligned. On a corpus this small, toarray() is safe. On a real one, it would exhaust memory, so avoid it.
From counts to the GloVe objective
Let Xi be the total of row i, which is how much context word i has overall. The ratio P(j | i) = X[i][j] / Xi estimates the probability that word j appears near word i.
GloVe fits word vectors so that the dot product of two vectors, plus bias terms, approximates the logarithm of the count:
wi · w̃j + bi + b̃j ≈ log X[i][j]
Here wi is the vector for word i as a center word, and w̃j is a separate vector for it as a context word. The loss is a weighted least-squares sum over the nonzero entries only. This is why sparsity helps: zero entries have an undefined logarithm, and skipping them also saves work. The weighting function f(X) is small for rare pairs and capped for frequent ones, so neither noise nor very common words dominate.
Common errors
- Counting pairs twice. If your loop looks both left and right, and you also add both (w, c) and (c, w), every pair is counted twice. The values are then doubled, which changes absolute counts but not ratios. It is still a bug if you compare against a reference.
- Crossing sentence boundaries. Windows should not span two unrelated sentences. The function above avoids this by looping per sentence. Whether to cross boundaries within a document is a design choice, so make it deliberately.
- Using a different vocabulary for rows and columns. Build one shared vocabulary first. Mismatched indexes silently scramble the matrix.
- Skipping a frequency cutoff. Words seen once give noisy rows. Most pipelines drop words below a minimum count, such as 5, before building the matrix.
- Forgetting memory. Counting on a large corpus in an in-memory dictionary can outgrow RAM. The original GloVe tool writes partial counts to disk and merges them.
Exercises
Exercise
Using window=2 and the weighting 1/distance, what is X[("sits", "the")] for the sentence "the cat sits on the mat"? Work it out by hand, then check with the code.
Show answer
The first "the" (position 0) is at distance 2 from "sits" (position 2), which adds 0.5. The second "the" (position 4) is at distance 2 from "sits", which adds another 0.5. The total is 1.0. In the code, the pair from position 4 is found when i=4 looks left to j=2 (distance 2), and the pair from position 0 is found when i=2 looks left to j=0 (distance 2). Both contribute 0.5.
Exercise
Why does GloVe fit only the nonzero entries of the matrix, and what two problems does that avoid?
Show answer
The logarithm of zero is undefined, so zero entries cannot be used in log X. Also, the matrix is mostly zeros, so including them would make each training pass far more expensive without adding useful information.