Skip to main content

Subsection 1.3 Learning Word Embeddings

Language models have an advantage over many other machine learning models: they can be trained on the large amounts of text available from sources like books, websites, and social media. Starting from that large pile of data, the first task is to figure out an embedding for each word.
This section focuses on how word embeddings are learned by the word2vec model.

Subsubsection 1.3.1 Generating Training Data

When children are learning to read, they often learn the meaning of a word by seeing it in context. A new reader might not understand the word β€œbank” (the side of a river), but in the sentence β€œThe children played on the bank of the river."”, the surrounding words provide clues to its meaning. Language models can use a similar approach to learn the meaning of words from their context.
"You shall know a word by the company it keeps" J.R. Firth
To learn from a piece of text, we must turn it into a series of simple examples the model can use for training. Training examples can be generated in three steps:
  1. Collect a large text dataset, such as Wikipedia articles. Clean it up to remove formatting, capitalization, and punctuation.
  2. Move a window of a fixed size, such as five words, across the text.
  3. Use the sliding window to generate training samples for the model.
Wikipedia articles about Hyperion Cantos, Dune, and The Matrix are converted to text. A highlighted window over the opening words of the first article slides to the right to collect training examples.
As the window moves across the text, it generates examples for training a model. As an example, we will consider processing the sentence β€œTheir pet dog slept on the couch.” Initially, the context window covers the first five words of the sentence. We will use those five words to generate training examples for the model to learn.
In the sentence Their pet dog slept on the couch, a five-word context window covers their pet dog slept on, with dog highlighted as the active center word.
There are many approaches to generate examples from a sliding window. The one we will focus on is the skipgram model. In it, the task is to use the active word (center one) to predict the four context words (the two immediate neighbors on each side). Based on our sentence, we should learn to predict that β€œdog” is associated with the words β€œtheir”, β€œpet”, β€œslept”, and β€œon”. These four pairs of input and output words form the first training samples:
Table 1.10. Training examples from the initial context position
Input Word Output Word
dog their
dog pet
dog slept
dog on
These samples indicate that when the model sees β€œdog”, it should be able to predict the words β€œtheir”, β€œpet”, β€œslept”, and β€œon”.
We then slide the window to the next position. Now β€œslept” is the active word and we want to learn to predict β€œpet”, β€œdog”, β€œon”, and β€œthe” from it.
The context window moves one word right to cover pet dog slept on the, with slept highlighted as the active center word. Their and couch are outside the window.
This generates the next four examples:
Table 1.11. Training examples from the first two context positions
Input Word Output Word
dog their
dog pet
dog slept
dog on
slept pet
slept dog
slept on
slept the
Each time we slide the window, we generate four new training examples. Eventually, we might process the sentence β€œOn a farm, a dog might help herd sheep.” In this sentence, the word β€œdog” appears in a context that includes β€œfarm”, β€œa”, β€œmight”, and β€œhelp”. These new training examples do not replace the old ones for dog, instead they add to the existing set of examples.
Table 1.12. Training examples including a new β€œdog” sentence
Input Word Output Word
dog their
dog pet
dog slept
dog on
dog farm
dog a
dog might
dog help
slept pet
... ...
It is even possible that we end up with duplicate entries in our training data. That is OK. Duplicate entries like dog:pet and dog:pet occur if those words are often used in the same context. That relationship is part of what we want to capture in our word embeddings. Having multiple training examples will encourage the model to learn that particular relationship extra strongly.
We have focused on a total window length of 5 to keep the examples manageable. Real implementations will generally use larger window sizes, like 21 total words (the target word plus 10 words on each side). Larger windows will capture more context for the center word, but may also introduce more noise into the training data and will likely require more computational resources to train.

Subsubsection 1.3.2 Learning from the Data

The learning process relies on a simple neural network. On both the input and output sides, we have a list of all the words in the vocabulary. In between is a single hidden layer of neurons. That size of that layer determines the number of values in the embedding space.
Here is what the model might look like if we were training on a small sample of text that only used 17 words and were trying to build word embeddings that consisted of 3 values:
A neural network connects 17 input words through three hidden neurons to 17 output words. Dog is active, its three input weights are labeled, and the initial output activations are scattered across unrelated words.

Note 1.13.

