Sub topic 12
Subsampling frequent words
This chapter assumes you know the skip-gram training setup from the earlier chapters: (word, context) pairs drawn from a window, and the idea that training is a loop over a corpus. It covers the one word2vec step that changes the corpus before the pairs are built.
The problem: a few words dominate the pairs
Word frequencies in natural text follow a steep power law. In English, "the", "of", "and" and "a" can make up a large share of all tokens. In skip-gram, every token generates up to 2 * window training pairs. Frequent words therefore dominate the training set, and this causes two problems.
- Wasted updates. The pair ("france", "the") says almost nothing about "france". After a few thousand examples, the vector for "the" barely changes, but training keeps spending time on it.
- Noisy signal for content words. Informative pairs such as ("france", "paris") are a small fraction of the data, so the model sees them less often than it needs to.
Subsampling randomly drops tokens from the corpus before pairs are formed, and it drops frequent tokens much more often than rare ones.
The formulas
Let f(w) be the fraction of corpus tokens that are word w, and let t be a threshold.
The original paper (Mikolov et al., 2013) discards each occurrence of w with probability:
P_discard(w) = 1 - sqrt(t / f(w))So the keep probability is sqrt(t / f(w)), capped at 1. The paper suggests t around 1e-5.
The released C code and gensim use a slightly different formula for the keep probability:
P_keep(w) = (sqrt(f(w) / t) + 1) * t / f(w)This is also capped at 1. It is gentler than the paper's version for the same t. Words are kept with certainty up to roughly 2.618 * t, because that is where the expression drops to 1. The default threshold in gensim (sample=1e-3) is much larger than the paper's 1e-5, so the default removes less.
The following script computes both versions:
import math
def keep_paper(f, t):
return min(1.0, math.sqrt(t / f))
def keep_word2vec(f, t):
return min(1.0, (math.sqrt(f / t) + 1.0) * t / f)
freqs = {"the": 0.05, "of": 0.01, "model": 0.002, "paris": 0.0001}
print(f"{'word':<8}{'f':>10}{'paper t=1e-5':>16}{'w2v t=1e-3':>14}")
for word, f in freqs.items():
print(f"{word:<8}{f:>10.4f}{keep_paper(f, 1e-5):>16.4f}{keep_word2vec(f, 1e-3):>14.4f}")Approximate values from these formulas:
| Word frequency `f` | Paper keep prob. (`t = 1e-5`) | word2vec/gensim keep prob. (`t = 1e-3`) |
|---|---|---|
| 0.05 | 0.014 | 0.161 |
| 0.01 | 0.032 | 0.416 |
| 0.002 | 0.071 | 1.000 |
| 0.0001 | 0.316 | 1.000 |
With the paper's threshold, even a word with f = 0.0001 loses most of its occurrences. With the gensim default, only words above about 0.26% of the corpus are touched.
Applying it to a corpus
The process is a per-token coin flip. The following code applies it to one sentence, using the gensim-style formula:
import math
import random
from collections import Counter
def subsample(sentences, t=1e-3, seed=0):
rng = random.Random(seed)
counts = Counter(w for s in sentences for w in s)
total = sum(counts.values())
def keep(w):
f = counts[w] / total
return min(1.0, (math.sqrt(f / t) + 1.0) * t / f)
return [[w for w in s if rng.random() < keep(w)] for s in sentences]
corpus = [["the", "cat", "sits", "on", "the", "mat"]] * 200
print(subsample(corpus, t=1e-2)[0])Every call draws new random numbers. A real implementation does this again on each epoch, so a given "the" is dropped in one pass and kept in another.
Where it fits in the pipeline
The order matters. Tokens are removed first, and the window then slides over the shortened sentence. This has a useful side effect: with the same window setting, the model sees words that were farther apart in the original text. In "the cat sat on the mat", dropping both "the" tokens lets "cat" and "mat" fall within a window of 2 of each other and share a pair, though they were separated in the original.
What subsampling changes
- Speed. Fewer tokens means fewer pairs per epoch, so each epoch is faster.
- Vector quality. The word2vec paper reports faster training and better vectors for rarer words. The gain is usually largest on large corpora.
- Effective context. As noted above, windows reach farther in the original text. Frequent function words stop acting as filler in the context.
- It is not a stop-word list. Frequent words are not deleted for good. They are downweighted statistically, and "the" still appears sometimes and still gets a vector.
Gotchas
- Do not confuse it with the negative sampling distribution. Negative samples are drawn from the unigram distribution raised to the power 0.75. That also suppresses frequent words, but it works on the noise side of the loss and is unrelated to
sample. - Tiny corpora. On a corpus of a few sentences, every word has a large
f. Withsample=1e-3, most tokens are dropped and training may see almost nothing. For toy examples, setsample=0. - Interaction with
min_count. gensim builds the vocabulary and counts frequencies first, and subsampling happens afterward. Frequencies reflect the full corpus, not the pruned one. - GloVe has no equivalent step. GloVe builds its counts over the whole corpus. It handles frequent words through the weighting function
f(X_ij), which caps the influence of large counts, not through random token removal. - Results vary by seed. Because tokens are dropped randomly, two runs with different seeds give slightly different vectors. Use
seedandworkers=1if you need reproducibility.
Setting it in gensim
In gensim, the sample parameter holds t. The default is 1e-3, and the documentation suggests a useful range of (0, 1e-5). Setting sample=0 turns it off.
from gensim.models import Word2Vec
sentences = [
["the", "cat", "sits", "on", "the", "mat"],
["the", "dog", "sits", "on", "the", "rug"],
["the", "cat", "chases", "the", "mouse"],
]
model = Word2Vec(
sentences=sentences,
vector_size=50,
window=2,
min_count=1,
sg=1,
negative=5,
sample=0, # disabled: the corpus is far too small for subsampling
epochs=50,
workers=1,
seed=1,
)
print(model.wv["cat"].shape)On a real corpus, start with the default and try values between 1e-3 and 1e-5. Smaller values are more aggressive. Evaluate on a similarity or analogy benchmark, as described in the evaluation chapter, instead of guessing.
Exercise
A corpus has 1,000,000 tokens, and "the" appears 50,000 times. Using the gensim/word2vec C formula with sample=1e-3, what is the keep probability of "the"? Is "dog", which appears 500 times, affected?
Show answer
For "the", f = 0.05, so P_keep = (sqrt(0.05/0.001) + 1) 0.001/0.05 = (7.071 + 1) 0.02 ≈ 0.161. About 84% of occurrences of "the" are dropped in each epoch. For "dog", f = 0.0005, which is below the 2.618 * t ≈ 0.0026 point, so the formula gives a value above 1. It is capped at 1.0, so "dog" is never dropped.
Exercise
Why can subsampling make words that were far apart in the original sentence appear in the same training pair?
Show answer
Tokens are removed before the context window slides over the sentence. Removing frequent words between two content words shortens the distance between them in the sentence the window sees, so they can fall inside the window and form a pair.