Implement the Word2Vec as taught in class. Use a span length of 5 words on each side (total window length 11), 50 dimensions per embeddings, 0.01 learning rate, 15 negative samples per target word, and 500_000 number of iterations or trainig updates, as already set default in the starter code provided.
While calculating the loss explicitly is not needed to find gradient updates, we require you to calculate it so we can log it every 10K steps (code already provided - do not change). This will help track the loss as it goes down over training steps.
Hint: Do not try to find real negatives for a given context, instead randomly sample 15 words from the vocabulary to use as negative samples, and given the size of the vocabulary, it is very unlikely to include a word among the 11 context words.
Updated Hint: Also optionally do not try to find samples without replacement. You can use np.random.randint to instead sample with replacement, which is much more efficient hence brings down training time.
Help me do this
Assistant
Certainly! Let's break down the steps you need to implement Word2Vec with negative sampling, and I'll guide you through the process without providing the full code. This way, you'll understand each component and be able to implement it yourself.
Overview of the Skip-Gram Model with Negative Sampling
In the Skip-Gram model, the goal is to predict context words given a target word. With negative sampling, instead of updating all weights, we focus on a small number of positive and negative samples, which makes training more efficient.
Key Components to Implement
Initialization
Initialize the word embeddings (input vectors) and the context embeddings (output vectors) with small random values.
Typically, you have two embedding matrices:
input_vectors: shape (vocab_size, embedding_dim)
output_vectors: shape (vocab_size, embedding_dim)
Generating Training Samples
For each word in your corpus:
Use a window size of 5 words on each side (total window size of 11).
For the current word (center word), collect all context words within the window.
For each positive pair, sample 15 negative words from your vocabulary.
You can use np.random.randint(0, vocab_size, size=15) to sample indices with replacement.
Computing the Loss and Gradients
For each positive pair and its negative samples:
Positive sample loss: Encourage the model to predict high similarity between the center word and the context word.
[
\text{Positive Loss} = -\log(\sigma(u_c^\top v_t))
]
Negative samples loss: Encourage the model to predict low similarity between the center word and negative samples.
[
\text{Negative Loss} = -\sum_{n=1}^{K} \log(\sigma(-u_n^\top v_t))
]
Total loss for the sample is the sum of positive and negative losses.
Compute gradients with respect to:
v_t (embedding of the center word)
u_c (embedding of the context word)
u_n (embeddings of the negative samples)
Updating Embeddings
Update the embeddings using the gradients and the learning rate (0.01).
Ensure you're updating both the input and output embeddings appropriately.
Logging the Loss
Accumulate the loss for every 10,000 steps and log it.
Do not change the provided code for logging.
Step-by-Step Implementation Guide
1. Initialize Embeddings
python
import numpy as np
vocab_size = len(vocabulary) # Assuming you have a list of all unique words
embedding_dim = 50
input_vectors = np.random.uniform(-0.5 / embedding_dim, 0.5 / embedding_dim, (vocab_size, embedding_dim))
output_vectors = np.random.uniform(-0.5 / embedding_dim, 0.5 / embedding_dim, (vocab_size, embedding_dim))
2. Function to Generate Training Batches
Create a function that iterates over your corpus and yields center words along with their context words.
python
def generate_batches(corpus, window_size):
for idx, center_word in enumerate(corpus):
context = []
# Compute the window boundaries
start = max(0, idx - window_size)
end = min(len(corpus), idx + window_size + 1)
# Collect context words
for i in range(start, end):
if i != idx:
context.append(corpus[i])
yield center_word, context
3. Negative Sampling Function
python
def get_negative_samples(vocab_size, num_samples):
# Randomly sample indices from 0 to vocab_size - 1
return np.random.randint(0, vocab_size, size=num_samples)
4. Sigmoid Function
Define the sigmoid function, which will be used in computing the loss and gradients.
python
def sigmoid(x):
return 1 / (1 + np.exp(-x))
5. Training Loop
Implement the main training loop.
python
learning_rate = 0.01
window_size = 5
num_negative_samples = 15
num_iterations = 500_000
loss = 0
for step in range(num_iterations):
# Sample a center word and its context
center_idx, context_indices = your_batch_generation_logic()
# Positive sample
v_t = input_vectors[center_idx]
for context_idx in context_indices:
u_c = output_vectors[context_idx]
# Compute positive loss and gradients
score = np.dot(u_c, v_t)
sig_score = sigmoid(score)
pos_loss = -np.log(sig_score)
loss += pos_loss
# Gradients
grad_pos = learning_rate * (sig_score - 1)
# Update embeddings
input_vectors[center_idx] -= grad_pos * u_c
output_vectors[context_idx] -= grad_pos * v_t
# Negative samples
neg_sample_indices = get_negative_samples(vocab_size, num_negative_samples)
for neg_sample_idx in neg_sample_indices:
u_n = output_vectors[neg_sample_idx]
score_neg = np.dot(u_n, v_t)
sig_score_neg = sigmoid(-score_neg)
neg_loss = -np.log(sig_score_neg)
loss += neg_loss
# Gradients
grad_neg = learning_rate * (sig_score_neg - 1)
# Update embeddings
input_vectors[center_idx] -= grad_neg * u_n
output_vectors[neg_sample_idx] -= grad_neg * v_t
# Every 10,000 steps, log the loss
if step % 10_000 == 0 and step > 0:
print(f"Loss after {step} steps: {loss/10_000}")
loss = 0 # Reset the loss for the next interval
6. Important Notes
Vectorized Operations: For efficiency, consider vectorizing your computations where possible.
Handling Indexing: Ensure that your word indexing (word to index mapping) is consistent across your corpus and embeddings.
Normalization: Optionally, normalize your embeddings periodically to prevent them from growing too large.
Understanding Gradient Computations
The gradients for updating embeddings are derived from the logistic loss function.
Note: Since we are summing over all negative samples, ensure you accumulate the gradients accordingly.
Tips for Efficiency
Sampling with Replacement: Using np.random.randint as suggested allows you to sample negative words quickly without worrying about duplicates.
Avoiding Loops: Where possible, replace explicit for loops with numpy array operations.
Batch Updates: You might consider batching several samples together to leverage matrix operations.
Putting It All Together
By following the steps above and ensuring that you correctly implement the loss computations and gradient updates, you should be able to train your Word2Vec model as specified.
Remember to:
Keep track of the indices of words and their corresponding embeddings.
Update both the input and output embeddings.
Monitor the loss to ensure that it's decreasing over time.
Additional Resources
Efficient Estimation of Word Representations in Vector Space by Mikolov et al. (2013): This is the original paper introducing negative sampling.
Stanford CS224n lecture notes and videos provide an excellent explanation of Word2Vec and negative sampling.
Final Thoughts
Implementing Word2Vec from scratch is a valuable learning experience. By carefully following the mathematical formulations and translating them into code, you'll gain a deep understanding of how word embeddings work.
If you encounter specific issues or have questions about particular parts of your implementation, feel free to ask, and I'll be happy to help clarify those points!