Path: blob/master/2 - Natural Language Processing with Probabilistic Models/Week 4/C2W4_L5_Word Embeddings Step by Step.ipynb
65 views
Word Embeddings: Ungraded Practice Notebook
In this ungraded notebook, you'll try out all the individual techniques that you learned about in the lecture. Practicing on small examples will prepare you for the graded assignment, where you will combine the techniques in more advanced ways to create word embeddings from a real-life corpus.
This notebook is made of two main parts: data preparation, and the continuous bag-of-words (CBOW) model.
To get started, import and initialize all the libraries you will need.
Requirement already satisfied: emoji in /opt/conda/lib/python3.7/site-packages (0.5.4)
WARNING: You are using pip version 20.1; however, version 20.1.1 is available.
You should consider upgrading via the '/opt/conda/bin/python -m pip install --upgrade pip' command.
Data preparation
In the data preparation phase, starting with a corpus of text, you will:
Clean and tokenize the corpus.
Extract the pairs of context words and center word that will make up the training data set for the CBOW model. The context words are the features that will be fed into the model, and the center words are the target values that the model will learn to predict.
Create simple vector representations of the context words (features) and center words (targets) that can be used by the neural network of the CBOW model.
Cleaning and tokenization
To demonstrate the cleaning and tokenization process, consider a corpus that contains emojis and various punctuation signs.
First, replace all interrupting punctuation signs — such as commas and exclamation marks — with periods.
Next, use NLTK's tokenization engine to split the corpus into individual tokens.
Finally, as you saw in the lecture, get rid of numbers and punctuation other than periods, and convert all the remaining tokens to lowercase.
Note that the heart emoji is considered as a token just like any normal word.
Now let's streamline the cleaning and tokenization process by wrapping the previous steps in a function.
Apply this function to the corpus that you'll be working on in the rest of this notebook: "I am happy because I am learning"
Now try it out yourself with your own sentence.
Sliding window of words
Now that you have transformed the corpus into a list of clean tokens, you can slide a window of words across this list. For each window you can extract a center word and the context words.
The get_windows function in the next cell was introduced in the lecture.
The first argument of this function is a list of words (or tokens). The second argument, C, is the context half-size. Recall that for a given center word, the context words are made of C words to the left and C words to the right of the center word.
Here is how you can use this function to extract context words and center words from a list of tokens. These context and center words will make up the training set that you will use to train the CBOW model.
The first example of the training set is made of:
the context words "i", "am", "because", "i",
and the center word to be predicted: "happy".
Now try it out yourself. In the next cell, you can change both the sentence and the context half-size.
Transforming words into vectors for the training set
To finish preparing the training set, you need to transform the context words and center words into vectors.
Mapping words to indices and indices to words
The center words will be represented as one-hot vectors, and the vectors that represent context words are also based on one-hot vectors.
To create one-hot word vectors, you can start by mapping each unique word to a unique integer (or index). We have provided a helper function, get_dict, that creates a Python dictionary that maps words to integers and back.
Here's the dictionary that maps words to numeric indices.
You can use this dictionary to get the index of a word.
And conversely, here's the dictionary that maps indices to words.
Finally, get the length of either of these dictionaries to get the size of the vocabulary of your corpus, in other words the number of different words making up the corpus.
Getting one-hot word vectors
Recall from the lecture that you can easily convert an integer, , into a one-hot vector.
Consider the word "happy". First, retrieve its numeric index.
Now create a vector with the size of the vocabulary, and fill it with zeros.
You can confirm that the vector has the right size.
Next, replace the 0 of the -th element with a 1.
And you have your one-hot word vector.
You can now group all of these steps in a convenient function, which takes as parameters: a word to be encoded, a dictionary that maps words to indices, and the size of the vocabulary.
Check that it works as intended.
What is the word vector for "learning"?
Expected output:
Getting context word vectors
To create the vectors that represent context words, you will calculate the average of the one-hot vectors representing the individual words.
Let's start with a list of context words.
Using Python's list comprehension construct and the word_to_one_hot_vector function that you created in the previous section, you can create a list of one-hot vectors representing each of the context words.
And you can now simply get the average of these vectors using numpy's mean function, to get the vector representation of the context words.
Note the axis=0 parameter that tells mean to calculate the average of the rows (if you had wanted the average of the columns, you would have used axis=1).
Now create the context_words_to_vector function that takes in a list of context words, a word-to-index dictionary, and a vocabulary size, and outputs the vector representation of the context words.
And check that you obtain the same output as the manual approach above.
What is the vector representation of the context words "am happy i am"?
Expected output:
Building the training set
You can now combine the functions that you created in the previous sections, to build a training set for the CBOW model, starting from the following tokenized corpus.
To do this you need to use the sliding window function (get_windows) to extract the context words and center words, and you then convert these sets of words into a basic vector representation using word_to_one_hot_vector and context_words_to_vector.
In this practice notebook you'll be performing a single iteration of training using a single example, but in this week's assignment you'll train the CBOW model using several iterations and batches of example. Here is how you would use a Python generator function (remember the yield keyword from the lecture?) to make it easier to iterate over a set of examples.
The output of this function can be iterated on to get successive context word vectors and center word vectors, as demonstrated in the next cell.
Your training set is ready, you can now move on to the CBOW model itself.
The continuous bag-of-words model
The CBOW model is based on a neural network, the architecture of which looks like the figure below, as you'll recall from the lecture.
Figure 1 This part of the notebook will walk you through:
The two activation functions used in the neural network.
Forward propagation.
Cross-entropy loss.
Backpropagation.
Gradient descent.
Extracting the word embedding vectors from the weight matrices once the neural network has been trained.
Activation functions
Let's start by implementing the activation functions, ReLU and softmax.
ReLU
ReLU is used to calculate the values of the hidden layer, in the following formulas:
Let's fix a value for as a working example.
To get the ReLU of this vector, you want all the negative values to become zeros.
First create a copy of this vector.
Now determine which of its values are negative.
You can now simply set all of the values which are negative to 0.
And that's it: you have the ReLU of !
Now implement ReLU as a function.
And check that it's working.
Expected output:
Softmax
The second activation function that you need is softmax. This function is used to calculate the values of the output layer of the neural network, using the following formulas:
To calculate softmax of a vector , the -th component of the resulting vector is given by:
Let's work through an example.
You'll need to calculate the exponentials of each element, both for the numerator and for the denominator.
The denominator is equal to the sum of these exponentials.
And the value of the first element of is given by:
This is for one element. You can use numpy's vectorized operations to calculate the values of all the elements of the vector in one go.
Implement the softmax function.
Now check that it works.
Expected output:
Dimensions: 1-D arrays vs 2-D column vectors
Before moving on to implement forward propagation, backpropagation, and gradient descent, let's have a look at the dimensions of the vectors you've been handling until now.
Create a vector of length filled with zeros.
This is a 1-dimensional array, as revealed by the .shape property of the array.
To perform matrix multiplication in the next steps, you actually need your column vectors to be represented as a matrix with one column. In numpy, this matrix is represented as a 2-dimensional array.
The easiest way to convert a 1D vector to a 2D column matrix is to set its .shape property to the number of rows and one column, as shown in the next cell.
The shape of the resulting "vector" is:
So you now have a 5x1 matrix that you can use to perform standard matrix multiplication.
Forward propagation
Let's dive into the neural network itself, which is shown below with all the dimensions and formulas you'll need.
Figure 2 Set equal to 3. Remember that is a hyperparameter of the CBOW model that represents the size of the word embedding vectors, as well as the size of the hidden layer.
Initialization of the weights and biases
Before you start training the neural network, you need to initialize the weight matrices and bias vectors with random values.
In the assignment you will implement a function to do this yourself using numpy.random.rand. In this notebook, we've pre-populated these matrices and vectors for you.
Check that the dimensions of these matrices match those shown in the figure above.
Training example
Run the next cells to get the first training example, made of the vector representing the context words "i am because i", and the target which is the one-hot vector representing the center word "happy".
You don't need to worry about the Python syntax, but there are some explanations below if you want to know what's happening behind the scenes.
get_training_examples, which uses theyieldkeyword, is known as a generator. When run, it builds an iterator, which is a special type of object that... you can iterate on (using aforloop for instance), to retrieve the successive values that the function generates.In this case
get_training_examplesyields training examples, and iterating ontraining_exampleswill return the successive training examples.
nextis another special keyword, which gets the next available value from an iterator. Here, you'll get the very first value, which is the first training example. If you run this cell again, you'll get the next value, and so on until the iterator runs out of values to return.In this notebook
nextis used because you will only be performing one iteration of training. In this week's assignment with the full training over several iterations you'll use regularforloops with the iterator that supplies the training examples.
The vector representing the context words, which will be fed into the neural network, is:
The one-hot vector representing the center word to be predicted is:
Now convert these vectors into matrices (or 2D arrays) to be able to perform matrix multiplication on the right types of objects, as explained above.
Values of the hidden layer
Now that you have initialized all the variables that you need for forward propagation, you can calculate the values of the hidden layer using the following formulas:
First, you can calculate the value of .
np.dotis numpy's function for matrix multiplication.
As expected you get an by 1 matrix, or column vector with elements, where is equal to the embedding size, which is 3 in this example.
You can now take the ReLU of to get , the vector with the values of the hidden layer.
Applying ReLU means that the negative element of has been replaced with a zero.
Values of the output layer
Here are the formulas you need to calculate the values of the output layer, represented by the vector :
First, calculate .
Expected output:
This is a by 1 matrix, where is the size of the vocabulary, which is 5 in this example.
Now calculate the value of .
Expected output:
As you've performed the calculations with random matrices and vectors (apart from the input vector), the output of the neural network is essentially random at this point. The learning process will adjust the weights and biases to match the actual targets better.
That being said, what word did the neural network predict?
The neural network predicted the word "happy": the largest element of is the third one, and the third word of the vocabulary is "happy".
Here's how you could implement this in Python:
print(Ind2word[np.argmax(y_hat)])
Well done, you've completed the forward propagation phase!
Cross-entropy loss
Now that you have the network's prediction, you can calculate the cross-entropy loss to determine how accurate the prediction was compared to the actual target.
Remember that you are working on a single training example, not on a batch of examples, which is why you are using loss and not cost, which is the generalized form of loss.
First let's recall what the prediction was.
And the actual target value is:
The formula for cross-entropy loss is:
Implement the cross-entropy loss function.
Here are a some hints if you're stuck.
To multiply two numpy matrices (such as y and y_hat) element-wise, you can simply use the * operator.
Once you have a vector equal to the element-wise multiplication of y and y_hat, you can use np.sum to calculate the sum of the elements of this vector.
Now use this function to calculate the loss with the actual values of and .
Expected output:
This value is neither good nor bad, which is expected as the neural network hasn't learned anything yet.
The actual learning will start during the next phase: backpropagation.
Backpropagation
The formulas that you will implement for backpropagation are the following.
Note: these formulas are slightly simplified compared to the ones in the lecture as you're working on a single training example, whereas the lecture provided the formulas for a batch of examples. In the assignment you'll be implementing the latter.
Let's start with an easy one.
Calculate the partial derivative of the loss function with respect to , and store the result in grad_b2.
Expected output:
Next, calculate the partial derivative of the loss function with respect to , and store the result in grad_W2.
Hint: use
.Tto get a transposed matrix, e.g.h.Treturns .
Expected output:
Now calculate the partial derivative with respect to and store the result in grad_b1.
Expected output:
Finally, calculate the partial derivative of the loss with respect to , and store it in grad_W1.
Expected output:
Before moving on to gradient descent, double-check that all the matrices have the expected dimensions.
Gradient descent
During the gradient descent phase, you will update the weights and biases by subtracting times the gradient from the original matrices and vectors, using the following formulas.
First, let set a value for .
The updated weight matrix will be:
Let's compare the previous and new values of :
The difference is very subtle (hint: take a closer look at the last row), which is why it takes a fair amount of iterations to train the neural network until it reaches optimal weights and biases starting from random values.
Now calculate the new values of (to be stored in W2_new), (in b1_new), and (in b2_new).
Expected output:
Congratulations, you have completed one iteration of training using one training example!
You'll need many more iterations to fully train the neural network, and you can optimize the learning process by training on batches of examples, as described in the lecture. You will get to do this during this week's assignment.
Extracting word embedding vectors
Once you have finished training the neural network, you have three options to get word embedding vectors for the words of your vocabulary, based on the weight matrices and/or .
Option 1: extract embedding vectors from
The first option is to take the columns of as the embedding vectors of the words of the vocabulary, using the same order of the words as for the input and output vectors.
Note: in this practice notebook the values of the word embedding vectors are meaningless after a single iteration with just one training example, but here's how you would proceed after the training process is complete.
For example is this matrix:
The first column, which is a 3-element vector, is the embedding vector of the first word of your vocabulary. The second column is the word embedding vector for the second word, and so on.
The first, second, etc. words are ordered as follows.
So the word embedding vectors corresponding to each word are:
Option 2: extract embedding vectors from
The second option is to take transposed, and take its columns as the word embedding vectors just like you did for .
Option 3: extract embedding vectors from and
The third option, which is the one you will use in this week's assignment, uses the average of and .
Calculate the average of and , and store the result in W3.
Expected output:
Extracting the word embedding vectors works just like the two previous options, by taking the columns of the matrix you've just created.
You're now ready to take on this week's assignment!
How this practice relates to and differs from the upcoming graded assignment
In the assignment, for each iteration of training you will use batches of examples instead of a single example. The formulas for forward propagation and backpropagation will be modified accordingly, and you will use cross-entropy cost instead of cross-entropy loss.
You will also complete several iterations of training, until you reach an acceptably low cross-entropy cost, at which point you can extract good word embeddings from the weight matrices.
After extracting the word embedding vectors, you will use principal component analysis (PCA) to visualize the vectors, which will enable you to perform an intrinsic evaluation of the quality of the vectors, as explained in the lecture.