{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Improvise a Jazz Solo with an LSTM Network\n", "\n", "Welcome to your final programming assignment of this week! In this notebook, you will implement a model that uses an LSTM to generate music. At the end, you'll even be able to listen to your own music! \n", "\n", "\n", "\n", "**By the end of this assignment, you'll be able to:**\n", "\n", "- Apply an LSTM to a music generation task\n", "- Generate your own jazz music with deep learning\n", "- Use the flexible Functional API to create complex models\n", "\n", "This is going to be a fun one. Let's get started! " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Table of Contents\n", "\n", "- [Packages](#0)\n", "- [1 - Problem Statement](#1)\n", " - [1.1 - Dataset](#1-1)\n", " - [1.2 - Model Overview](#1-2)\n", "- [2 - Building the Model](#2)\n", " - [Exercise 1 - djmodel](#ex-1)\n", "- [3 - Generating Music](#3)\n", " - [3.1 - Predicting & Sampling](#3-1)\n", " - [Exercise 2 - music_inference_model](#ex-2)\n", " - [Exercise 3 - predict_and_sample](#ex-3)\n", " - [3.2 - Generate Music](#3-2)\n", "- [4 - References](#4) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Packages\n", "\n", "Run the following cell to load all the packages you'll need. This may take a few minutes!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import IPython\n", "import sys\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import tensorflow as tf\n", "\n", "from music21 import *\n", "from grammar import *\n", "from qa import *\n", "from preprocess import * \n", "from music_utils import *\n", "from data_utils import *\n", "from outputs import *\n", "from test_utils import *\n", "\n", "from tensorflow.keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector\n", "from tensorflow.keras.models import Model\n", "from tensorflow.keras.optimizers import Adam\n", "from tensorflow.keras.utils import to_categorical" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 1 - Problem Statement\n", "\n", "You would like to create a jazz music piece specially for a friend's birthday. However, you don't know how to play any instruments, or how to compose music. Fortunately, you know deep learning and will solve this problem using an LSTM network! \n", "\n", "You will train a network to generate novel jazz solos in a style representative of a body of performed work. 😎🎷\n", "\n", "\n", "### 1.1 - Dataset\n", "\n", "To get started, you'll train your algorithm on a corpus of Jazz music. Run the cell below to listen to a snippet of the audio from the training set:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "IPython.display.Audio('./data/30s_seq.wav')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The preprocessing of the musical data has been taken care of already, which for this notebook means it's been rendered in terms of musical \"values.\" \n", "\n", "#### What are musical \"values\"? (optional)\n", "You can informally think of each \"value\" as a note, which comprises a pitch and duration. For example, if you press down a specific piano key for 0.5 seconds, then you have just played a note. In music theory, a \"value\" is actually more complicated than this -- specifically, it also captures the information needed to play multiple notes at the same time. For example, when playing a music piece, you might press down two piano keys at the same time (playing multiple notes at the same time generates what's called a \"chord\"). But you don't need to worry about the details of music theory for this assignment. \n", "\n", "#### Music as a sequence of values\n", "\n", "* For the purposes of this assignment, all you need to know is that you'll obtain a dataset of values, and will use an RNN model to generate sequences of values. \n", "* Your music generation system will use 90 unique values. \n", "\n", "Run the following code to load the raw music data and preprocess it into values. This might take a few minutes!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "X, Y, n_values, indices_values, chords = load_music_utils('data/original_metheny.mid')\n", "print('number of training examples:', X.shape[0])\n", "print('Tx (length of sequence):', X.shape[1])\n", "print('total # of unique values:', n_values)\n", "print('shape of X:', X.shape)\n", "print('Shape of Y:', Y.shape)\n", "print('Number of chords', len(chords))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You have just loaded the following:\n", "\n", "- `X`: This is an (m, $T_x$, 90) dimensional array. \n", " - You have m training examples, each of which is a snippet of $T_x =30$ musical values. \n", " - At each time step, the input is one of 90 different possible values, represented as a one-hot vector. \n", " - For example, X[i,t,:] is a one-hot vector representing the value of the i-th example at time t. \n", "\n", "- `Y`: a $(T_y, m, 90)$ dimensional array\n", " - This is essentially the same as `X`, but shifted one step to the left (to the past). \n", " - Notice that the data in `Y` is **reordered** to be dimension $(T_y, m, 90)$, where $T_y = T_x$. This format makes it more convenient to feed into the LSTM later.\n", " - Similar to the dinosaur assignment, you're using the previous values to predict the next value.\n", " - So your sequence model will try to predict $y^{\\langle t \\rangle}$ given $x^{\\langle 1\\rangle}, \\ldots, x^{\\langle t \\rangle}$. \n", "\n", "- `n_values`: The number of unique values in this dataset. This should be 90. \n", "\n", "- `indices_values`: python dictionary mapping integers 0 through 89 to musical values.\n", "\n", "- `chords`: Chords used in the input midi" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 1.2 - Model Overview\n", "\n", "Here is the architecture of the model you'll use. It's similar to the Dinosaurus model, except that you'll implement it in Keras.\n", "\n", "\n", "
Figure 1: Basic LSTM model
\n", "\n", "\n", "* $X = (x^{\\langle 1 \\rangle}, x^{\\langle 2 \\rangle}, \\cdots, x^{\\langle T_x \\rangle})$ is a window of size $T_x$ scanned over the musical corpus. \n", "* Each $x^{\\langle t \\rangle}$ is an index corresponding to a value.\n", "* $\\hat{y}^{\\langle t \\rangle}$ is the prediction for the next value.\n", "* You'll be training the model on random snippets of 30 values taken from a much longer piece of music. \n", " - Thus, you won't bother to set the first input $x^{\\langle 1 \\rangle} = \\vec{0}$, since most of these snippets of audio start somewhere in the middle of a piece of music. \n", " - You're setting each of the snippets to have the same length $T_x = 30$ to make vectorization easier." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Overview of Section 2 and 3\n", "\n", "In Section 2, you're going to train a model that predicts the next note in a style similar to the jazz music it's trained on. The training is contained in the weights and biases of the model. \n", "\n", "Then, in Section 3, you're going to use those weights and biases in a new model that predicts a series of notes, and using the previous note to predict the next note. \n", "\n", "* The weights and biases are transferred to the new model using the global shared layers (`LSTM_cell`, `densor`, `reshaper`) described below" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 2 - Building the Model\n", "\n", "Now, you'll build and train a model that will learn musical patterns. \n", "* The model takes input X of shape $(m, T_x, 90)$ and labels Y of shape $(T_y, m, 90)$. \n", "* You'll use an LSTM with hidden states that have $n_{a} = 64$ dimensions." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# number of dimensions for the hidden state of each LSTM cell.\n", "n_a = 64 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Sequence generation uses a for-loop\n", "* If you're building an RNN where, at test time, the entire input sequence $x^{\\langle 1 \\rangle}, x^{\\langle 2 \\rangle}, \\ldots, x^{\\langle T_x \\rangle}$ is given in advance, then Keras has simple built-in functions to build the model. \n", "* However, for **sequence generation, at test time you won't know all the values of $x^{\\langle t\\rangle}$ in advance**.\n", "* Instead, you'll generate them one at a time using $x^{\\langle t\\rangle} = y^{\\langle t-1 \\rangle}$. \n", " * The input at time \"t\" is the prediction at the previous time step \"t-1\".\n", "* So you'll need to implement your own for-loop to iterate over the time steps. \n", "\n", "#### Shareable weights\n", "* The function `djmodel()` will call the LSTM layer $T_x$ times using a for-loop.\n", "* It is important that all $T_x$ copies have the same weights. \n", " - The $T_x$ steps should have shared weights that aren't re-initialized.\n", "* Referencing a globally defined shared layer will utilize the same layer-object instance at each time step.\n", "* The key steps for implementing layers with shareable weights in Keras are: \n", "1. Define the layer objects (you'll use global variables for this).\n", "2. Call these objects when propagating the input.\n", "\n", "#### 3 types of layers\n", "* The layer objects you need for global variables have been defined. \n", " * Just run the next cell to create them! \n", "* Please read the Keras documentation and understand these layers: \n", " - [Reshape()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Reshape): Reshapes an output to a certain shape.\n", " - [LSTM()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM): Long Short-Term Memory layer\n", " - [Dense()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense): A regular fully-connected neural network layer." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "n_values = 90 # number of music values\n", "reshaper = Reshape((1, n_values)) # Used in Step 2.B of djmodel(), below\n", "LSTM_cell = LSTM(n_a, return_state = True) # Used in Step 2.C\n", "densor = Dense(n_values, activation='softmax') # Used in Step 2.D" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* `reshaper`, `LSTM_cell` and `densor` are globally defined layer objects that you'll use to implement `djmodel()`. \n", "* In order to propagate a Keras tensor object X through one of these layers, use `layer_object()`.\n", " - For one input, use `layer_object(X)`\n", " - For more than one input, put the inputs in a list: `layer_object([X1,X2])`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Exercise 1 - djmodel\n", "\n", "Implement `djmodel()`.\n", "\n", "#### Inputs (given)\n", "\n", "* The `Input()` layer is used for defining the input `X` as well as the initial hidden state 'a0' and cell state `c0`.\n", "* The `shape` parameter takes a tuple that does not include the batch dimension (`m`).\n", " - For example,\n", " ```Python\n", " X = Input(shape=(Tx, n_values)) # X has 3 dimensions and not 2: (m, Tx, n_values)\n", " ```\n", " \n", "**Step 1: Outputs**\n", "\n", "* Create an empty list \"outputs\" to save the outputs of the LSTM Cell at every time step." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Step 2: Loop through time steps\n", "* Loop for $t \\in 1, \\ldots, T_x$:\n", "\n", "#### 2A. Select the 't' time-step vector from `X`.\n", "* X has the shape (m, Tx, n_values).\n", "* The shape of the 't' selection should be (n_values,). \n", "* Recall that if you were implementing in numpy instead of Keras, you would extract a slice from a 3D numpy array like this:\n", "```Python\n", "var1 = array1[:,1,:]\n", "```\n", " \n", "#### 2B. Reshape `x` to be (1, n_values).\n", "* Use the `reshaper()` layer. This is a function that takes the previous layer as its input argument.\n", "\n", "#### 2C. Run `x` through one step of `LSTM_cell`.\n", "\n", "* Initialize the `LSTM_cell` with the previous step's hidden state $a$ and cell state $c$. \n", "* Use the following formatting:\n", "```python\n", "next_hidden_state, _, next_cell_state = LSTM_cell(inputs=input_x, initial_state=[previous_hidden_state, previous_cell_state])\n", "```\n", " * Choose appropriate variables for inputs, hidden state and cell state.\n", "\n", "#### 2D. Dense layer\n", "* Propagate the LSTM's hidden state through a dense+softmax layer using `densor`. \n", " \n", "#### 2E. Append output\n", "* Append the output to the list of \"outputs\"." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Step 3: After the loop, create the model\n", "* Use the Keras `Model` object to create a model. There are two ways to instantiate the `Model` object. One is by subclassing, which you won't use here. Instead, you'll use the highly flexible Functional API, which you may remember from an earlier assignment in this course! With the Functional API, you'll start from your Input, then specify the model's forward pass with chained layer calls, and finally create the model from inputs and outputs.\n", "\n", "* Specify the inputs and output like so:\n", "```Python\n", "model = Model(inputs=[input_x, initial_hidden_state, initial_cell_state], outputs=the_outputs)\n", "```\n", " * Then, choose the appropriate variables for the input tensor, hidden state, cell state, and output.\n", "* See the documentation for [Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n", "# GRADED FUNCTION: djmodel\n", "\n", "def djmodel(Tx, LSTM_cell, densor, reshaper):\n", " \"\"\"\n", " Implement the djmodel composed of Tx LSTM cells where each cell is responsible\n", " for learning the following note based on the previous note and context.\n", " Each cell has the following schema: \n", " [X_{t}, a_{t-1}, c0_{t-1}] -> RESHAPE() -> LSTM() -> DENSE()\n", " Arguments:\n", " Tx -- length of the sequences in the corpus\n", " LSTM_cell -- LSTM layer instance\n", " densor -- Dense layer instance\n", " reshaper -- Reshape layer instance\n", " \n", " Returns:\n", " model -- a keras instance model with inputs [X, a0, c0]\n", " \"\"\"\n", " # Get the shape of input values\n", " n_values = densor.units\n", " \n", " # Get the number of the hidden state vector\n", " n_a = LSTM_cell.units\n", " \n", " # Define the input layer and specify the shape\n", " X = Input(shape=(Tx, n_values)) \n", " \n", " # Define the initial hidden state a0 and initial cell state c0\n", " # using `Input`\n", " a0 = Input(shape=(n_a,), name='a0')\n", " c0 = Input(shape=(n_a,), name='c0')\n", " a = a0\n", " c = c0\n", " ### START CODE HERE ### \n", " # Step 1: Create empty list to append the outputs while you iterate (≈1 line)\n", " outputs = []\n", " \n", " # Step 2: Loop from 0 to Tx\n", " for t in range(Tx):\n", " \n", " # Step 2.A: select the \"t\"th time step vector from X. \n", " x = X[:,t,:]\n", " # Step 2.B: Use reshaper to reshape x to be (1, n_values) (≈1 line)\n", " x = reshaper(x)\n", " # Step 2.C: Perform one step of the LSTM_cell\n", " a, _, c = LSTM_cell(x, initial_state=[a, c])\n", " # Step 2.D: Apply densor to the hidden state output of LSTM_Cell\n", " out = densor(a)\n", " # Step 2.E: add the output to \"outputs\"\n", " outputs.append(out)\n", " \n", " # Step 3: Create model instance\n", " model = Model(inputs=[X, a0, c0], outputs=outputs)\n", " \n", " ### END CODE HERE ###\n", " \n", " return model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Create the model object\n", "* Run the following cell to define your model. \n", "* We will use `Tx=30`. \n", "* This cell may take a few seconds to run. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "model = djmodel(Tx=30, LSTM_cell=LSTM_cell, densor=densor, reshaper=reshaper)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNIT TEST\n", "output = summary(model) \n", "comparator(output, djmodel_out)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "# Check your model\n", "model.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output** \n", "Scroll to the bottom of the output, and you'll see the following:\n", "\n", "```Python\n", "Total params: 45,530\n", "Trainable params: 45,530\n", "Non-trainable params: 0\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Compile the model for training\n", "* You now need to compile your model to be trained. \n", "* We will use:\n", " - optimizer: Adam optimizer\n", " - Loss function: categorical cross-entropy (for multi-class classification)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "opt = Adam(lr=0.01, beta_1=0.9, beta_2=0.999, decay=0.01)\n", "\n", "model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Initialize hidden state and cell state\n", "Finally, let's initialize `a0` and `c0` for the LSTM's initial state to be zero. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true }, "scrolled": true }, "outputs": [], "source": [ "m = 60\n", "a0 = np.zeros((m, n_a))\n", "c0 = np.zeros((m, n_a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Train the model\n", "\n", "You're now ready to fit the model! \n", "\n", "* You'll turn `Y` into a list, since the cost function expects `Y` to be provided in this format. \n", " - `list(Y)` is a list with 30 items, where each of the list items is of shape (60,90). \n", " - Train for 100 epochs (This will take a few minutes). " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true }, "scrolled": true }, "outputs": [], "source": [ "history = model.fit([X, a0, c0], list(Y), epochs=100, verbose = 0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f\"loss at epoch 1: {history.history['loss'][0]}\")\n", "print(f\"loss at epoch 100: {history.history['loss'][99]}\")\n", "plt.plot(history.history['loss'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "#### Expected Output\n", "\n", "The model loss will start high, (100 or so), and after 100 epochs, it should be in the single digits. These won't be the exact number that you'll see, due to random initialization of weights. \n", "For example:\n", "```\n", "loss at epoch 1: 129.88641357421875\n", "...\n", "```\n", "Scroll to the bottom to check Epoch 100\n", "```\n", "loss at epoch 100: 9.21483039855957\n", "```\n", "\n", "Now that you have trained a model, let's go to the final section to implement an inference algorithm, and generate some music! " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 3 - Generating Music\n", "\n", "You now have a trained model which has learned the patterns of a jazz soloist. You can now use this model to synthesize new music! \n", "\n", "\n", "### 3.1 - Predicting & Sampling\n", "\n", "\n", "
Figure 2: Generating new values in an LSTM " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "At each step of sampling, you will:\n", "* Take as input the activation '`a`' and cell state '`c`' from the previous state of the LSTM.\n", "* Forward propagate by one step.\n", "* Get a new output activation, as well as cell state. \n", "* The new activation '`a`' can then be used to generate the output using the fully connected layer, `densor`. \n", "\n", "#### Initialization\n", "* You'll initialize the following to be zeros:\n", " * `x0` \n", " * hidden state `a0` \n", " * cell state `c0` " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Exercise 2 - music_inference_model\n", "\n", "Implement `music_inference_model()` to sample a sequence of musical values.\n", "\n", "Here are some of the key steps you'll need to implement inside the for-loop that generates the $T_y$ output characters: \n", "\n", "**Step 1**: Create an empty list \"outputs\" to save the outputs of the LSTM Cell at every time step.\n", "\n", "**Step 2.A**: Use `LSTM_Cell`, which takes in the input layer, as well as the previous step's '`c`' and '`a`' to generate the current step's '`c`' and '`a`'. \n", "\n", "```Python\n", "next_hidden_state, _, next_cell_state = LSTM_cell(input_x, initial_state=[previous_hidden_state, previous_cell_state])\n", "```\n", " - Choose the appropriate variables for `input_x`, `hidden_state`, and `cell_state`\n", "\n", "**2.B**: Compute the output by applying `densor` to compute a softmax on '`a`' to get the output for the current step. \n", "\n", "**2.C**: Append the output to the list `outputs`.\n", "\n", "**2.D**: Convert the last output into a new input for the next time step. You will do this in 2 substeps:\n", "- Get the index of the maximum value of the predicted output using `tf.math.argmax` along the last axis.\n", "- Convert the index into its n_values-one-hot encoding using `tf.one_hot`.\n", "\n", "**2.E**: Use `RepeatVector(1)(x)` to convert the output of the one-hot enconding with shape=(None, 90) into a tensor with shape=(None, 1, 90)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Step 3: Inference Model: \n", "This is how to use the Keras `Model` object:\n", "\n", "```Python\n", "model = Model(inputs=[input_x, initial_hidden_state, initial_cell_state], outputs=the_outputs)\n", "```\n", "\n", "* Choose the appropriate variables for the input tensor, hidden state, cell state, and output.\n", "\n", "**Hint**: the inputs to the model are the **initial** inputs and states." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n", "# GRADED FUNCTION: music_inference_model\n", "\n", "def music_inference_model(LSTM_cell, densor, Ty=100):\n", " \"\"\"\n", " Uses the trained \"LSTM_cell\" and \"densor\" from model() to generate a sequence of values.\n", " \n", " Arguments:\n", " LSTM_cell -- the trained \"LSTM_cell\" from model(), Keras layer object\n", " densor -- the trained \"densor\" from model(), Keras layer object\n", " Ty -- integer, number of time steps to generate\n", " \n", " Returns:\n", " inference_model -- Keras model instance\n", " \"\"\"\n", " \n", " # Get the shape of input values\n", " n_values = densor.units\n", " # Get the number of the hidden state vector\n", " n_a = LSTM_cell.units\n", " \n", " # Define the input of your model with a shape \n", " x0 = Input(shape=(1, n_values))\n", " \n", " \n", " # Define s0, initial hidden state for the decoder LSTM\n", " a0 = Input(shape=(n_a,), name='a0')\n", " c0 = Input(shape=(n_a,), name='c0')\n", " a = a0\n", " c = c0\n", " x = x0\n", "\n", " ### START CODE HERE ###\n", " # Step 1: Create an empty list of \"outputs\" to later store your predicted values (≈1 line)\n", " outputs = []\n", " \n", " # Step 2: Loop over Ty and generate a value at every time step\n", " for t in range(Ty):\n", " # Step 2.A: Perform one step of LSTM_cell. Use \"x\", not \"x0\" (≈1 line)\n", " a, _, c = LSTM_cell(x, initial_state=[a, c])\n", " \n", " # Step 2.B: Apply Dense layer to the hidden state output of the LSTM_cell (≈1 line)\n", " out = densor(a)\n", " # Step 2.C: Append the prediction \"out\" to \"outputs\". out.shape = (None, 90) (≈1 line)\n", " outputs.append(out)\n", "\n", " \n", " # Step 2.D: \n", " # Select the next value according to \"out\",\n", " # Set \"x\" to be the one-hot representation of the selected value\n", " # See instructions above.\n", " x = tf.math.argmax(out, axis=-1)\n", " x = tf.one_hot(x, n_values)\n", " # Step 2.E: \n", " # Use RepeatVector(1) to convert x into a tensor with shape=(None, 1, 90)\n", " x = RepeatVector(1)(x)\n", " \n", " # Step 3: Create model instance with the correct \"inputs\" and \"outputs\" (≈1 line)\n", " inference_model = Model(inputs=[x0, a0, c0], outputs=outputs)\n", " \n", " ### END CODE HERE ###\n", " \n", " return inference_model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Run the cell below to define your inference model. This model is hard coded to generate 50 values." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "inference_model = music_inference_model(LSTM_cell, densor, Ty = 50)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNIT TEST\n", "inference_summary = summary(inference_model) \n", "comparator(inference_summary, music_inference_model_out)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "# Check the inference model\n", "inference_model.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output**\n", "\n", "If you scroll to the bottom of the output, you'll see:\n", "```\n", "Total params: 45,530\n", "Trainable params: 45,530\n", "Non-trainable params: 0\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Initialize inference model\n", "The following code creates the zero-valued vectors you will use to initialize `x` and the LSTM state variables `a` and `c`. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "x_initializer = np.zeros((1, 1, n_values))\n", "a_initializer = np.zeros((1, n_a))\n", "c_initializer = np.zeros((1, n_a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Exercise 3 - predict_and_sample\n", "\n", "Implement `predict_and_sample()`. \n", "\n", "This function takes many arguments, including the inputs `x_initializer`, `a_initializer`, and `c_initializer`. \n", "\n", "In order to predict the output corresponding to this input, you'll need to carry out 3 steps:\n", "\n", "\n", "#### Step 1:\n", "\n", "* Use your inference model to predict an output given your set of inputs. The output `pred` should be a list of length $T_y$ where each element is a numpy-array of shape (1, n_values).\n", "```Python\n", "inference_model.predict([input_x_init, hidden_state_init, cell_state_init])\n", "```\n", " * Choose the appropriate input arguments to `predict` from the input arguments of this `predict_and_sample` function.\n", " \n", "#### Step 2:\n", "\n", "* Convert `pred` into a numpy array of $T_y$ indices. \n", " * Each index is computed by taking the `argmax` of an element of the `pred` list. \n", " * Use [numpy.argmax](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html).\n", " * Set the `axis` parameter.\n", " * Remember that the shape of the prediction is $(m, T_{y}, n_{values})$\n", "\n", "#### Step 3: \n", "\n", "* Convert the indices into their one-hot vector representations. \n", " * Use [to_categorical](https://www.tensorflow.org/api_docs/python/tf/keras/utils/to_categorical).\n", " * Set the `num_classes` parameter. Note that for grading purposes: you'll need to either:\n", " * Use a dimension from the given parameters of `predict_and_sample()` (for example, one of the dimensions of x_initializer has the value for the number of distinct classes).\n", " * Or just hard code the number of distinct classes (will pass the grader as well).\n", " * **Note** that using a global variable such as `n_values` will not work for grading purposes." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n", "# GRADED FUNCTION: predict_and_sample\n", "\n", "def predict_and_sample(inference_model, x_initializer = x_initializer, a_initializer = a_initializer, \n", " c_initializer = c_initializer):\n", " \"\"\"\n", " Predicts the next value of values using the inference model.\n", " \n", " Arguments:\n", " inference_model -- Keras model instance for inference time\n", " x_initializer -- numpy array of shape (1, 1, 90), one-hot vector initializing the values generation\n", " a_initializer -- numpy array of shape (1, n_a), initializing the hidden state of the LSTM_cell\n", " c_initializer -- numpy array of shape (1, n_a), initializing the cell state of the LSTM_cel\n", " \n", " Returns:\n", " results -- numpy-array of shape (Ty, 90), matrix of one-hot vectors representing the values generated\n", " indices -- numpy-array of shape (Ty, 1), matrix of indices representing the values generated\n", " \"\"\"\n", " \n", " n_values = x_initializer.shape[2]\n", " \n", " ### START CODE HERE ###\n", " # Step 1: Use your inference model to predict an output sequence given x_initializer, a_initializer and c_initializer.\n", " pred = inference_model.predict([x_initializer, a_initializer, c_initializer])\n", " # Step 2: Convert \"pred\" into an np.array() of indices with the maximum probabilities\n", " indices = np.argmax(pred, axis = -1)\n", " # Step 3: Convert indices to one-hot vectors, the shape of the results should be (Ty, n_values)\n", " results = to_categorical(indices, num_classes=n_values)\n", " ### END CODE HERE ###\n", " \n", " return results, indices" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "results, indices = predict_and_sample(inference_model, x_initializer, a_initializer, c_initializer)\n", "\n", "print(\"np.argmax(results[12]) =\", np.argmax(results[12]))\n", "print(\"np.argmax(results[17]) =\", np.argmax(results[17]))\n", "print(\"list(indices[12:18]) =\", list(indices[12:18]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected (Approximate) Output**: \n", "\n", "* Your results **may likely differ** because Keras' results are not completely predictable. \n", "* However, if you have trained your LSTM_cell with model.fit() for exactly 100 epochs as described above: \n", " * You should very likely observe a sequence of indices that are not all identical. Perhaps with the following values:\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
\n", " **np.argmax(results[12])** =\n", " \n", " 26\n", "
\n", " **np.argmax(results[17])** =\n", " \n", " 7\n", "
\n", " **list(indices[12:18])** =\n", " \n", " [array([26]), array([18]), array([53]), array([27]), array([40]), array([7])]\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 3.2 - Generate Music \n", "\n", "Finally! You're ready to generate music. \n", "\n", "Your RNN generates a sequence of values. The following code generates music by first calling your `predict_and_sample()` function. These values are then post-processed into musical chords (meaning that multiple values or notes can be played at the same time). \n", "\n", "Most computational music algorithms use some post-processing because it's difficult to generate music that sounds good without it. The post-processing does things like clean up the generated audio by making sure the same sound is not repeated too many times, or that two successive notes are not too far from each other in pitch, and so on. \n", "\n", "One could argue that a lot of these post-processing steps are hacks; also, a lot of the music generation literature has also focused on hand-crafting post-processors, and a lot of the output quality depends on the quality of the post-processing and not just the quality of the model. But this post-processing does make a huge difference, so you should use it in your implementation as well. \n", "\n", "Let's make some music! " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Run the following cell to generate music and record it into your `out_stream`. This can take a couple of minutes." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "out_stream = generate_music(inference_model, indices_values, chords)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using a basic midi to wav parser you can have a rough idea about the audio clip generated by this model. The parser is very limited." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mid2wav('output/my_music.midi')\n", "IPython.display.Audio('./output/rendered.wav')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To listen to your music, click File->Open... Then go to \"output/\" and download \"my_music.midi\". Either play it on your computer with an application that can read midi files if you have one, or use one of the free online \"MIDI to mp3\" conversion tools to convert this to mp3. \n", "\n", "As a reference, here is a 30 second audio clip generated using this algorithm:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "IPython.display.Audio('./data/30s_trained_model.wav')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Congratulations!\n", "\n", "You've completed this assignment, and generated your own jazz solo! The Coltranes would be proud. \n", "\n", "By now, you've: \n", "\n", "- Applied an LSTM to a music generation task\n", "- Generated your own jazz music with deep learning\n", "- Used the flexible Functional API to create a more complex model\n", "\n", "This was a lengthy task. You should be proud of your hard work, and hopefully you have some good music to show for it. Cheers and see you next time! " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " What you should remember:\n", " \n", "- A sequence model can be used to generate musical values, which are then post-processed into midi music. \n", "- You can use a fairly similar model for tasks ranging from generating dinosaur names to generating original music, with the only major difference being the input fed to the model. \n", "- In Keras, sequence generation involves defining layers with shared weights, which are then repeated for the different time steps $1, \\ldots, T_x$. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 4 - References\n", "\n", "The ideas presented in this notebook came primarily from three computational music papers cited below. The implementation here also took significant inspiration and used many components from Ji-Sung Kim's GitHub repository.\n", "\n", "- Ji-Sung Kim, 2016, [deepjazz](https://github.com/jisungk/deepjazz)\n", "- Jon Gillick, Kevin Tang and Robert Keller, 2009. [Learning Jazz Grammars](http://ai.stanford.edu/~kdtang/papers/smc09-jazzgrammar.pdf)\n", "- Robert Keller and David Morrison, 2007, [A Grammatical Approach to Automatic Improvisation](http://smc07.uoa.gr/SMC07%20Proceedings/SMC07%20Paper%2055.pdf)\n", "- François Pachet, 1999, [Surprising Harmonies](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.5.7473&rep=rep1&type=pdf)\n", "\n", "Finally, a shoutout to François Germain for valuable feedback." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [] } ], "metadata": { "coursera": { "schema_names": [ "DLSC5W1-A3" ] }, "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": 4 }