Sub topic 12
Building a Co-occurrence Matrix
Prerequisites: you should know basic Python, NumPy arrays, vectors, and the idea of a training loss. This chapter uses tokenized sentences, so each sentence is already a list of words.
Building a co-occurrence matrix
A co-occurrence matrix records how often words appear near one another. Let the target word be the row and the context word be the column. An entry X[i, j] is the number of times context word j appears within a chosen window around word i.
For example, with a window size of 2, the sentence the cat sits on the mat gives cat nearby words such as the and sits. A larger window captures broader topical relationships, while a smaller window tends to capture syntactic relationships.
The matrix is usually sparse because a vocabulary contains many possible word pairs, but each word occurs near only some of them. GloVe often uses distance weighting: a context word one position away contributes 1, while one two positions away contributes 1/2.
from collections import defaultdict
def cooccurrence(sentences, window=2):
counts = defaultdict(float)
for sentence in sentences:
for i, target in enumerate(sentence):
start = max(0, i - window)
stop = min(len(sentence), i + window + 1)
for j in range(start, stop):
if i == j:
continue
context = sentence[j]
weight = 1.0 / abs(i - j)
counts[(target, context)] += weight
return counts
sentences = [["the", "cat", "sits", "on", "the", "mat"]]
X = cooccurrence(sentences, window=2)
print(X[("cat", "the")])
print(X[("cat", "sits")])This implementation stores only nonzero entries in a dictionary. It also counts both directions when the loop visits each word as a target.
GloVe: fitting log co-occurrence counts
GloVe means Global Vectors. It learns a vector for each target word and another vector for each context word. Their dot product, plus bias terms, is trained to approximate the logarithm of the co-occurrence count:
w_i · c_j + b_i + b_j ≈ log(X_ij)
The logarithm reduces the dominance of extremely frequent pairs. GloVe minimizes a weighted squared error:
f(X_ij) * (w_i · c_j + b_i + b_j - log(X_ij))²
The weighting function f gives little influence to extremely rare observations, prevents very frequent observations from dominating, and becomes capped after a chosen threshold. A common form is:
f(x) = (x / x_max)^alpha when x < x_max, otherwise 1
After training, implementations commonly combine the target and context vectors, for example by adding them. The resulting embedding reflects global co-occurrence structure rather than a single prediction event.
Exercise
Why does GloVe use log(Xij) instead of Xij directly?
Show answer
The logarithm compresses large counts, so very frequent word pairs do not overwhelm the learning objective.