A real-world implementation of word2vec would involve a much larger vocabulary (thousands of words) and more dimensions (hundreds).
Training happens by activating one of the input neurons and allowing the signal to propagate through the network. The image above shows what we might get if we initially activate the word β€œdog”, with brighter red indicating higher activation in the outputs.
This initial output does not match our training data. Our training examples include dog:their , dog:pet, dog:slept, and dog:on. So the algorithm adjusts the weights that connect the input to the hidden layer and the hidden layer to the output layer. These adjustments will attempt to reduce the value of incorrect associations like dog:couch while increasing the value of correct associations like dog:on.
One training iteration won’t produce perfect results, but if we keep presenting the same examples repeatedly, the model will gradually improve. Eventually, it might learn to produce output that matches the training data:
With dog active in the same network, training strengthens the output activations for on, pet, slept, and their, while the other outputs remain weak.
As the model gets good at reproducing the training data, learning will slow down. The weights of the connections will settle into stable values.
Of course, that is likely not the only sentence in which the word β€œdog” appears. Perhaps we have another sentence like β€œOn a farm a dog might help herd sheep.” In that sentence, the word β€œdog” is associated with β€œfarm”, β€œa”, β€œmight”, and β€œhelp”. Right now, the model does not represent those associations.
If we train just on these new samples, it would learn to form those associations. But, it might also lose the ability to correctly predict the original associations. So, we need to keep feeding the model all the different β€œdog” test examples. Eventually, we would hope that it learns to represent all the things that β€œdog” is associated with:
With dog active, the network now activates a, farm, help, and might as well as on, pet, slept, and their, representing context words learned from both dog sentences.
Associations won’t be binary. As the model learns to represent all the associations for β€œdog”, it will learn that some associations are stronger (seem more often) than others. It will also be learning other associations, like the contexts for the word β€œcat” in β€œOur pet cat ignores us.” (cat:our, cat:pet, cat:ignores, cat:us):
With cat active, the network activates ignores, our, pet, and us. The three labeled weights from cat feed the same hidden neurons and output connections used for dog.
The connections from the hidden layer to the output layer are shared by all of the words in the vocabulary. This means that as the model learns to represent β€œcat”, that representation must be built in a way that also accommodates the representation of β€œdog”. We would expect the model to see lots of training samples that link β€œcat” and β€œdog” to similar contexts, like β€œpet”. For β€œpet” to appear in the output for both β€œcat” and β€œdog” inputs, the model will be forced to use similar weights for at least some of the connections from those two words to the hidden layer and from the hidden layer to β€œpet” in the output layer.
Although the weights connecting the hidden layer to the output layer are shared by all the words in the vocabulary, each word has a unique set of weights for its connections to the hidden layer. These are labeled in the diagrams above like w2,1 which would indicate the weight from the second word to the first hidden node. The β€œcat” weights are w2,1, w2,2, and w2,3 as the all link word two to a different hidden node. Because the β€œdog” input is word 4, it’s weigths are w4,1, w4,2, and w4,3.
These unique weights are what the model uses to represent each word in the embedding space. After training is complete, they can be extracted and put in a table that looks like this:
Input weight matrix with rows for a, cat, couch, dog, and farm, followed by an ellipsis. Each row has three weights. The dog row highlights a low first weight, high second weight, and medium third weight.
Note that each row represents a word in the vocabulary (though only the first 5 rows are shown). Each row has 3 values, corresponding to the weights from that word to the hidden layer. Rather than make up numbers for each cell, we will just illustrate those weights with colors. In the diagram above, we can see that β€œdog” has a low weight (light blue) for the first dimension, a high weight (dark blue) for the second dimension, and a medium weight for the third dimension.
If we colored all of the weights, the final result might look like this:
Three-column embedding heatmap for a, cat, couch, dog, and farm. Cat and dog share a dark second cell, indicating a high weight in the second dimension; the other words have lighter second cells.
As with the β€œking”/β€œqueen” example, we should not assume that any dimension has a particular meaning. But we likely can find patterns in the way the weights are distributed that tell us something about the semantic relationships between the words. In the made up example above, it appears that dimension 2 must capture something essential about β€œcat” and β€œdog” that is not as true of the other words. Maybe the concept of β€œanimal”? However, that same dimension will also be important for other words and may have a different interpretation in the context of those words. So we should be careful about ascribing too specific a meaning to any single dimension.
The other set of weights that were learned, which connect the hidden layer to the output layer, are generally discarded after training is complete. They are essential to help the model learn representations of the words, but do not tend to contain as much meaningful information about each word as the input weights do.