Count based VS Prediction models for word embeddings
Count-based embedding methods construct word vectors from global corpus co-occurrence statistics using weighting and factorization techniques such as PPMI, truncated SVD, and GloVe's log-bilinear regression. Prediction-based methods like Word2Vec (CBOW and Skip-gram) learn dense embeddings incrementally by predicting target or context words within local sliding windows, scaling cleanly to massive streaming corpora.
Study Card: Count-Based vs. Prediction-Based Word Embeddings
Direct Answer
Static word embeddings map words into dense vectors where geometric proximity reflects semantic and syntactic similarity. Count-based methods begin by aggregating global word-context co-occurrence statistics across the entire corpus—via Positive Pointwise Mutual Information (PPMI), truncated SVD / Latent Semantic Analysis (LSA), or GloVe (which trains a weighted log-bilinear regression directly on nonzero global co-occurrence counts ). Prediction-based methods, notably Word2Vec (CBOW and Skip-gram), train a shallow neural network on local sliding context windows to predict words from neighbors or vice versa. While count-based methods leverage global statistical summaries directly, prediction-based models stream over text in mini-batches without storing an explicit co-occurrence matrix, and Levy & Goldberg (2014) proved that Skip-gram with negative sampling implicitly factorizes a shifted PMI matrix—unifying both paradigms.
Key Terms
- Word Embeddings: Dense, low-dimensional vector representations of words that encode semantic and syntactic regularities.
- Co-occurrence Matrix: A matrix counting how frequently word and context word appear within a fixed window size across a corpus.
- PPMI (Positive Pointwise Mutual Information): Discounts ubiquitous uninformative words (like “the”) relative to chance co-occurrence:
- Word2Vec (CBOW / Skip-gram): A prediction-based algorithm using local context windows—CBOW predicts a target word from surrounding context, while Skip-gram predicts context words from a target word.
- GloVe (Global Vectors): A count-based global log-bilinear matrix factorization method minimizing over observed co-occurrence counts .
Example
Consider building embeddings from a news corpus. A pure count-based pipeline counts co-occurrences within a 5-word window, transforms raw counts with PPMI so rare informative associations stand out over stopwords, and applies truncated SVD to compress sparse -dimensional rows into 300-dimensional vectors. GloVe fits directly to those global ratios so vector differences capture linear analogies such as . Word2Vec Skip-gram achieves comparable analogy structure without materializing the full co-occurrence matrix by scanning windows sequentially with negative sampling.
Code Implementation
import re
import numpy as np
from gensim.models import Word2Vec
sentences = [
"the quick brown fox jumps over the lazy dog",
"the dog barked at the fox",
"the fox is quick and brown",
]
# Simple deterministic tokenization (no external tokenizer download required)
tokenized_sentences = [re.findall(r"\b\w+\b", s.lower()) for s in sentences]
vocab = sorted({word for sent in tokenized_sentences for word in sent})
word_to_idx = {w: i for i, w in enumerate(vocab)}
# 1. Count-Based Method: Sliding-window co-occurrence matrix + PPMI
def build_cooccurrence(tokens_list, w2i, window=2):
n = len(w2i)
counts = np.zeros((n, n), dtype=np.float64)
for tokens in tokens_list:
for i, target in enumerate(tokens):
t_idx = w2i[target]
start = max(0, i - window)
end = min(len(tokens), i + window + 1)
for j in range(start, end):
if i != j:
c_idx = w2i[tokens[j]]
counts[t_idx, c_idx] += 1.0
return counts
def compute_ppmi(counts):
total = counts.sum()
p_ij = counts / total
p_i = counts.sum(axis=1, keepdims=True) / total
p_j = counts.sum(axis=0, keepdims=True) / total
expected = p_i * p_j
ratio = np.divide(p_ij, expected, out=np.zeros_like(p_ij), where=(p_ij > 0) & (expected > 0))
pmi = np.log2(ratio, out=np.zeros_like(ratio), where=ratio > 0)
return np.maximum(0.0, pmi)
cooc = build_cooccurrence(tokenized_sentences, word_to_idx, window=2)
ppmi = compute_ppmi(cooc)
print("Sample Sliding-Window Co-occurrence Matrix shape:", cooc.shape)
print("Sample PPMI Matrix (rounded):")
print(np.round(ppmi[:5, :5], 2))
# 2. Prediction-Based Method: Word2Vec (Skip-gram, sg=1)
model_w2v = Word2Vec(
tokenized_sentences, vector_size=5, window=2, min_count=1, sg=1, seed=42
)
print("\nSample Word2Vec Embeddings:")
for word in model_w2v.wv.index_to_key[:5]:
print(word, np.round(model_w2v.wv[word], 3))
Related Concepts
- Cosine Similarity: Standard similarity metric for comparing word embedding directions independently of vector norm.
- Matrix Factorization Equivalence: Skip-gram with negative sampling (SGNS) implicitly factorizes the shifted PMI matrix (where is the number of negative samples), bridging prediction and count approaches.
- Subword Embeddings (FastText): Extends Word2Vec by representing words as bags of character -grams, enabling representations for rare or out-of-vocabulary words.
- Contextualized Representations (ELMo, BERT, LLMs): Static embeddings assign one vector per word type (failing on polysemy like “bank”), whereas Transformer hidden states generate dynamic token vectors conditioned on surrounding context.