Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/C5 - Sequence Models/Week 2/Emojify/Emojify_v2a.ipynb
Views: 4819
Emojify!
Welcome to the second assignment of Week 2. You are going to use word vector representations to build an Emojifier.
Have you ever wanted to make your text messages more expressive? Your emojifier app will help you do that. So rather than writing:
"Congratulations on the promotion! Let's get coffee and talk. Love you!"
The emojifier can automatically turn this into:
"Congratulations on the promotion! 👍 Let's get coffee and talk. ☕️ Love you! ❤️"
You will implement a model which inputs a sentence (such as "Let's go see the baseball game tonight!") and finds the most appropriate emoji to be used with this sentence (⚾️).
Using word vectors to improve emoji lookups
In many emoji interfaces, you need to remember that ❤️ is the "heart" symbol rather than the "love" symbol.
In other words, you'll have to remember to type "heart" to find the desired emoji, and typing "love" won't bring up that symbol.
We can make a more flexible emoji interface by using word vectors!
When using word vectors, you'll see that even if your training set explicitly relates only a few words to a particular emoji, your algorithm will be able to generalize and associate additional words in the test set to the same emoji.
This works even if those additional words don't even appear in the training set.
This allows you to build an accurate classifier mapping from sentences to emojis, even using a small training set.
What you'll build
In this exercise, you'll start with a baseline model (Emojifier-V1) using word embeddings.
Then you will build a more sophisticated model (Emojifier-V2) that further incorporates an LSTM.
Updates
If you were working on the notebook before this update...
The current notebook is version "2a".
You can find your original work saved in the notebook with the previous version name ("v2")
To view the file directory, go to the menu "File->Open", and this will open a new tab that shows the file directory.
List of updates
sentence_to_avg
Updated instructions.
Use separate variables to store the total and the average (instead of just
avg
).Additional hint about how to initialize the shape of
avg
vector.
sentences_to_indices
Updated preceding text and instructions, added additional hints.
pretrained_embedding_layer
Additional instructions to explain how to implement each step.
Emoify_V2
Modifies instructions to specify which parameters are needed for each Keras layer.
Remind users of Keras syntax.
Explanation of how to use the layer object that is returned by
pretrained_embedding_layer
.Provides sample Keras code.
Spelling, grammar and wording corrections.
Let's get started! Run the following cell to load the package you are going to use.
1 - Baseline model: Emojifier-V1
1.1 - Dataset EMOJISET
Let's start by building a simple baseline classifier.
You have a tiny dataset (X, Y) where:
X contains 127 sentences (strings).
Y contains an integer label between 0 and 4 corresponding to an emoji for each sentence.

Let's load the dataset using the code below. We split the dataset between training (127 examples) and testing (56 examples).
Run the following cell to print sentences from X_train and corresponding labels from Y_train.
Change
idx
to see different examples.Note that due to the font used by iPython notebook, the heart emoji may be colored black rather than red.
1.2 - Overview of the Emojifier-V1
In this part, you are going to implement a baseline model called "Emojifier-v1".

