References
- Paper: Distributed Representations of Words and Phrases and their Compositionality, Mikolov et al., 2013.
- Lecture: CS224N Lecture 1.
1. Motivation
1.1 Problem with Softmax
In standard Word2Vec, the conditional probability uses softmax:
The denominator, or partition function, has several problems:
- Computational complexity: It requires summing over the whole vocabulary , so the complexity is .
- Large vocabulary: Usually .
- Low optimization efficiency: Every update needs scores for all words.
1.2 Role of the Partition Function
从两个角度理解分母:
- Probability perspective: 归一化项, 保证概率和为 .
- Optimization perspective:
- 提高分子 , 即正样本相似度.
- 降低分母 , 即负样本相似度.
2. Negative Sampling Method
2.1 Core Idea
Note: Core idea
我们没必要遍历整个词汇表, 只需要对少量有代表性的词汇进行采样即可.
将多分类问题转化为多个二分类问题:
- 正样本: 真实的
(center, context)pair, label = . - 负样本: 随机采样的
(center, random)pair, label = .
2.2 New Loss Function
For center word and context word :
其中:
- is the sigmoid function.
- is the set of negative samples, usually .
2.3 Loss Interpretation
| Term | Formula | Goal |
|---|---|---|
| Positive sample | Make , so positive sample score is high | |
| Negative sample | Make , so negative sample score is low |
Equivalently, the negative sample term can be written as:
3. Negative Sampling Distribution
3.1 Sampling Strategy
Negative sample is sampled from distribution :
其中:
- is the frequency of word in the corpus.
- , with empirical recommendation .
3.2 Why Use ?
- : 按原始词频采样, 高频词如 “the” and “a” 被过度采样.
- : 均匀采样, 忽略词频信息.
- : 平滑词频分布, 既考虑词频又避免过度集中.
Example: suppose “the” appears 100 times and “cat” appears 1 time.
- Original ratio: .
- Smoothed ratio: .
4. Softmax vs Negative Sampling
| Full Softmax | Negative Sampling | |
|---|---|---|
| Computed logits | All words | 1 positive sample + negative samples |
| Complexity | , | |
| Loss | ||
| Normalization | Global normalization | No global normalization |
| Classification type | Multi-class classification | Multiple binary classifications |
4.1 Matrix Form
Full Softmax.
Negative Sampling.
5. Practical Suggestions
5.1 Hyperparameters
| Parameter | Suggested Value | Description |
|---|---|---|
| 5-20 | Use larger for small datasets and smaller for large datasets | |
| 0.75 | Empirically strong smoothing exponent |
5.2 Preprocessing
# Count word frequency
word_freq = Counter(all_tokens)
# Compute negative sampling probabilities
alpha = 0.75
freq_array = np.array([word_freq[w] for w in vocab])
neg_sampling_dist = (freq_array ** alpha) / (freq_array ** alpha).sum()