Implement Word2Vec (skip-gram) training from scratch
Written by the mlprep team · Updated
Implement Word2Vec skip-gram with negative sampling from scratch in NumPy. Explain what each part is doing, why negative sampling is necessary, and what the resulting embeddings capture.
Word2Vec learns word embeddings by training a simple task: given a word, predict its neighbors. The magic is that the weight matrix learned during training becomes the embedding — a dense vector that captures semantic meaning.
Skip-gram objective#
For each word w in the corpus, maximize the probability of nearby context words c:
maximize Σ log P(c | w) for all (w, c) pairs within a window
With full softmax: P(c | w) = exp(v_c · v_w) / Σ_all_words exp(v_j · v_w)
The denominator sums over the entire vocabulary (100K+ words) — too expensive.
Negative sampling approximation#
Instead of normalizing over all words, train a binary classifier:
- Positive: (w, c) pairs that actually appear together → predict 1
- Negative: (w, random_word) pairs that don't appear together → predict 0
For each positive pair, sample k negative pairs (typically k=5-15).
Implementation#
import numpy as np
from collections import Counter
class Word2Vec:
def __init__(self, vocab_size, embedding_dim=100, learning_rate=0.025,
window=5, n_negatives=5):
self.vocab_size = vocab_size
self.embedding_dim = embedding_dim
self.lr = learning_rate
self.window = window
self.n_negatives = n_negatives
# Two embedding matrices: center words and context words
self.W_center = np.random.randn(vocab_size, embedding_dim) * 0.01
self.W_context = np.random.randn(vocab_size, embedding_dim) * 0.01
# Negative sampling distribution: P(w) ∝ freq(w)^0.75
self.neg_dist = None
def build_neg_distribution(self, word_counts):
freq = np.array([word_counts.get(i, 0) for i in range(self.vocab_size)])
freq_075 = freq ** 0.75
self.neg_dist = freq_075 / freq_075.sum()
def train_pair(self, center_idx, context_idx):
# Get embeddings
v_center = self.W_center[center_idx] # (embedding_dim,)
v_context = self.W_context[context_idx] # (embedding_dim,)
# Positive example: sigmoid(v_center · v_context) should be high
score = np.dot(v_center, v_context)
sigmoid_pos = self._sigmoid(score)
# Gradient for positive pair
# Loss = -log(sigmoid(v_c · v_w))
# d/dv_center = (sigmoid - 1) * v_context
# d/dv_context = (sigmoid - 1) * v_center
grad_center = (sigmoid_pos - 1) * v_context
grad_context = (sigmoid_pos - 1) * v_center
# Negative examples
neg_indices = np.random.choice(
self.vocab_size, size=self.n_negatives, p=self.neg_dist
)
for neg_idx in neg_indices:
v_neg = self.W_context[neg_idx]
score_neg = np.dot(v_center, v_neg)
sigmoid_neg = self._sigmoid(score_neg)
# Loss += -log(sigmoid(-v_center · v_neg))
# d/dv_center += sigmoid_neg * v_neg
# d/dv_neg = sigmoid_neg * v_center
grad_center += sigmoid_neg * v_neg
self.W_context[neg_idx] -= self.lr * (sigmoid_neg * v_center)
# Update embeddings
self.W_center[center_idx] -= self.lr * grad_center
self.W_context[context_idx] -= self.lr * grad_context
def train_corpus(self, token_ids, n_epochs=5):
for epoch in range(n_epochs):
for i, center_id in enumerate(token_ids):
# Dynamic window: random size from 1 to self.window
actual_window = np.random.randint(1, self.window + 1)
for j in range(max(0, i - actual_window),
min(len(token_ids), i + actual_window + 1)):
if j == i:
continue
self.train_pair(center_id, token_ids[j])
# Decay learning rate
self.lr *= 0.9
def get_embedding(self, word_idx):
return self.W_center[word_idx]
def most_similar(self, word_idx, top_k=10):
v = self.W_center[word_idx]
# Cosine similarity to all other words
norms = np.linalg.norm(self.W_center, axis=1)
similarities = (self.W_center @ v) / (norms * np.linalg.norm(v) + 1e-8)
top_indices = np.argsort(similarities)[::-1][1:top_k+1]
return top_indices, similarities[top_indices]
def _sigmoid(self, x):
return 1.0 / (1.0 + np.exp(-np.clip(x, -15, 15)))Why two embedding matrices (W_center and W_context)?#
The center word and context word play different roles in the objective. Using separate matrices prevents the degenerate solution where all embeddings collapse to the same point (which would maximize dot products for all pairs equally).
In practice, the final embedding is often W_center alone, or (W_center + W_context) / 2.
Why P(w) ∝ freq^0.75 for negative sampling?#
Using the raw frequency distribution means you almost always sample "the", "a", "is" as negatives — common words that aren't informative. The 0.75 power sublinearly dampens frequent words and boosts rare words, giving more informative negatives:
Raw freq: "the"=0.06, "cat"=0.0001, "quantum"=0.00001
^0.75: "the"=0.03, "cat"=0.0003, "quantum"=0.00006
"cat" and "quantum" get relatively more negative sampling, which helps learn their embeddings.
What the embeddings capture#
The objective forces words that appear in similar contexts to have similar embeddings. "king" and "queen" appear with "royal", "throne", "rule" → similar embeddings. The famous analogy property (king - man + woman ≈ queen) emerges because the vector directions encode semantic relationships.
The embedding space learns:
- Semantic similarity (cosine distance)
- Analogical relationships (vector arithmetic)
- Syntactic patterns (plurals, tenses cluster together)
Interview red flags#
- Computing a full softmax over the vocabulary for every training pair, which is the cost negative sampling exists to avoid.
- Using one shared embedding matrix for center and context words without addressing why two are standard.
- Sampling negatives uniformly or by raw frequency instead of the unigram distribution raised to the 0.75 power.
- Skipping frequent-word subsampling, so "the" and "of" dominate training.
Your implementation processes one word pair at a time. In practice, Word2Vec trains on billions of tokens. How would you make this significantly faster without changing the algorithm?
Several optimizations make Word2Vec practical at scale:
1. Batch the negative sampling#
Instead of sampling negatives per pair, pre-sample a large table of negatives and index into it. This avoids the expensive np.random.choice call per training pair:
# Pre-compute a large table of negative samples
neg_table_size = 100_000_000
neg_table = np.random.choice(
vocab_size, size=neg_table_size, p=self.neg_dist
)
neg_table_idx = 0
# During training, just slice from the table
neg_indices = neg_table[neg_table_idx:neg_table_idx + self.n_negatives]
neg_table_idx += self.n_negatives2. Subsampling frequent words#
Common words ("the", "is", "a") add little information but dominate training time. Randomly discard them with probability proportional to their frequency:
def should_discard(word_freq, threshold=1e-3):
prob_keep = np.sqrt(threshold / word_freq) + threshold / word_freq
return np.random.random() > prob_keepWords appearing more than 0.1% of the time get discarded frequently. This speeds training 2-5x and actually improves embedding quality (less noise from uninformative pairs).
3. Vectorize the inner loop with matrix operations#
Process multiple positive pairs simultaneously:
# Batch of center and context indices
center_vecs = self.W_center[center_batch] # (batch, dim)
context_vecs = self.W_context[context_batch] # (batch, dim)
neg_vecs = self.W_context[neg_batch] # (batch, n_neg, dim)
# Positive scores
pos_scores = np.sum(center_vecs * context_vecs, axis=1)
# Negative scores
neg_scores = np.einsum('bd,bnd->bn', center_vecs, neg_vecs)4. Hogwild! asynchronous training#
The original Word2Vec uses multiple threads updating the embedding matrix simultaneously without locks. Because updates are sparse (only a few rows change per training pair) and the embedding dimension is large, conflicts are rare and don't hurt convergence. This gives near-linear speedup with thread count.
5. Use C/Cython#
The original Word2Vec implementation (gensim) uses C for the inner loop, achieving 100K+ word pairs per second per thread. Python/NumPy overhead for per-pair processing is the bottleneck.
Combined speedup: these optimizations together make Word2Vec trainable on the entire English Wikipedia (2B tokens) in hours on a single machine.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Word2Vec skip-gram learns embeddings by predicting context words from center words. Negative sampling avoids the expensive full-vocabulary softmax by training a binary classifier (real context vs. random noise). Two embedding matrices prevent collapse. The ^0.75 power on sampling frequency boosts rare-word negatives for better learning. At scale: pre-sample negative tables, subsample frequent words, vectorize operations, and use lock-free parallel training (Hogwild!).
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- What's the relationship between Word2Vec and matrix factorization of the PMI (pointwise mutual information) matrix? What does this equivalence tell you?
- How would you evaluate whether your learned embeddings are good — what benchmarks and intrinsic/extrinsic evaluations would you use?
- Modern language models (BERT, GPT) produce contextual embeddings. What do they capture that Word2Vec cannot, and when would you still prefer Word2Vec?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions