Sub topic 5
word2vec: Learning Embeddings by Prediction
Prerequisites and the main idea
This chapter assumes you know basic Python and NumPy, vectors, dot products, norms, conditional probability, softmax, and gradient descent. It also assumes you can split text into tokens.
word2vec learns a vector for each word by solving a prediction task. The model sees a word and nearby words, then adjusts vectors so that words used in similar contexts receive similar representations. This follows the distributional hypothesis: a word's meaning can be inferred from the company it keeps.
A context window is the nearby region around a target word. With a window size of 2, the sentence
the cat sat on the mat
creates pairs such as (cat, the), (cat, sat), (sat, cat), and (sat, on). These pairs are the training evidence.
Two word2vec architectures
Skip-gram
Skip-gram uses a target word to predict each nearby context word. For the pair (cat, sat), the input is cat and the desired output is sat.
For a target vector \(vw\) and a context vector \(uc\), the model scores their relationship with a dot product:
\text{score}(w,c)=u_c^\mathsf{T}v_wA softmax converts scores for all vocabulary words into probabilities:
P(c\mid w)=\frac{\exp(u_c^\mathsf{T}v_w)}
{\sum_{c'}\exp(u_{c'}^\mathsf{T}v_w)}Training increases the probability of the actual context word. After training, the input vectors are commonly used as the word embeddings.
CBOW
Continuous bag of words, or CBOW, reverses the task. It uses nearby context words to predict the missing target. The context vectors are usually averaged or summed before prediction.
For example, from the cat ___ on the mat, CBOW predicts sat. CBOW is often faster and works well for frequent words. Skip-gram can represent less frequent words better because it creates several prediction tasks from one target.
A tiny training task
The following code shows how a window creates skip-gram pairs. It does not train vectors yet, but it makes the learning objective concrete.
sentence = ["the", "cat", "sat", "on", "the", "mat"]
window = 1
pairs = []
for i, target in enumerate(sentence):
start = max(0, i - window)
stop = min(len(sentence), i + window + 1)
for j in range(start, stop):
if i != j:
pairs.append((target, sentence[j]))
print(pairs)The full softmax must compare the target with every vocabulary word. That becomes expensive for a large vocabulary. Negative sampling replaces this calculation with a few binary comparisons, which is the next step in the training process.
Exercise
In skip-gram, what prediction is made for the pair (cat, sat)?
Show answer
The model takes cat as the input target word and predicts sat as a nearby context word.