What is the concept of negative-sampling in word2vec?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Word2Vec, a popular model introduced by Mikolov et al., revolutionized the way word embeddings are created by representing words in continuous vector space. This model, particularly through the negative-sampling technique, efficiently predicts words based on their context within a corpus. Understanding negative sampling requires delving into the functioning of Word2Vec and the challenge it seeks to address.
Background: Word2Vec Overview
Word2Vec operates in two main architectures:
- Continuous Bag-of-Words (CBOW): Predicts the current word given its surrounding context words within a window.
- Skip-Gram: Predicts surrounding context words for a given target word.
Both methods optimize the word vectors by enhancing the probability of predicting actual context words correctly. However, they handle potentially massive outputs, as the softmax function used involves computing probabilities for all words in the vocabulary, which can be computationally expensive. Negative sampling provides a workaround to this problem.
The Challenge of the Softmax Function
In its unsimplified form, the optimization objective for models using the softmax function involves computing probabilities for the entire vocabulary:
Here, $v_{w_I}$ and $v'_{w_O}$ are input and output vectors for the input and output words respectively, and is the total vocabulary size. This calculation is computationally heavy, especially if the vocabulary V is extensive.
Negative Sampling Simplified
Negative sampling addresses the softmax computation challenge by narrowing the focus only to a few negative samples rather than the whole vocabulary. The idea is to optimize a simplified objective: distinguish a set of context word pairs from randomly sampled negative ones. This involves the following steps:
- Select Positive Pairs: Use actual word-context pairs (target word and context word ) from the corpus.
- Sample Negative Pairs: Randomly select a few negative samples, which are words that do not appear in the same context as the target word. The number of negative samples, typically set by the user, is a tuning parameter.
- Define the Loss Function: The goal is to maximize the objective function:In this formulation:
- is the sigmoid function.
- is the output vector of a negative sample.
- is the number of negative samples. This loss function contrasts the positive example score with the scores of negative samples, encouraging the model to distinguish actual context pairs from random ones.
Example Application
Consider a simple example with the sentence: "The cat sat on the mat". In this case:
- Positive Pair: ('cat', 'sat')
- Negative Samples: ('dog', 'run', 'blue') — as they do not typically appear in similar contexts in the given dataset.
By focusing the optimization on this small subset of scores, the model efficiently updates word vectors, pushing positive pairs closer in space, while moving randomly sampled negative pairs apart.
Advantages of Negative Sampling
- Efficiency: Reduces computational complexity significantly, particularly advantageous for handling large corpora.
- Scalability: Allows Word2Vec to scale seamlessly to handle vast vocabulary sizes.
- Simplicity: Conceptually straightforward with easy-to-compute gradients for updates during training.
Key Considerations in Negative Sampling
- Choice of Negative Samples: Influences model quality. Typically, negative samples are chosen with a distribution reflecting word frequency, such as by the power law distribution
P(w)∝U(w)^{3/4}whereU(w)is the unigram distribution. - Number of Negative Samples: A hyperparameter that might require tuning. Common choices are 5-20 per positive sample.
- Implementation: Especially valuable in neural language models where real-time processing is paramount.
Summary
| Concept | Details |
| Objective | Maximize probability of genuine word-context pairs while minimizing chances of predicting randomly paired words. |
| Optimization Problem | Large vocabulary makes full softmax computationally prohibitive. |
| Negative Sampling | Alleviates expensive computation by sampling a few 'negative' examples. |
| Objective Simplification | Converts multi-class prediction into binary classification. |
| Hyperparameters | Number of negative samples (commonly 5-20). |
| Efficiency | Highly efficient - only affects a few vectors per update. |
| Impact | Produced remarkably capable embeddings powering applications in NLP. |
Negative sampling is a cornerstone technique within Word2Vec that enhances its reliability and applicability for natural language processing tasks, underscoring its importance in the broader field of machine learning.
Related reading
- What is the difference between an Embedding Layer and a Dense Layer?
- what is the difference between bigram and unigram text features extraction
- What is the difference between keras.tokenize.text_to_sequences and word embeddings
- What is the good metric to evaluate NER model trained in Spacy
- What is the correct way to create representative dataset for TFliteconverter?
- What is the correct way to iterate over an indefinitely repeated tf.data Dataset in Tensorflow 2.0
- What is the network structure inside a Tensorflow Embedding Layer?
- What is the preferred ratio between the vocabulary size and embedding dimension?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.