Inputs and outputs
The input of the model is a string corresponding to a sentence (e.g. "I love you).
The output will be a probability vector of shape (1,5), (there are 5 emojis to choose from).
The (1,5) probability vector is passed to an argmax layer, which extracts the index of the emoji with the highest probability.
One-hot encoding
To get our labels into a format suitable for training a softmax classifier, lets convert from its current shape into a "one-hot representation" ,
Each row is a one-hot vector giving the label of one example.
Here,
Y_oh
stands for "Y-one-hot" in the variable namesY_oh_train
andY_oh_test
:
Let's see what convert_to_one_hot()
did. Feel free to change index
to print out different values.
All the data is now ready to be fed into the Emojify-V1 model. Let's implement the model!
1.3 - Implementing Emojifier-V1
As shown in Figure 2 (above), the first step is to:
Convert each word in the input sentence into their word vector representations.
Then take an average of the word vectors.
Similar to the previous exercise, we will use pre-trained 50-dimensional GloVe embeddings.
Run the following cell to load the word_to_vec_map
, which contains all the vector representations.
You've loaded:
word_to_index
: dictionary mapping from words to their indices in the vocabulary(400,001 words, with the valid indices ranging from 0 to 400,000)
index_to_word
: dictionary mapping from indices to their corresponding words in the vocabularyword_to_vec_map
: dictionary mapping words to their GloVe vector representation.
Run the following cell to check if it works.
Exercise: Implement sentence_to_avg()
. You will need to carry out two steps:
Convert every sentence to lower-case, then split the sentence into a list of words.
X.lower()
andX.split()
might be useful.
For each word in the sentence, access its GloVe representation.
Then take the average of all of these word vectors.
You might use
numpy.zeros()
.
Additional Hints
When creating the
avg
array of zeros, you'll want it to be a vector of the same shape as the other word vectors in theword_to_vec_map
.You can choose a word that exists in the
word_to_vec_map
and access its.shape
field.Be careful not to hard code the word that you access. In other words, don't assume that if you see the word 'the' in the
word_to_vec_map
within this notebook, that this word will be in theword_to_vec_map
when the function is being called by the automatic grader.Hint: you can use any one of the word vectors that you retrieved from the input
sentence
to find the shape of a word vector.
Expected Output:
Model
You now have all the pieces to finish implementing the model()
function. After using sentence_to_avg()
you need to:
Pass the average through forward propagation
Compute the cost
Backpropagate to update the softmax parameters
Exercise: Implement the model()
function described in Figure (2).
The equations you need to implement in the forward pass and to compute the cross-entropy cost are below:
The variable ("Y one hot") is the one-hot encoding of the output labels.
Note It is possible to come up with a more efficient vectorized implementation. For now, let's use nested for loops to better understand the algorithm, and for easier debugging.
We provided the function softmax()
, which was imported earlier.
Run the next cell to train your model and learn the softmax parameters (W,b).
Expected Output (on a subset of iterations):
**Epoch: 0** | cost = 1.95204988128 | Accuracy: 0.348484848485 |
Great! Your model has pretty high accuracy on the training set. Lets now see how it does on the test set.
1.4 - Examining test set performance
Note that the
predict
function used here is defined in emo_util.spy.
Expected Output:
**Train set accuracy** | 97.7 |
**Test set accuracy** | 85.7 |
Random guessing would have had 20% accuracy given that there are 5 classes. (1/5 = 20%).
This is pretty good performance after training on only 127 examples.
The model matches emojis to relevant words
In the training set, the algorithm saw the sentence
"I love you"
with the label ❤️.
You can check that the word "adore" does not appear in the training set.
Nonetheless, lets see what happens if you write "I adore you."
Amazing!
Because adore has a similar embedding as love, the algorithm has generalized correctly even to a word it has never seen before.
Words such as heart, dear, beloved or adore have embedding vectors similar to love.
Feel free to modify the inputs above and try out a variety of input sentences.
How well does it work?
Word ordering isn't considered in this model
Note that the model doesn't get the following sentence correct:
"not feeling happy"
This algorithm ignores word ordering, so is not good at understanding phrases like "not happy."
Confusion matrix
Printing the confusion matrix can also help understand which classes are more difficult for your model.
A confusion matrix shows how often an example whose label is one class ("actual" class) is mislabeled by the algorithm with a different class ("predicted" class).
What you should remember from this section
Even with a 127 training examples, you can get a reasonably good model for Emojifying.
This is due to the generalization power word vectors gives you.
Emojify-V1 will perform poorly on sentences such as "This movie is not good and not enjoyable"
It doesn't understand combinations of words.
It just averages all the words' embedding vectors together, without considering the ordering of words.
You will build a better algorithm in the next section!
2 - Emojifier-V2: Using LSTMs in Keras:
Let's build an LSTM model that takes word sequences as input!
This model will be able to account for the word ordering.
Emojifier-V2 will continue to use pre-trained word embeddings to represent words.
We will feed word embeddings into an LSTM.
The LSTM will learn to predict the most appropriate emoji.
Run the following cell to load the Keras packages.
2.1 - Overview of the model
Here is the Emojifier-v2 you will implement:
2.2 Keras and mini-batching
In this exercise, we want to train Keras using mini-batches.
However, most deep learning frameworks require that all sequences in the same mini-batch have the same length.
This is what allows vectorization to work: If you had a 3-word sentence and a 4-word sentence, then the computations needed for them are different (one takes 3 steps of an LSTM, one takes 4 steps) so it's just not possible to do them both at the same time.
Padding handles sequences of varying length
The common solution to handling sequences of different length is to use padding. Specifically:
Set a maximum sequence length
Pad all sequences to have the same length.
Example of padding
Given a maximum sequence length of 20, we could pad every sentence with "0"s so that each input sentence is of length 20.
Thus, the sentence "I love you" would be represented as .
In this example, any sentences longer than 20 words would have to be truncated.
One way to choose the maximum sequence length is to just pick the length of the longest sentence in the training set.
2.3 - The Embedding layer
In Keras, the embedding matrix is represented as a "layer".
The embedding matrix maps word indices to embedding vectors.
The word indices are positive integers.
The embedding vectors are dense vectors of fixed size.
When we say a vector is "dense", in this context, it means that most of the values are non-zero. As a counter-example, a one-hot encoded vector is not "dense."
The embedding matrix can be derived in two ways:
Training a model to derive the embeddings from scratch.
Using a pretrained embedding
Using and updating pre-trained embeddings
In this part, you will learn how to create an Embedding() layer in Keras
You will initialize the Embedding layer with the GloVe 50-dimensional vectors.
In the code below, we'll show you how Keras allows you to either train or leave fixed this layer.
Because our training set is quite small, we will leave the GloVe embeddings fixed instead of updating them.
Inputs and outputs to the embedding layer
The
Embedding()
layer's input is an integer matrix of size (batch size, max input length).This input corresponds to sentences converted into lists of indices (integers).
The largest integer (the highest word index) in the input should be no larger than the vocabulary size.
The embedding layer outputs an array of shape (batch size, max input length, dimension of word vectors).
The figure shows the propagation of two example sentences through the embedding layer.
Both examples have been zero-padded to a length of
max_len=5
.The word embeddings are 50 units in length.
The final dimension of the representation is
(2,max_len,50)
.

Prepare the input sentences
Exercise:
Implement
sentences_to_indices
, which processes an array of sentences (X) and returns inputs to the embedding layer:Convert each training sentences into a list of indices (the indices correspond to each word in the sentence)
Zero-pad all these lists so that their length is the length of the longest sentence.
Additional Hints
Note that you may have considered using the
enumerate()
function in the for loop, but for the purposes of passing the autograder, please follow the starter code by initializing and incrementingj
explicitly.
Run the following cell to check what sentences_to_indices()
does, and check your results.
Expected Output:
Build embedding layer
Let's build the
Embedding()
layer in Keras, using pre-trained word vectors.The embedding layer takes as input a list of word indices.
sentences_to_indices()
creates these word indices.
The embedding layer will return the word embeddings for a sentence.
Exercise: Implement pretrained_embedding_layer()
with these steps:
Initialize the embedding matrix as a numpy array of zeros.
The embedding matrix has a row for each unique word in the vocabulary.
There is one additional row to handle "unknown" words.
So vocab_len is the number of unique words plus one.
Each row will store the vector representation of one word.
For example, one row may be 50 positions long if using GloVe word vectors.
In the code below,
emb_dim
represents the length of a word embedding.
Fill in each row of the embedding matrix with the vector representation of a word
Each word in
word_to_index
is a string.word_to_vec_map is a dictionary where the keys are strings and the values are the word vectors.
Define the Keras embedding layer.
Use Embedding().
The input dimension is equal to the vocabulary length (number of unique words plus one).
The output dimension is equal to the number of positions in a word embedding.
Make this layer's embeddings fixed.
If you were to set
trainable = True
, then it will allow the optimization algorithm to modify the values of the word embeddings.In this case, we don't want the model to modify the word embeddings.
Set the embedding weights to be equal to the embedding matrix.
Note that this is part of the code is already completed for you and does not need to be modified.
Expected Output:
2.3 Building the Emojifier-V2
Lets now build the Emojifier-V2 model.
You feed the embedding layer's output to an LSTM network.
Exercise: Implement Emojify_V2()
, which builds a Keras graph of the architecture shown in Figure 3.
The model takes as input an array of sentences of shape (
m
,max_len
, ) defined byinput_shape
.The model outputs a softmax probability vector of shape (
m
,C = 5
).You may need to use the following Keras layers:
Set the
shape
anddtype
parameters.The inputs are integers, so you can specify the data type as a string, 'int32'.
Set the
units
andreturn_sequences
parameters.
Set the
rate
parameter.
Set the
units
,Note that
Dense()
has anactivation
parameter. For the purposes of passing the autograder, please do not set the activation withinDense()
. Use the separateActivation
layer to do so.
You can pass in the activation of your choice as a lowercase string.
Model Set
inputs
andoutputs
.
Additional Hints
Remember that these Keras layers return an object, and you will feed in the outputs of the previous layer as the input arguments to that object. The returned object can be created and called in the same line.
The
embedding_layer
that is returned bypretrained_embedding_layer
is a layer object that can be called as a function, passing in a single argument (sentence indices).Here is some sample code in case you're stuck
Run the following cell to create your model and check its summary. Because all sentences in the dataset are less than 10 words, we chose max_len = 10
. You should see your architecture, it uses "20,223,927" parameters, of which 20,000,050 (the word embeddings) are non-trainable, and the remaining 223,877 are. Because our vocabulary size has 400,001 words (with valid indices from 0 to 400,000) there are 400,001*50 = 20,000,050 non-trainable parameters.
As usual, after creating your model in Keras, you need to compile it and define what loss, optimizer and metrics your are want to use. Compile your model using categorical_crossentropy
loss, adam
optimizer and ['accuracy']
metrics:
It's time to train your model. Your Emojifier-V2 model
takes as input an array of shape (m
, max_len
) and outputs probability vectors of shape (m
, number of classes
). We thus have to convert X_train (array of sentences as strings) to X_train_indices (array of sentences as list of word indices), and Y_train (labels as indices) to Y_train_oh (labels as one-hot vectors).
Fit the Keras model on X_train_indices
and Y_train_oh
. We will use epochs = 50
and batch_size = 32
.
Your model should perform around 90% to 100% accuracy on the training set. The exact accuracy you get may be a little different. Run the following cell to evaluate your model on the test set.
You should get a test accuracy between 80% and 95%. Run the cell below to see the mislabelled examples.
Now you can try it on your own example. Write your own sentence below.
LSTM version accounts for word order
Previously, Emojify-V1 model did not correctly label "not feeling happy," but our implementation of Emojiy-V2 got it right.
(Keras' outputs are slightly random each time, so you may not have obtained the same result.)
The current model still isn't very robust at understanding negation (such as "not happy")
This is because the training set is small and doesn't have a lot of examples of negation.
But if the training set were larger, the LSTM model would be much better than the Emojify-V1 model at understanding such complex sentences.
Congratulations!
You have completed this notebook! ❤️❤️❤️
What you should remember
If you have an NLP task where the training set is small, using word embeddings can help your algorithm significantly.
Word embeddings allow your model to work on words in the test set that may not even appear in the training set.
Training sequence models in Keras (and in most other deep learning frameworks) requires a few important details:
To use mini-batches, the sequences need to be padded so that all the examples in a mini-batch have the same length.
An
Embedding()
layer can be initialized with pretrained values.These values can be either fixed or trained further on your dataset.
If however your labeled dataset is small, it's usually not worth trying to train a large pre-trained set of embeddings.
LSTM()
has a flag calledreturn_sequences
to decide if you would like to return every hidden states or only the last one.You can use
Dropout()
right afterLSTM()
to regularize your network.
Input sentences:
Output emojis:
😀😀😀😀😀😀
Acknowledgments
Thanks to Alison Darcy and the Woebot team for their advice on the creation of this assignment.
Woebot is a chatbot friend that is ready to speak with you 24/7.
Part of Woebot's technology uses word embeddings to understand the emotions of what you say.
You can chat with Woebot by going to http://woebot.io