{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "5bgPpghocFIa" }, "source": [ "# Emojify! \n", "\n", "Welcome to the second assignment of Week 2! You're going to use word vector representations to build an Emojifier. \n", "🀩 πŸ’« πŸ”₯\n", "\n", "Have you ever wanted to make your text messages more expressive? Your emojifier app will help you do that. \n", "Rather than writing:\n", ">\"Congratulations on the promotion! Let's get coffee and talk. Love you!\" \n", "\n", "The emojifier can automatically turn this into:\n", ">\"Congratulations on the promotion! πŸ‘ Let's get coffee and talk. β˜•οΈ Love you! ❀️\"\n", "\n", "You'll 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 (⚾️).\n", "\n", "### Using Word Vectors to Improve Emoji Lookups\n", "* In many emoji interfaces, you need to remember that ❀️ is the \"heart\" symbol rather than the \"love\" symbol. \n", " * 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.\n", "* You can make a more flexible emoji interface by using word vectors!\n", "* 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.\n", " * This works even if those additional words don't even appear in the training set. \n", " * This allows you to build an accurate classifier mapping from sentences to emojis, even using a small training set. \n", "\n", "### What you'll build:\n", "1. In this exercise, you'll start with a baseline model (Emojifier-V1) using word embeddings.\n", "2. Then you will build a more sophisticated model (Emojifier-V2) that further incorporates an LSTM. \n", "\n", "By the end of this notebook, you'll be able to:\n", "\n", "* Create an embedding layer in Keras with pre-trained word vectors\n", "* Explain the advantages and disadvantages of the GloVe algorithm\n", "* Describe how negative sampling learns word vectors more efficiently than other methods\n", "* Build a sentiment classifier using word embeddings\n", "* Build and train a more sophisticated classifier using an LSTM\n", "\n", "πŸ€ πŸ‘‘\n", "\n", "πŸ‘† 😎\n", "\n", "(^^^ Emoji for \"skills\") " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Table of Contents\n", "\n", "- [Packages](#0)\n", "- [1 - Baseline Model: Emojifier-V1](#1)\n", " - [1.1 - Dataset EMOJISET](#1-1)\n", " - [1.2 - Overview of the Emojifier-V1](#1-2)\n", " - [1.3 - Implementing Emojifier-V1](#1-3)\n", " - [Exercise 1 - sentence_to_avg](#ex-1)\n", " - [1.4 - Implement the Model](#1-4)\n", " - [Exercise 2 - model](#ex-2)\n", " - [1.5 - Examining Test Set Performance](#1-5)\n", "- [2 - Emojifier-V2: Using LSTMs in Keras](#2)\n", " - [2.1 - Model Overview](#2-1)\n", " - [2.2 Keras and Mini-batching](#2-2)\n", " - [2.3 - The Embedding Layer](#2-3)\n", " - [Exercise 3 - sentences_to_indices](#ex-3)\n", " - [Exercise 4 - pretrained_embedding_layer](#ex-4)\n", " - [2.4 - Building the Emojifier-V2](#2-4)\n", " - [Exercise 5 - Emojify_V2](#ex-5)\n", " - [2.5 - Train the Model](#2-5)\n", "- [3 - Acknowledgments](#3)" ] }, { "cell_type": "markdown", "metadata": { "id": "HsztVBA8cFIg" }, "source": [ "\n", "## Packages\n", "\n", "Let's get started! Run the following cell to load the packages you're going to use. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "lMZ9xg8MFHZU" }, "outputs": [], "source": [ "import numpy as np\n", "from emo_utils import *\n", "import emoji\n", "import matplotlib.pyplot as plt\n", "from test_utils import *\n", "\n", "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": { "id": "Av0PwZYscFIh" }, "source": [ "\n", "## 1 - Baseline Model: Emojifier-V1\n", "\n", "\n", "### 1.1 - Dataset EMOJISET\n", "\n", "Let's start by building a simple baseline classifier. \n", "\n", "You have a tiny dataset (X, Y) where:\n", "- X contains 127 sentences (strings).\n", "- Y contains an integer label between 0 and 4 corresponding to an emoji for each sentence.\n", "\n", "\n", "
Figure 1: EMOJISET - a classification problem with 5 classes. A few examples of sentences are given here.
\n", "\n", "Load the dataset using the code below. The dataset is split between training (127 examples) and testing (56 examples)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2671, "status": "ok", "timestamp": 1611738624467, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "OvuoZ8pWcFIi" }, "outputs": [], "source": [ "X_train, Y_train = read_csv('data/train_emoji.csv')\n", "X_test, Y_test = read_csv('data/tesss.csv')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2046, "status": "ok", "timestamp": 1611738634135, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "DjAuDbxrcFIi" }, "outputs": [], "source": [ "maxLen = len(max(X_train, key=len).split())" ] }, { "cell_type": "markdown", "metadata": { "id": "EpbQIx7dcFIi" }, "source": [ "Run the following cell to print sentences from X_train and corresponding labels from Y_train. \n", "* Change `idx` to see different examples. \n", "* Note that due to the font used by iPython notebook, the heart emoji may be colored black rather than red." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 2058, "status": "ok", "timestamp": 1611738637381, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "vE1Zd2SMcFIj", "outputId": "49f45ed1-8f2f-4ea8-da44-4acb41731287", "scrolled": true }, "outputs": [], "source": [ "for idx in range(10):\n", " print(X_train[idx], label_to_emoji(Y_train[idx]))" ] }, { "cell_type": "markdown", "metadata": { "id": "tS_N2pMpcFIk" }, "source": [ "\n", "### 1.2 - Overview of the Emojifier-V1\n", "\n", "In this section, you'll implement a baseline model called \"Emojifier-v1\". \n", "\n", "
\n", "\n", "
Figure 2: Baseline model (Emojifier-V1).
\n", "
\n", "\n", "\n", "#### Inputs and Outputs\n", "* The input of the model is a string corresponding to a sentence (e.g. \"I love you\"). \n", "* The output will be a probability vector of shape (1,5), (indicating that there are 5 emojis to choose from).\n", "* The (1,5) probability vector is passed to an argmax layer, which extracts the index of the emoji with the highest probability." ] }, { "cell_type": "markdown", "metadata": { "id": "Y6nloeF5cFIl" }, "source": [ "#### One-hot Encoding\n", "* To get your labels into a format suitable for training a softmax classifier, convert $Y$ from its current shape $(m, 1)$ into a \"one-hot representation\" $(m, 5)$, \n", " * Each row is a one-hot vector giving the label of one example.\n", " * Here, `Y_oh` stands for \"Y-one-hot\" in the variable names `Y_oh_train` and `Y_oh_test`: " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2619, "status": "ok", "timestamp": 1611738660835, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "RhRTRwVncFIm" }, "outputs": [], "source": [ "Y_oh_train = convert_to_one_hot(Y_train, C = 5)\n", "Y_oh_test = convert_to_one_hot(Y_test, C = 5)" ] }, { "cell_type": "markdown", "metadata": { "id": "2w3GRkw2cFIo" }, "source": [ "Now, see what `convert_to_one_hot()` did. Feel free to change `index` to print out different values. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 2838, "status": "ok", "timestamp": 1611738667164, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "GlHYeuBIcFIo", "outputId": "c2b73f6a-9a15-4728-a8b4-7ba38b5372ed" }, "outputs": [], "source": [ "idx = 50\n", "print(f\"Sentence '{X_train[50]}' has label index {Y_train[idx]}, which is emoji {label_to_emoji(Y_train[idx])}\", )\n", "print(f\"Label index {Y_train[idx]} in one-hot encoding format is {Y_oh_train[idx]}\")" ] }, { "cell_type": "markdown", "metadata": { "id": "gbFECkqAcFIp" }, "source": [ "All the data is now ready to be fed into the Emojify-V1 model. You're ready to implement the model!" ] }, { "cell_type": "markdown", "metadata": { "id": "KI8mJoafcFIp" }, "source": [ "\n", "### 1.3 - Implementing Emojifier-V1\n", "\n", "As shown in Figure 2 (above), the first step is to:\n", "* Convert each word in the input sentence into their word vector representations.\n", "* Take an average of the word vectors. \n", "\n", "Similar to this week's previous assignment, you'll use pre-trained 50-dimensional GloVe embeddings. \n", "\n", "Run the following cell to load the `word_to_vec_map`, which contains all the vector representations." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 8474, "status": "ok", "timestamp": 1611738705912, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "QXI3avt7cFIq" }, "outputs": [], "source": [ "word_to_index, index_to_word, word_to_vec_map = read_glove_vecs('data/glove.6B.50d.txt')" ] }, { "cell_type": "markdown", "metadata": { "id": "9JM-0zg6cFIr" }, "source": [ "You've loaded:\n", "- `word_to_index`: dictionary mapping from words to their indices in the vocabulary \n", " - (400,001 words, with the valid indices ranging from 0 to 400,000)\n", "- `index_to_word`: dictionary mapping from indices to their corresponding words in the vocabulary\n", "- `word_to_vec_map`: dictionary mapping words to their GloVe vector representation. (50-dimensional)\n", "\n", "Run the following cell to check if it works:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 1164, "status": "ok", "timestamp": 1611738710682, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "RB2ZN6ajcFIr", "outputId": "3c733016-edf8-417d-f589-828c2a9d8a09" }, "outputs": [], "source": [ "word = \"cucumber\"\n", "idx = 289846\n", "print(\"the index of\", word, \"in the vocabulary is\", word_to_index[word])\n", "print(\"the\", str(idx) + \"th word in the vocabulary is\", index_to_word[idx])" ] }, { "cell_type": "markdown", "metadata": { "id": "wg9QpkR5cFIs" }, "source": [ "\n", "### Exercise 1 - sentence_to_avg\n", "\n", "Implement `sentence_to_avg()` \n", "\n", "You'll need to carry out two steps:\n", "\n", "1. Convert every sentence to lower-case, then split the sentence into a list of words. \n", " * `X.lower()` and `X.split()` might be useful. πŸ˜‰\n", "2. For each word in the sentence, access its GloVe representation.\n", " * Then take the average of all of these word vectors.\n", " * You might use `numpy.zeros()`, which you can read more about [here]('https://numpy.org/doc/stable/reference/generated/numpy.zeros.html').\n", " \n", " \n", "#### Additional Hints\n", "* 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 the `word_to_vec_map`. \n", " * You can choose a word that exists in the `word_to_vec_map` and access its `.shape` field.\n", " * 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 the `word_to_vec_map` when the function is being called by the automatic grader.\n", "\n", "**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." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 1943, "status": "ok", "timestamp": 1611738728468, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "buYjsIBecFIs" }, "outputs": [], "source": [ "# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n", "# GRADED FUNCTION: sentence_to_avg\n", "\n", "def sentence_to_avg(sentence, word_to_vec_map):\n", " \"\"\"\n", " Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word\n", " and averages its value into a single vector encoding the meaning of the sentence.\n", " \n", " Arguments:\n", " sentence -- string, one training example from X\n", " word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation\n", " \n", " Returns:\n", " avg -- average vector encoding information about the sentence, numpy-array of shape (50,)\n", " \"\"\"\n", " # Get a valid word contained in the word_to_vec_map. \n", " any_word = list(word_to_vec_map.keys())[0]\n", " \n", " ### START CODE HERE ###\n", " # Step 1: Split sentence into list of lower case words (β‰ˆ 1 line)\n", " words = sentence.lower().split()\n", "\n", " # Initialize the average word vector, should have the same shape as your word vectors.\n", " avg = np.zeros(word_to_vec_map[any_word].shape)\n", " \n", " # Initialize count to 0\n", " count = 0\n", " \n", " # Step 2: average the word vectors. You can loop over the words in the list \"words\".\n", " for w in words:\n", " # Check that word exists in word_to_vec_map\n", " if w in list(word_to_vec_map.keys()):\n", " avg += word_to_vec_map[w]\n", " # Increment count\n", " count +=1\n", " \n", " if count > 0:\n", " # Get the average. But only if count > 0\n", " avg = avg/count\n", " \n", " ### END CODE HERE ###\n", " \n", " return avg" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 1861, "status": "ok", "timestamp": 1611738734359, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "7OwW-r6ecFIt", "outputId": "7ed0ff55-10f4-4072-fdff-2edc216373fc", "scrolled": true }, "outputs": [], "source": [ "# BEGIN UNIT TEST\n", "avg = sentence_to_avg(\"Morrocan couscous is my favorite dish\", word_to_vec_map)\n", "print(\"avg = \\n\", avg)\n", "\n", "def sentence_to_avg_test(target):\n", " # Create a controlled word to vec map\n", " word_to_vec_map = {'a': [3, 3], 'synonym_of_a': [3, 3], 'a_nw': [2, 4], 'a_s': [3, 2], \n", " 'c': [-2, 1], 'c_n': [-2, 2],'c_ne': [-1, 2], 'c_e': [-1, 1], 'c_se': [-1, 0], \n", " 'c_s': [-2, 0], 'c_sw': [-3, 0], 'c_w': [-3, 1], 'c_nw': [-3, 2]\n", " }\n", " # Convert lists to np.arrays\n", " for key in word_to_vec_map.keys():\n", " word_to_vec_map[key] = np.array(word_to_vec_map[key])\n", " \n", " avg = target(\"a a_nw c_w a_s\", word_to_vec_map)\n", " assert tuple(avg.shape) == tuple(word_to_vec_map['a'].shape), \"Check the shape of your avg array\" \n", " assert np.allclose(avg, [1.25, 2.5]), \"Check that you are finding the 4 words\"\n", " avg = target(\"love a a_nw c_w a_s\", word_to_vec_map)\n", " assert np.allclose(avg, [1.25, 2.5]), \"Divide by count, not len(words)\"\n", " avg = target(\"love\", word_to_vec_map)\n", " assert np.allclose(avg, [0, 0]), \"Average of no words must give an array of zeros\"\n", " avg = target(\"c_se foo a a_nw c_w a_s deeplearning c_nw\", word_to_vec_map)\n", " assert np.allclose(avg, [0.1666667, 2.0]), \"Debug the last example\"\n", " \n", " print(\"\\033[92mAll tests passed!\")\n", " \n", "sentence_to_avg_test(sentence_to_avg)\n", "\n", "# END UNIT TEST" ] }, { "cell_type": "markdown", "metadata": { "id": "NPPv5gmucFIv" }, "source": [ "\n", "### 1.4 - Implement the Model\n", "\n", "You now have all the pieces to finish implementing the `model()` function! \n", "After using `sentence_to_avg()` you need to:\n", "* Pass the average through forward propagation\n", "* Compute the cost\n", "* Backpropagate to update the softmax parameters\n", "\n", "\n", "### Exercise 2 - model\n", "\n", "Implement the `model()` function described in Figure (2). \n", "\n", "* The equations you need to implement in the forward pass and to compute the cross-entropy cost are below:\n", "* The variable $Y_{oh}$ (\"Y one hot\") is the one-hot encoding of the output labels. \n", "\n", "$$ z^{(i)} = W . avg^{(i)} + b$$\n", "\n", "$$ a^{(i)} = softmax(z^{(i)})$$\n", "\n", "$$ \\mathcal{L}^{(i)} = - \\sum_{k = 0}^{n_y - 1} Y_{oh,k}^{(i)} * log(a^{(i)}_k)$$\n", "\n", "**Note**: It is possible to come up with a more efficient vectorized implementation. For now, just use nested for loops to better understand the algorithm, and for easier debugging.\n", "\n", "The function `softmax()` is provided, and has already been imported." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2322, "status": "ok", "timestamp": 1611738741724, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "O_BzrO-TcFIv" }, "outputs": [], "source": [ "# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n", "# GRADED FUNCTION: model\n", "\n", "def model(X, Y, word_to_vec_map, learning_rate = 0.01, num_iterations = 200):\n", " \"\"\"\n", " Model to train word vector representations in numpy.\n", " \n", " Arguments:\n", " X -- input data, numpy array of sentences as strings, of shape (m, 1)\n", " Y -- labels, numpy array of integers between 0 and 7, numpy-array of shape (m, 1)\n", " word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation\n", " learning_rate -- learning_rate for the stochastic gradient descent algorithm\n", " num_iterations -- number of iterations\n", " \n", " Returns:\n", " pred -- vector of predictions, numpy-array of shape (m, 1)\n", " W -- weight matrix of the softmax layer, of shape (n_y, n_h)\n", " b -- bias of the softmax layer, of shape (n_y,)\n", " \"\"\"\n", " \n", " # Get a valid word contained in the word_to_vec_map \n", " any_word = list(word_to_vec_map.keys())[0]\n", " \n", " # Initialize cost. It is needed during grading\n", " cost = 0\n", " \n", " # Define number of training examples\n", " m = Y.shape[0] # number of training examples\n", " n_y = len(np.unique(Y)) # number of classes \n", " n_h = word_to_vec_map[any_word].shape[0] # dimensions of the GloVe vectors \n", " \n", " # Initialize parameters using Xavier initialization\n", " W = np.random.randn(n_y, n_h) / np.sqrt(n_h)\n", " b = np.zeros((n_y,))\n", " \n", " # Convert Y to Y_onehot with n_y classes\n", " Y_oh = convert_to_one_hot(Y, C = n_y) \n", " \n", " # Optimization loop\n", " for t in range(num_iterations): # Loop over the number of iterations\n", " for i in range(m): # Loop over the training examples\n", " \n", " ### START CODE HERE ### (β‰ˆ 4 lines of code)\n", " # Average the word vectors of the words from the i'th training example\n", " avg = sentence_to_avg(X[i], word_to_vec_map)\n", "\n", " # Forward propagate the avg through the softmax layer\n", " z = np.add(np.dot(W,avg),b)\n", " a = softmax(z)\n", "\n", " # Compute cost using the i'th training label's one hot representation and \"A\" (the output of the softmax)\n", " cost = -np.sum(np.dot(Y_oh[i], np.log(a)))\n", " ### END CODE HERE ###\n", " \n", " # Compute gradients \n", " dz = a - Y_oh[i]\n", " dW = np.dot(dz.reshape(n_y,1), avg.reshape(1, n_h))\n", " db = dz\n", "\n", " # Update parameters with Stochastic Gradient Descent\n", " W = W - learning_rate * dW\n", " b = b - learning_rate * db\n", " \n", " if t % 10 == 0:\n", " print(\"Epoch: \" + str(t) + \" --- cost = \" + str(cost))\n", " pred = predict(X, Y, W, b, word_to_vec_map) #predict is defined in emo_utils.py\n", "\n", " return pred, W, b" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNIT TEST\n", "def model_test(target):\n", " # Create a controlled word to vec map\n", " word_to_vec_map = {'a': [3, 3], 'synonym_of_a': [3, 3], 'a_nw': [2, 4], 'a_s': [3, 2], 'a_n': [3, 4], \n", " 'c': [-2, 1], 'c_n': [-2, 2],'c_ne': [-1, 2], 'c_e': [-1, 1], 'c_se': [-1, 0], \n", " 'c_s': [-2, 0], 'c_sw': [-3, 0], 'c_w': [-3, 1], 'c_nw': [-3, 2]\n", " }\n", " # Convert lists to np.arrays\n", " for key in word_to_vec_map.keys():\n", " word_to_vec_map[key] = np.array(word_to_vec_map[key])\n", " \n", " # Training set. Sentences composed of a_* words will be of class 0 and sentences composed of c_* words will be of class 1\n", " X = np.asarray(['a a_s synonym_of_a a_n c_sw', 'a a_s a_n c_sw', 'a_s a a_n', 'synonym_of_a a a_s a_n c_sw', \" a_s a_n\",\n", " \" a a_s a_n c \", \" a_n a c c c_e\",\n", " 'c c_nw c_n c c_ne', 'c_e c c_se c_s', 'c_nw c a_s c_e c_e', 'c_e a_nw c_sw', 'c_sw c c_ne c_ne'])\n", " \n", " Y = np.asarray([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])\n", " \n", " np.random.seed(10)\n", " pred, W, b = model(X, Y, word_to_vec_map, 0.0025, 110)\n", " \n", " assert W.shape == (2, 2), \"W must be of shape 2 x 2\"\n", " assert np.allclose(pred.transpose(), Y), \"Model must give a perfect accuracy\"\n", " assert np.allclose(b[0], -1 * b[1]), \"b should be symmetric in this example\"\n", " \n", " print(\"\\033[92mAll tests passed!\")\n", " \n", "model_test(model)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 2416, "status": "ok", "timestamp": 1611738747239, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "n7bWQtarcFIv", "outputId": "bf9c836f-a330-47b7-aa79-0e18e3c3d2fc" }, "outputs": [], "source": [ "print(X_train.shape)\n", "print(Y_train.shape)\n", "print(np.eye(5)[Y_train.reshape(-1)].shape)\n", "print(X_train[0])\n", "print(type(X_train))\n", "Y = np.asarray([5, 0, 0, 5, 4, 4, 4, 6, 6, 4, 1, 1, 5, 6, 6, 3, 6, 3, 4, 4])\n", "print(Y.shape)\n", "\n", "X = np.asarray(['I am going to the bar tonight', 'I love you', 'miss you my dear',\n", " 'Lets go party and have drinks','Congrats on the new job','Congratulations',\n", " 'I am so happy for you', 'Why are you feeling bad', 'What is wrong with you',\n", " 'You totally deserve this prize', 'Let us go play football',\n", " 'Are you down for football this afternoon', 'Work hard play harder',\n", " 'It is surprising how people can be dumb sometimes',\n", " 'I am very disappointed','It is the best day in my life',\n", " 'I think I will end up alone','My life is so boring','Good job',\n", " 'Great so awesome'])\n", "\n", "print(X.shape)\n", "print(np.eye(5)[Y_train.reshape(-1)].shape)\n", "print(type(X_train))\n" ] }, { "cell_type": "markdown", "metadata": { "id": "KvdG05pgcFIw" }, "source": [ "Run the next cell to train your model and learn the softmax parameters (W, b). **The training process will take about 5 minutes**" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 3817, "status": "ok", "timestamp": 1611738757775, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "umWTqRcpcFIw", "outputId": "7b74cb94-e98c-4936-98bc-693a3bb5f34e", "scrolled": true }, "outputs": [], "source": [ "np.random.seed(1)\n", "pred, W, b = model(X_train, Y_train, word_to_vec_map)\n", "print(pred)" ] }, { "cell_type": "markdown", "metadata": { "id": "ygumNDIUcFIx" }, "source": [ "Great! Your model has pretty high accuracy on the training set. Now see how it does on the test set:" ] }, { "cell_type": "markdown", "metadata": { "id": "O862gcUicFIx" }, "source": [ "\n", "### 1.5 - Examining Test Set Performance \n", "\n", "Note that the `predict` function used here is defined in `emo_util.spy`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 3704, "status": "ok", "timestamp": 1611738776291, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "yhb6CzhrcFIx", "outputId": "08d07fd0-55c2-4eff-d570-2562deb0570b", "scrolled": true }, "outputs": [], "source": [ "print(\"Training set:\")\n", "pred_train = predict(X_train, Y_train, W, b, word_to_vec_map)\n", "print('Test set:')\n", "pred_test = predict(X_test, Y_test, W, b, word_to_vec_map)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def predict_single(sentence, W=W, b=b, word_to_vec_map=word_to_vec_map):\n", " \"\"\"\n", " Given X (sentences) and Y (emoji indices), predict emojis and compute the accuracy of your model over the given set.\n", " \n", " Arguments:\n", " X -- input data containing sentences, numpy array of shape (m, None)\n", " Y -- labels, containing index of the label emoji, numpy array of shape (m, 1)\n", " \n", " Returns:\n", " pred -- numpy array of shape (m, 1) with your predictions\n", " \"\"\"\n", "\n", " any_word = list(word_to_vec_map.keys())[0]\n", " # number of classes \n", " n_h = word_to_vec_map[any_word].shape[0] \n", " \n", " # Split jth test example (sentence) into list of lower case words\n", " words = sentence.lower().split()\n", "\n", " # Average words' vectors\n", " avg = np.zeros((n_h,))\n", " count = 0\n", " for w in words:\n", " if w in word_to_vec_map:\n", " avg += word_to_vec_map[w]\n", " count += 1\n", "\n", " if count > 0:\n", " avg = avg / count\n", "\n", " # Forward propagation\n", " Z = np.dot(W, avg) + b\n", " A = softmax(Z)\n", " pred = np.argmax(A)\n", " \n", " \n", " return pred" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "label_to_emoji(int(predict_single(\"I love you\")))" ] }, { "cell_type": "markdown", "metadata": { "id": "hwmrm-aDcFIy" }, "source": [ "**Note**:\n", "* Random guessing would have had 20% accuracy, given that there are 5 classes. (1/5 = 20%).\n", "* This is pretty good performance after training on only 127 examples. \n", "\n", "\n", "#### The Model Matches Emojis to Relevant Words\n", "In the training set, the algorithm saw the sentence \n", ">\"I love you.\" \n", "\n", "with the label ❀️. \n", "* You can check that the word \"adore\" does not appear in the training set. \n", "* Nonetheless, let's see what happens if you write \"I adore you.\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 1909, "status": "ok", "timestamp": 1611738785398, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "tvCl7fUvcFIz", "outputId": "a3913da3-85df-466d-dd8f-520245d495fc", "scrolled": true }, "outputs": [], "source": [ "X_my_sentences = np.array([\"i adore you\", \"i love you\", \"funny lol\", \"lets play with a ball\", \"food is ready\", \"not feeling happy\"])\n", "Y_my_labels = np.array([[0], [0], [2], [1], [4],[3]])\n", "\n", "pred = predict(X_my_sentences, Y_my_labels , W, b, word_to_vec_map)\n", "print_predictions(X_my_sentences, pred)" ] }, { "cell_type": "markdown", "metadata": { "id": "ZyC-BGqKcFI0" }, "source": [ "Amazing! \n", "* Because *adore* has a similar embedding as *love*, the algorithm has generalized correctly even to a word it has never seen before. \n", "* Words such as *heart*, *dear*, *beloved* or *adore* have embedding vectors similar to *love*. \n", " * Feel free to modify the inputs above and try out a variety of input sentences. \n", " * How well does it work?\n", "\n", "#### Word Ordering isn't Considered in this Model\n", "* Note that the model doesn't get the following sentence correct:\n", ">\"not feeling happy\" \n", "\n", "* This algorithm ignores word ordering, so is not good at understanding phrases like \"not happy.\" \n", "\n", "#### Confusion Matrix\n", "* Printing the confusion matrix can also help understand which classes are more difficult for your model. \n", "* 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).\n", "\n", "Print the confusion matrix below:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 433 }, "executionInfo": { "elapsed": 2061, "status": "ok", "timestamp": 1611738816883, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "Ab9aH9IQcFI1", "outputId": "d8cfc4cc-bbdc-487b-8efc-3d9a3cdbdd06" }, "outputs": [], "source": [ "# START SKIP FOR GRADING\n", "print(Y_test.shape)\n", "print(' '+ label_to_emoji(0)+ ' ' + label_to_emoji(1) + ' ' + label_to_emoji(2)+ ' ' + label_to_emoji(3)+' ' + label_to_emoji(4))\n", "print(pd.crosstab(Y_test, pred_test.reshape(56,), rownames=['Actual'], colnames=['Predicted'], margins=True))\n", "plot_confusion_matrix(Y_test, pred_test)\n", "# END SKIP FOR GRADING" ] }, { "cell_type": "markdown", "metadata": { "id": "Zm2o8SQIcFI1" }, "source": [ "What you should remember:\n", "- Even with a mere 127 training examples, you can get a reasonably good model for Emojifying. \n", " - This is due to the generalization power word vectors gives you. \n", "- Emojify-V1 will perform poorly on sentences such as *\"This movie is not good and not enjoyable\"* \n", " - It doesn't understand combinations of words.\n", " - It just averages all the words' embedding vectors together, without considering the ordering of words. \n", "\n", " \n", "**Not to worry! You will build a better algorithm in the next section!**" ] }, { "cell_type": "markdown", "metadata": { "id": "BEeTqpjlcFI2" }, "source": [ "\n", "## 2 - Emojifier-V2: Using LSTMs in Keras \n", "\n", "You're going to build an LSTM model that takes word **sequences** as input! This model will be able to account for word ordering. \n", "\n", "Emojifier-V2 will continue to use pre-trained word embeddings to represent words. You'll feed word embeddings into an LSTM, and the LSTM will learn to predict the most appropriate emoji. " ] }, { "cell_type": "markdown", "metadata": { "id": "CPIihtFVFEbz" }, "source": [ "### Packages\n", "\n", "Run the following cell to load the Keras packages you'll need:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2501, "status": "ok", "timestamp": 1611738953388, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "uZ-fy9fYcFI3" }, "outputs": [], "source": [ "import numpy as np\n", "import tensorflow\n", "np.random.seed(0)\n", "from tensorflow.keras.models import Model\n", "from tensorflow.keras.layers import Dense, Input, Dropout, LSTM, Activation\n", "from tensorflow.keras.layers import Embedding\n", "from tensorflow.keras.preprocessing import sequence\n", "from tensorflow.keras.initializers import glorot_uniform\n", "np.random.seed(1)" ] }, { "cell_type": "markdown", "metadata": { "id": "P7LJvriXcFI3" }, "source": [ "\n", "### 2.1 - Model Overview\n", "\n", "Here is the Emojifier-v2 you will implement:\n", "\n", "
\n", "
Figure 3: Emojifier-V2. A 2-layer LSTM sequence classifier.
" ] }, { "cell_type": "markdown", "metadata": { "id": "-3W3WTbpcFI3" }, "source": [ "\n", "### 2.2 Keras and Mini-batching \n", "\n", "In this exercise, you 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**. \n", "\n", "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.\n", " \n", "#### Padding Handles Sequences of Varying Length\n", "* The common solution to handling sequences of **different length** is to use padding. Specifically:\n", " * Set a maximum sequence length\n", " * Pad all sequences to have the same length. \n", " \n", "#### Example of Padding:\n", "* Given a maximum sequence length of 20, you could pad every sentence with \"0\"s so that each input sentence is of length 20. \n", "* Thus, the sentence \"I love you\" would be represented as $(e_{I}, e_{love}, e_{you}, \\vec{0}, \\vec{0}, \\ldots, \\vec{0})$. \n", "* In this example, any sentences longer than 20 words would have to be truncated. \n", "* One way to choose the maximum sequence length is to just pick the length of the longest sentence in the training set. " ] }, { "cell_type": "markdown", "metadata": { "id": "QuwbNWS0cFI4" }, "source": [ "\n", "### 2.3 - The Embedding Layer\n", "\n", "In Keras, the embedding matrix is represented as a \"layer.\"\n", "\n", "* The embedding matrix maps word indices to embedding vectors.\n", " * The word indices are positive integers.\n", " * The embedding vectors are dense vectors of fixed size.\n", " * A \"dense\" vector is the opposite of a sparse vector. It means that most of its values are non-zero. As a counter-example, a one-hot encoded vector is not \"dense.\"\n", "* The embedding matrix can be derived in two ways:\n", " * Training a model to derive the embeddings from scratch. \n", " * Using a pretrained embedding.\n", " \n", "#### Using and Updating Pre-trained Embeddings\n", "In this section, you'll create an [Embedding()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding) layer in Keras\n", "\n", "* You will initialize the Embedding layer with GloVe 50-dimensional vectors. \n", "* In the code below, you'll observe how Keras allows you to either train or leave this layer fixed. \n", " * Because your training set is quite small, you'll leave the GloVe embeddings fixed instead of updating them." ] }, { "cell_type": "markdown", "metadata": { "id": "zhyVzuThcFI4" }, "source": [ "#### Inputs and Outputs to the Embedding Layer\n", "\n", "* The `Embedding()` layer's input is an integer matrix of size **(batch size, max input length)**. \n", " * This input corresponds to sentences converted into lists of indices (integers).\n", " * The largest integer (the highest word index) in the input should be no larger than the vocabulary size.\n", "* The embedding layer outputs an array of shape (batch size, max input length, dimension of word vectors).\n", "\n", "* The figure shows the propagation of two example sentences through the embedding layer. \n", " * Both examples have been zero-padded to a length of `max_len=5`.\n", " * The word embeddings are 50 units in length.\n", " * The final dimension of the representation is `(2,max_len,50)`. \n", "\n", "\n", "
Figure 4: Embedding layer
" ] }, { "cell_type": "markdown", "metadata": { "id": "KnoTtNWBcFI5" }, "source": [ "#### Prepare the Input Sentences\n", "\n", "\n", "### Exercise 3 - sentences_to_indices\n", "\n", "Implement `sentences_to_indices`\n", "\n", "This function processes an array of sentences X and returns inputs to the embedding layer:\n", "\n", "* Convert each training sentences into a list of indices (the indices correspond to each word in the sentence)\n", "* Zero-pad all these lists so that their length is the length of the longest sentence.\n", " \n", "#### Additional Hints:\n", "* 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 incrementing `j` explicitly." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 2291, "status": "ok", "timestamp": 1611738965576, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "8cMm64iWcFI5", "outputId": "f82cb8b2-991c-44ae-9c81-7a5235edeea2" }, "outputs": [], "source": [ "for idx, val in enumerate([\"I\", \"like\", \"learning\"]):\n", " print(idx, val)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2881, "status": "ok", "timestamp": 1611738972334, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "Z0SixlIwcFI5" }, "outputs": [], "source": [ "# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n", "# GRADED FUNCTION: sentences_to_indices\n", "\n", "def sentences_to_indices(X, word_to_index, max_len):\n", " \"\"\"\n", " Converts an array of sentences (strings) into an array of indices corresponding to words in the sentences.\n", " The output shape should be such that it can be given to `Embedding()` (described in Figure 4). \n", " \n", " Arguments:\n", " X -- array of sentences (strings), of shape (m, 1)\n", " word_to_index -- a dictionary containing the each word mapped to its index\n", " max_len -- maximum number of words in a sentence. You can assume every sentence in X is no longer than this. \n", " \n", " Returns:\n", " X_indices -- array of indices corresponding to words in the sentences from X, of shape (m, max_len)\n", " \"\"\"\n", " \n", " m = X.shape[0] # number of training examples\n", " \n", " ### START CODE HERE ###\n", " # Initialize X_indices as a numpy matrix of zeros and the correct shape (β‰ˆ 1 line)\n", " X_indices = np.zeros([m,max_len])\n", " \n", " for i in range(m): # loop over training examples\n", " \n", " # Convert the ith training sentence in lower case and split is into words. You should get a list of words.\n", " sentence_words = X[i].lower().split()\n", " \n", " # Initialize j to 0\n", " j = 0\n", " \n", " # Loop over the words of sentence_words\n", "\n", " for w in sentence_words:\n", " # if w exists in the word_to_index dictionary\n", " if w in word_to_index:\n", " # Set the (i,j)th entry of X_indices to the index of the correct word.\n", " X_indices[i, j] = word_to_index[w]\n", " # Increment j to j + 1\n", " j = j+1\n", " \n", " ### END CODE HERE ###\n", " \n", " return X_indices" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNIT TEST\n", "def sentences_to_indices_test(target):\n", " \n", " # Create a word_to_index dictionary\n", " word_to_index = {}\n", " for idx, val in enumerate([\"i\", \"like\", \"learning\", \"deep\", \"machine\", \"love\", \"smile\", 'Β΄0.=']):\n", " word_to_index[val] = idx;\n", " \n", " max_len = 4\n", " sentences = np.array([\"I like deep learning\", \"deep Β΄0.= love machine\", \"machine learning smile\"]);\n", " indexes = target(sentences, word_to_index, max_len)\n", " print(indexes)\n", " \n", " assert type(indexes) == np.ndarray, \"Wrong type. Use np arrays in the function\"\n", " assert indexes.shape == (sentences.shape[0], max_len), \"Wrong shape of ouput matrix\"\n", " assert np.allclose(indexes, [[0, 1, 3, 2],\n", " [3, 7, 5, 4],\n", " [4, 2, 6, 0]]), \"Wrong values. Debug with the given examples\"\n", " \n", " print(\"\\033[92mAll tests passed!\")\n", " \n", "sentences_to_indices_test(sentences_to_indices)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected value**\n", "\n", "```\n", "[[0, 1, 3, 2],\n", " [3, 7, 5, 4],\n", " [4, 2, 6, 0]]\n", "```" ] }, { "cell_type": "markdown", "metadata": { "id": "reyHmseecFI6" }, "source": [ "Run the following cell to check what `sentences_to_indices()` does, and take a look at your results." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 1992, "status": "ok", "timestamp": 1611738982161, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "oBL1PMOCcFI6", "outputId": "6781359c-bafd-4ab5-a477-f8a5a86ea219" }, "outputs": [], "source": [ "X1 = np.array([\"funny lol\", \"lets play baseball\", \"food is ready for you\"])\n", "X1_indices = sentences_to_indices(X1, word_to_index, max_len=5)\n", "print(\"X1 =\", X1)\n", "print(\"X1_indices =\\n\", X1_indices)" ] }, { "cell_type": "markdown", "metadata": { "id": "0OJPAEM5cFI6" }, "source": [ "#### Build Embedding Layer\n", "\n", "Now you'll build the `Embedding()` layer in Keras, using pre-trained word vectors. \n", "\n", "* The embedding layer takes as input a list of word indices.\n", " * `sentences_to_indices()` creates these word indices.\n", "* The embedding layer will return the word embeddings for a sentence. \n", "\n", "\n", "### Exercise 4 - pretrained_embedding_layer\n", "\n", "Implement `pretrained_embedding_layer()` with these steps:\n", "\n", "1. Initialize the embedding matrix as a numpy array of zeros.\n", " * The embedding matrix has a row for each unique word in the vocabulary.\n", " * There is one additional row to handle \"unknown\" words.\n", " * So vocab_size is the number of unique words plus one.\n", " * Each row will store the vector representation of one word. \n", " * For example, one row may be 50 positions long if using GloVe word vectors.\n", " * In the code below, `emb_dim` represents the length of a word embedding.\n", "2. Fill in each row of the embedding matrix with the vector representation of a word\n", " * Each word in `word_to_index` is a string.\n", " * `word_to_vec_map` is a dictionary where the keys are strings and the values are the word vectors.\n", "3. Define the Keras embedding layer. \n", " * Use [Embedding()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding). \n", " * The input dimension is equal to the vocabulary length (number of unique words plus one).\n", " * The output dimension is equal to the number of positions in a word embedding.\n", " * Make this layer's embeddings fixed.\n", " * If you were to set `trainable = True`, then it will allow the optimization algorithm to modify the values of the word embeddings.\n", " * In this case, you don't want the model to modify the word embeddings.\n", "4. Set the embedding weights to be equal to the embedding matrix.\n", " * Note that this is part of the code is already completed for you and does not need to be modified! " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2160, "status": "ok", "timestamp": 1611738992486, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "XBlEpiVkcFI7" }, "outputs": [], "source": [ "# UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n", "# GRADED FUNCTION: pretrained_embedding_layer\n", "\n", "def pretrained_embedding_layer(word_to_vec_map, word_to_index):\n", " \"\"\"\n", " Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors.\n", " \n", " Arguments:\n", " word_to_vec_map -- dictionary mapping words to their GloVe vector representation.\n", " word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words)\n", "\n", " Returns:\n", " embedding_layer -- pretrained layer Keras instance\n", " \"\"\"\n", " \n", " vocab_size = len(word_to_index) + 1 # adding 1 to fit Keras embedding (requirement)\n", " any_word = list(word_to_vec_map.keys())[0]\n", " emb_dim = word_to_vec_map[any_word].shape[0] # define dimensionality of your GloVe word vectors (= 50)\n", " \n", " ### START CODE HERE ###\n", " # Step 1\n", " # Initialize the embedding matrix as a numpy array of zeros.\n", " # See instructions above to choose the correct shape.\n", " emb_matrix = np.zeros([vocab_size,emb_dim])\n", " \n", " # Step 2\n", " # Set each row \"idx\" of the embedding matrix to be \n", " # the word vector representation of the idx'th word of the vocabulary\n", " for word, idx in word_to_index.items():\n", " emb_matrix[idx, :] = word_to_vec_map[word]\n", "\n", " # Step 3\n", " # Define Keras embedding layer with the correct input and output sizes\n", " # Make it non-trainable.\n", " embedding_layer = Embedding(vocab_size, emb_dim ,trainable = False)\n", " ### END CODE HERE ###\n", "\n", " # Step 4 (already done for you; please do not modify)\n", " # Build the embedding layer, it is required before setting the weights of the embedding layer. \n", " embedding_layer.build((None,)) # Do not modify the \"None\". This line of code is complete as-is.\n", " \n", " # Set the weights of the embedding layer to the embedding matrix. Your layer is now pretrained.\n", " embedding_layer.set_weights([emb_matrix])\n", " \n", " return embedding_layer" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNIT TEST\n", "def pretrained_embedding_layer_test(target):\n", " # Create a controlled word to vec map\n", " word_to_vec_map = {'a': [3, 3], 'synonym_of_a': [3, 3], 'a_nw': [2, 4], 'a_s': [3, 2], 'a_n': [3, 4], \n", " 'c': [-2, 1], 'c_n': [-2, 2],'c_ne': [-1, 2], 'c_e': [-1, 1], 'c_se': [-1, 0], \n", " 'c_s': [-2, 0], 'c_sw': [-3, 0], 'c_w': [-3, 1], 'c_nw': [-3, 2]\n", " }\n", " # Convert lists to np.arrays\n", " for key in word_to_vec_map.keys():\n", " word_to_vec_map[key] = np.array(word_to_vec_map[key])\n", " \n", " # Create a word_to_index dictionary\n", " word_to_index = {}\n", " for idx, val in enumerate(list(word_to_vec_map.keys())):\n", " word_to_index[val] = idx;\n", " \n", " np.random.seed(1)\n", " embedding_layer = target(word_to_vec_map, word_to_index)\n", " \n", " assert type(embedding_layer) == Embedding, \"Wrong type\"\n", " assert embedding_layer.input_dim == len(list(word_to_vec_map.keys())) + 1, \"Wrong input shape\"\n", " assert embedding_layer.output_dim == len(word_to_vec_map['a']), \"Wrong output shape\"\n", " assert np.allclose(embedding_layer.get_weights(), \n", " [[[ 3, 3], [ 3, 3], [ 2, 4], [ 3, 2], [ 3, 4],\n", " [-2, 1], [-2, 2], [-1, 2], [-1, 1], [-1, 0],\n", " [-2, 0], [-3, 0], [-3, 1], [-3, 2], [ 0, 0]]]), \"Wrong vaulues\"\n", " print(\"\\033[92mAll tests passed!\")\n", " \n", " \n", "pretrained_embedding_layer_test(pretrained_embedding_layer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 6068, "status": "ok", "timestamp": 1611739002394, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "Gn4iGb0AcFI7", "outputId": "5bab44b5-bf23-4c6e-f891-429e8be34981" }, "outputs": [], "source": [ "embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index)\n", "print(\"weights[0][1][1] =\", embedding_layer.get_weights()[0][1][1])\n", "print(\"Input_dim\", embedding_layer.input_dim)\n", "print(\"Output_dim\",embedding_layer.output_dim)" ] }, { "cell_type": "markdown", "metadata": { "id": "uEsWnZ_2cFI7" }, "source": [ "\n", "### 2.4 - Building the Emojifier-V2\n", "\n", "Now you're ready to build the Emojifier-V2 model, in which you feed the embedding layer's output to an LSTM network!\n", "\n", "
\n", "
Figure 3: Emojifier-v2. A 2-layer LSTM sequence classifier.
\n", "\n", "\n", "\n", "### Exercise 5 - Emojify_V2\n", "\n", "Implement `Emojify_V2()`\n", "\n", "This function builds a Keras graph of the architecture shown in Figure (3). \n", "\n", "* The model takes as input an array of sentences of shape (`m`, `max_len`, ) defined by `input_shape`. \n", "* The model outputs a softmax probability vector of shape (`m`, `C = 5`). \n", "\n", "* You may need to use the following Keras layers:\n", " * [Input()](https://www.tensorflow.org/api_docs/python/tf/keras/Input)\n", " * Set the `shape` and `dtype` parameters.\n", " * The inputs are integers, so you can specify the data type as a string, 'int32'.\n", " * [LSTM()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM)\n", " * Set the `units` and `return_sequences` parameters.\n", " * [Dropout()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dropout)\n", " * Set the `rate` parameter.\n", " * [Dense()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense)\n", " * Set the `units`, \n", " * Note that `Dense()` has an `activation` parameter. For the purposes of passing the autograder, please do not set the activation within `Dense()`. Use the separate `Activation` layer to do so.\n", " * [Activation()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Activation)\n", " * You can pass in the activation of your choice as a lowercase string.\n", " * [Model()](https://www.tensorflow.org/api_docs/python/tf/keras/Model)\n", " * Set `inputs` and `outputs`.\n", "\n", "\n", "#### Additional Hints\n", "* 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.\n", "\n", "```Python\n", "# How to use Keras layers in two lines of code\n", "dense_object = Dense(units = ...)\n", "X = dense_object(inputs)\n", "\n", "# How to use Keras layers in one line of code\n", "X = Dense(units = ...)(inputs)\n", "```\n", "\n", "* The `embedding_layer` that is returned by `pretrained_embedding_layer` is a layer object that can be called as a function, passing in a single argument (sentence indices).\n", "\n", "* Here is some sample code in case you're stuck: 😊\n", "```Python\n", "raw_inputs = Input(shape=(maxLen,), dtype='int32')\n", "preprocessed_inputs = ... # some pre-processing\n", "X = LSTM(units = ..., return_sequences= ...)(processed_inputs)\n", "X = Dropout(rate = ..., )(X)\n", "...\n", "X = Dense(units = ...)(X)\n", "X = Activation(...)(X)\n", "model = Model(inputs=..., outputs=...)\n", "...\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 3214, "status": "ok", "timestamp": 1611739012958, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "Pb2ugsSUcFI7" }, "outputs": [], "source": [ "# UNQ_C5 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n", "# GRADED FUNCTION: Emojify_V2\n", "\n", "def Emojify_V2(input_shape, word_to_vec_map, word_to_index):\n", " \"\"\"\n", " Function creating the Emojify-v2 model's graph.\n", " \n", " Arguments:\n", " input_shape -- shape of the input, usually (max_len,)\n", " word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation\n", " word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words)\n", "\n", " Returns:\n", " model -- a model instance in Keras\n", " \"\"\"\n", " \n", " ### START CODE HERE ###\n", " # Define sentence_indices as the input of the graph.\n", " # It should be of shape input_shape and dtype 'int32' (as it contains indices, which are integers).\n", " sentence_indices = Input(shape=input_shape,dtype='int32')\n", " \n", " # Create the embedding layer pretrained with GloVe Vectors (β‰ˆ1 line)\n", " embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index)\n", " \n", " # Propagate sentence_indices through your embedding layer\n", " # (See additional hints in the instructions).\n", " embeddings = embedding_layer(sentence_indices) \n", " \n", " # Propagate the embeddings through an LSTM layer with 128-dimensional hidden state\n", " # The returned output should be a batch of sequences, So, set return_sequences = True\n", " # If return_sequences = False, the LSTM returns only tht last output in output sequence\n", " X = LSTM(units=128,return_sequences = True)(embeddings)\n", " # Add dropout with a probability of 0.5\n", " X = Dropout(0.5)(X)\n", " # Propagate X trough another LSTM layer with 128-dimensional hidden state\n", " # The returned output should be a single hidden state, not a batch of sequences.\n", " X = LSTM(units=128,return_sequences = False)(X)\n", " # Add dropout with a probability of 0.5\n", " X = Dropout(0.5)(X)\n", " # Propagate X through a Dense layer with 5 units\n", " X = Dense(5)(X)\n", " # Add a softmax activation\n", " X = Activation('softmax')(X)\n", " \n", " # Create Model instance which converts sentence_indices into X.\n", " model = Model(inputs=sentence_indices,outputs=X)\n", " \n", " ### END CODE HERE ###\n", " \n", " return model" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNIT TEST\n", "def Emojify_V2_test(target):\n", " # Create a controlled word to vec map\n", " word_to_vec_map = {'a': [3, 3], 'synonym_of_a': [3, 3], 'a_nw': [2, 4], 'a_s': [3, 2], 'a_n': [3, 4], \n", " 'c': [-2, 1], 'c_n': [-2, 2],'c_ne': [-1, 2], 'c_e': [-1, 1], 'c_se': [-1, 0], \n", " 'c_s': [-2, 0], 'c_sw': [-3, 0], 'c_w': [-3, 1], 'c_nw': [-3, 2]\n", " }\n", " # Convert lists to np.arrays\n", " for key in word_to_vec_map.keys():\n", " word_to_vec_map[key] = np.array(word_to_vec_map[key])\n", " \n", " # Create a word_to_index dictionary\n", " word_to_index = {}\n", " for idx, val in enumerate(list(word_to_vec_map.keys())):\n", " word_to_index[val] = idx;\n", " \n", " maxLen = 4\n", " model = target((maxLen,), word_to_vec_map, word_to_index)\n", " \n", " expectedModel = [['InputLayer', [(None, 4)], 0], ['Embedding', (None, 4, 2), 30], ['LSTM', (None, 4, 128), 67072, (None, 4, 2), 'tanh', True], ['Dropout', (None, 4, 128), 0, 0.5], ['LSTM', (None, 128), 131584, (None, 4, 128), 'tanh', False], ['Dropout', (None, 128), 0, 0.5], ['Dense', (None, 5), 645, 'linear'], ['Activation', (None, 5), 0]]\n", " comparator(summary(model), expectedModel)\n", " \n", " \n", "Emojify_V2_test(Emojify_V2)" ] }, { "cell_type": "markdown", "metadata": { "id": "-VamRAKtcFI8" }, "source": [ "Run the following cell to create your model and check its summary. \n", "\n", "* Because all sentences in the dataset are less than 10 words, `max_len = 10` was chosen. \n", "* You should see that your architecture uses 20,223,927 parameters, of which 20,000,050 (the word embeddings) are non-trainable, with the remaining 223,877 being trainable. \n", "* Because your 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. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 3127, "status": "ok", "timestamp": 1611739019596, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "8fLhXJ9ucFI8", "outputId": "02d98359-a43b-4780-bb17-3d36e060aa86", "scrolled": false }, "outputs": [], "source": [ "model = Emojify_V2((maxLen,), word_to_vec_map, word_to_index)\n", "model.summary()" ] }, { "cell_type": "markdown", "metadata": { "id": "mKIsZqqicFI8" }, "source": [ "#### Compile the Model \n", "\n", "As usual, after creating your model in Keras, you need to compile it and define what loss, optimizer and metrics you want to use. Compile your model using `categorical_crossentropy` loss, `adam` optimizer and `['accuracy']` metrics:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2041, "status": "ok", "timestamp": 1611739024847, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "aMf79f45cFI9" }, "outputs": [], "source": [ "model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])" ] }, { "cell_type": "markdown", "metadata": { "id": "mX6NORy7cFI9" }, "source": [ "\n", "### 2.5 - Train the Model \n", "\n", "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`). Thus, you 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)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2284, "status": "ok", "timestamp": 1611739029525, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "UgsBnWQqcFI-" }, "outputs": [], "source": [ "X_train_indices = sentences_to_indices(X_train, word_to_index, maxLen)\n", "Y_train_oh = convert_to_one_hot(Y_train, C = 5)" ] }, { "cell_type": "markdown", "metadata": { "id": "9fMyo0vqcFI_" }, "source": [ "Fit the Keras model on `X_train_indices` and `Y_train_oh`, using `epochs = 50` and `batch_size = 32`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "LtFpvyJicFI_", "scrolled": true }, "outputs": [], "source": [ "model.fit(X_train_indices, Y_train_oh, epochs = 100, batch_size = 32, shuffle=True)" ] }, { "cell_type": "markdown", "metadata": { "id": "gR2QJZAkcFJA" }, "source": [ "Your model should perform around **90% to 100% accuracy** on the training set. Exact model accuracy may vary! \n", "\n", "Run the following cell to evaluate your model on the test set: " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 2962, "status": "ok", "timestamp": 1611739058762, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "sIbcdVibcFJA", "outputId": "65b06e6c-415e-4038-c6fd-3839b3fd39f1", "scrolled": true }, "outputs": [], "source": [ "X_test_indices = sentences_to_indices(X_test, word_to_index, max_len = maxLen)\n", "Y_test_oh = convert_to_one_hot(Y_test, C = 5)\n", "loss, acc = model.evaluate(X_test_indices, Y_test_oh)\n", "print()\n", "print(\"Test accuracy = \", acc)" ] }, { "cell_type": "markdown", "metadata": { "id": "2d6y4sJbcFJA" }, "source": [ "You should get a test accuracy between 80% and 95%. Run the cell below to see the mislabelled examples: " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 1779, "status": "ok", "timestamp": 1611739122633, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "mjMyEGmYcFJC", "outputId": "0e87d217-d501-40d1-a6c7-71d567643d52", "scrolled": true }, "outputs": [], "source": [ "# This code allows you to see the mislabelled examples\n", "C = 5\n", "y_test_oh = np.eye(C)[Y_test.reshape(-1)]\n", "X_test_indices = sentences_to_indices(X_test, word_to_index, maxLen)\n", "pred = model.predict(X_test_indices)\n", "for i in range(len(X_test)):\n", " x = X_test_indices\n", " num = np.argmax(pred[i])\n", " if(num != Y_test[i]):\n", " print('Expected emoji:'+ label_to_emoji(Y_test[i]) + ' prediction: '+ X_test[i] + label_to_emoji(num).strip())" ] }, { "cell_type": "markdown", "metadata": { "id": "UGg00oBRcFJD" }, "source": [ "Now you can try it on your own example! Write your own sentence below:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 1780, "status": "ok", "timestamp": 1611739204630, "user": { "displayName": "Mubsi K", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64", "userId": "08094225471505108399" }, "user_tz": -300 }, "id": "wEgCsIE7cFJE", "outputId": "28d6942b-ad6b-461e-9904-191430145d85" }, "outputs": [], "source": [ "# Change the sentence below to see your prediction. Make sure all the words are in the Glove embeddings. \n", "x_test = np.array([\"What are you eating?\"])\n", "X_test_indices = sentences_to_indices(x_test, word_to_index, maxLen)\n", "print(x_test[0] +' '+ label_to_emoji(np.argmax(model.predict(X_test_indices))))" ] }, { "cell_type": "markdown", "metadata": { "id": "tT53ibgFcFJE" }, "source": [ "#### LSTM Version Accounts for Word Order\n", "* The Emojify-V1 model did not \"not feeling happy\" correctly, but your implementation of Emojify-V2 got it right! \n", " * If it didn't, be aware that Keras' outputs are slightly random each time, so this is probably why. \n", "* The current model still isn't very robust at understanding negation (such as \"not happy\")\n", " * This is because the training set is small and doesn't have a lot of examples of negation. \n", " * If the training set were larger, the LSTM model would be much better than the Emojify-V1 model at understanding more complex sentences. " ] }, { "cell_type": "markdown", "metadata": { "id": "0ysWCkrcFEb7" }, "source": [ "### Congratulations!\n", " \n", "You've completed this notebook, and harnessed the power of LSTMs to make your words more emotive! ❀️❀️❀️\n", "\n", "By now, you've: \n", "\n", "* Created an embedding matrix\n", "* Observed how negative sampling learns word vectors more efficiently than other methods\n", "* Experienced the advantages and disadvantages of the GloVe algorithm\n", "* And built a sentiment classifier using word embeddings! \n", "\n", "Cool! (or Emojified: 😎😎😎 ) " ] }, { "cell_type": "markdown", "metadata": { "id": "GgoBXYn3cFJE" }, "source": [ "What you should remember:\n", "- If you have an NLP task where the training set is small, using word embeddings can help your algorithm significantly. \n", "- Word embeddings allow your model to work on words in the test set that may not even appear in the training set. \n", "- Training sequence models in Keras (and in most other deep learning frameworks) requires a few important details:\n", " - To use mini-batches, the sequences need to be **padded** so that all the examples in a mini-batch have the **same length**. \n", " - An `Embedding()` layer can be initialized with pretrained values. \n", " - These values can be either fixed or trained further on your dataset. \n", " - If however your labeled dataset is small, it's usually not worth trying to train a large pre-trained set of embeddings. \n", " - `LSTM()` has a flag called `return_sequences` to decide if you would like to return every hidden states or only the last one. \n", " - You can use `Dropout()` right after `LSTM()` to regularize your network. " ] }, { "cell_type": "markdown", "metadata": { "id": "LUSzrFkYcFJF" }, "source": [ "\n", "### Input sentences:\n", "```Python\n", "\"Congratulations on finishing this assignment and building an Emojifier.\"\n", "\"We hope you're happy with what you've accomplished in this notebook!\"\n", "```\n", "### Output emojis:\n", "# πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€\n", "\n", "☁ πŸ‘‹πŸš€ ☁☁\n", "\n", " ✨ BYE-BYE!\n", " \n", "☁ ✨ 🎈\n", "\n", " ✨ ☁\n", " \n", " ✨\n", " \n", " ✨\n", " \n", "πŸŒΎβœ¨πŸ’¨ πŸƒ 🏠🏒 " ] }, { "cell_type": "markdown", "metadata": { "id": "vYoEQMCVcFJG" }, "source": [ "\n", "## 3 - Acknowledgments\n", "\n", "Thanks to Alison Darcy and the Woebot team for their advice on the creation of this assignment. \n", "* Woebot is a chatbot friend that is ready to speak with you 24/7. \n", "* Part of Woebot's technology uses word embeddings to understand the emotions of what you say. \n", "* You can chat with Woebot by going to http://woebot.io\n", "\n", "" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "accelerator": "GPU", "colab": { "collapsed_sections": [ "zhyVzuThcFI4", "LUSzrFkYcFJF" ], "name": "Solution_Emojify_v2a.ipynb", "provenance": [] }, "coursera": { "schema_names": [ "DLSC5W2-A2" ] }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 1 }