Skip to content
E
Educatum

Count based VS Prediction models for word embeddings

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 XijX_{ij}). 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 ∣V∣×∣V∣|V| \times |V| 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 ww and context word cc 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: PPMI(w,c)=max⁡ ⁣(0,  log⁡2P(w,c)P(w)P(c))\text{PPMI}(w, c) = \max\!\left(0,\; \log_2 \frac{P(w, c)}{P(w)P(c)}\right)
  • 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 ∑i,jf(Xij)(wi⊤w~j+bi+b~j−log⁡Xij)2\sum_{i,j} f(X_{ij})(w_i^\top \tilde{w}_j + b_i + \tilde{b}_j - \log X_{ij})^2 over observed co-occurrence counts XijX_{ij}.

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 ∣V∣|V|-dimensional rows into 300-dimensional vectors. GloVe fits directly to those global log⁡Xij\log X_{ij} ratios so vector differences capture linear analogies such as v⃗king−v⃗man+v⃗woman≈v⃗queen\vec{v}_{\text{king}} - \vec{v}_{\text{man}} + \vec{v}_{\text{woman}} \approx \vec{v}_{\text{queen}}. 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))
  • Cosine Similarity: Standard similarity metric u⊤v∥u∥∥v∥\frac{u^\top v}{\|u\|\|v\|} for comparing word embedding directions independently of vector norm.
  • Matrix Factorization Equivalence: Skip-gram with negative sampling (SGNS) implicitly factorizes the shifted PMI matrix PMI(w,c)−log⁡k\text{PMI}(w, c) - \log k (where kk is the number of negative samples), bridging prediction and count approaches.
  • Subword Embeddings (FastText): Extends Word2Vec by representing words as bags of character nn-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.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.