Advertisement
ERENARD63

Improvise a Jazz Solo with an LSTM Network

May 24th, 2018
633
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 20.86 KB | None | 0 0
  1.  
  2. # coding: utf-8
  3.  
  4. # # Improvise a Jazz Solo with an LSTM Network
  5. #
  6. # Welcome to your final programming assignment of this week! In this notebook, you will implement a model that uses an LSTM to generate music. You will even be able to listen to your own music at the end of the assignment.
  7. #
  8. # **You will learn to:**
  9. # - Apply an LSTM to music generation.
  10. # - Generate your own jazz music with deep learning.
  11. #
  12. # Please run the following cell to load all the packages required in this assignment. This may take a few minutes.
  13.  
  14. # In[17]:
  15.  
  16. from __future__ import print_function
  17. import IPython
  18. import sys
  19. from music21 import *
  20. import numpy as np
  21. from grammar import *
  22. from qa import *
  23. from preprocess import *
  24. from music_utils import *
  25. from data_utils import *
  26. from keras.models import load_model, Model
  27. from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector
  28. from keras.initializers import glorot_uniform
  29. from keras.utils import to_categorical
  30. from keras.optimizers import Adam
  31. from keras import backend as K
  32.  
  33.  
  34. # ## 1 - Problem statement
  35. #
  36. # You would like to create a jazz music piece specially for a friend's birthday. However, you don't know any instruments or music composition. Fortunately, you know deep learning and will solve this problem using an LSTM netwok.  
  37. #
  38. # You will train a network to generate novel jazz solos in a style representative of a body of performed work.
  39. #
  40. #
  41. # ### 1.1 - Dataset
  42. #
  43. # You will 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:
  44.  
  45. # In[18]:
  46.  
  47. IPython.display.Audio('./data/30s_seq.mp3')
  48.  
  49.  
  50. # We have taken care of the preprocessing of the musical data to render it in terms of musical "values." You can informally think of each "value" as a note, which comprises a pitch and a 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 (playng multiple notes at the same time generates what's called a "chord"). But we don't need to worry about the details of music theory for this assignment. For the purpose of this assignment, all you need to know is that we will obtain a dataset of values, and will learn an RNN model to generate sequences of values.
  51. #
  52. # Our music generation system will use 78 unique values. Run the following code to load the raw music data and preprocess it into values. This might take a few minutes.
  53.  
  54. # In[19]:
  55.  
  56. X, Y, n_values, indices_values = load_music_utils()
  57. print('shape of X:', X.shape)
  58. print('number of training examples:', X.shape[0])
  59. print('Tx (length of sequence):', X.shape[1])
  60. print('total # of unique values:', n_values)
  61. print('Shape of Y:', Y.shape)
  62.  
  63.  
  64. # You have just loaded the following:
  65. #
  66. # - `X`: This is an (m, $T_x$, 78) dimensional array. We have m training examples, each of which is a snippet of $T_x =30$ musical values. At each time step, the input is one of 78 different possible values, represented as a one-hot vector. Thus for example, X[i,t,:] is a one-hot vector representating the value of the i-th example at time t.
  67. #
  68. # - `Y`: This is essentially the same as `X`, but shifted one step to the left (to the past). Similar to the dinosaurus assignment, we're interested in the network using the previous values to predict the next value, so our sequence model will try to predict $y^{\langle t \rangle}$ given $x^{\langle 1\rangle}, \ldots, x^{\langle t \rangle}$. However, the data in `Y` is reordered to be dimension $(T_y, m, 78)$, where $T_y = T_x$. This format makes it more convenient to feed to the LSTM later.
  69. #
  70. # - `n_values`: The number of unique values in this dataset. This should be 78.
  71. #
  72. # - `indices_values`: python dictionary mapping from 0-77 to musical values.
  73.  
  74. # ### 1.2 - Overview of our model
  75. #
  76. # Here is the architecture of the model we will use. This is similar to the Dinosaurus model you had used in the previous notebook, except that in you will be implementing it in Keras. The architecture is as follows:
  77. #
  78. #
  79. # We will be training the model on random snippets of 30 values taken from a much longer piece of music. Thus, we won't bother to set the first input $x^{\langle 1 \rangle} = \vec{0}$, which we had done previously to denote the start of a dinosaur name, since now most of these snippets of audio start somewhere in the middle of a piece of music. We are setting each of the snippts to have the same length $T_x = 30$ to make vectorization easier.
  80. #
  81.  
  82. # ## 2 - Building the model
  83. #
  84. # In this part you will build and train a model that will learn musical patterns. To do so, you will need to build a model that takes in X of shape $(m, T_x, 78)$ and Y of shape $(T_y, m, 78)$. We will use an LSTM with 64 dimensional hidden states. Lets set `n_a = 64`.
  85. #
  86.  
  87. # In[20]:
  88.  
  89. n_a = 64
  90.  
  91.  
  92. #
  93. # Here's how you can create a Keras model with multiple inputs and outputs. If you're building an RNN where even at test time entire input sequence $x^{\langle 1 \rangle}, x^{\langle 2 \rangle}, \ldots, x^{\langle T_x \rangle}$ were *given in advance*, for example if the inputs were words and the output was a label, then Keras has simple built-in functions to build the model. However, for sequence generation, at test time we don't know all the values of $x^{\langle t\rangle}$ in advance; instead we generate them one at a time using $x^{\langle t\rangle} = y^{\langle t-1 \rangle}$. So the code will be a bit more complicated, and you'll need to implement your own for-loop to iterate over the different time steps.
  94. #
  95. # The function `djmodel()` will call the LSTM layer $T_x$ times using a for-loop, and it is important that all $T_x$ copies have the same weights. I.e., it should not re-initiaiize the weights every time---the $T_x$ steps should have shared weights. The key steps for implementing layers with shareable weights in Keras are:
  96. # 1. Define the layer objects (we will use global variables for this).
  97. # 2. Call these objects when propagating the input.
  98. #
  99. # We have defined the layers objects you need as global variables. Please run the next cell to create them. Please check the Keras documentation to make sure you understand what these layers are: [Reshape()](https://keras.io/layers/core/#reshape), [LSTM()](https://keras.io/layers/recurrent/#lstm), [Dense()](https://keras.io/layers/core/#dense).
  100. #
  101.  
  102. # In[21]:
  103.  
  104. reshapor = Reshape((1, 78))                        # Used in Step 2.B of djmodel(), below
  105. LSTM_cell = LSTM(n_a, return_state = True)         # Used in Step 2.C
  106. densor = Dense(n_values, activation='softmax')     # Used in Step 2.D
  107.  
  108.  
  109. # Each of `reshapor`, `LSTM_cell` and `densor` are now layer objects, and you can use them to implement `djmodel()`. In order to propagate a Keras tensor object X through one of these layers, use `layer_object(X)` (or `layer_object([X,Y])` if it requires multiple inputs.). For example, `reshapor(X)` will propagate X through the `Reshape((1,78))` layer defined above.
  110.  
  111. #  
  112. # **Exercise**: Implement `djmodel()`. You will need to carry out 2 steps:
  113. #
  114. # 1. Create an empty list "outputs" to save the outputs of the LSTM Cell at every time step.
  115. # 2. Loop for $t \in 1, \ldots, T_x$:
  116. #
  117. #     A. Select the "t"th time-step vector from X. The shape of this selection should be (78,). To do so, create a custom [Lambda](https://keras.io/layers/core/#lambda) layer in Keras by using this line of code:
  118. # ```    
  119. #            x = Lambda(lambda x: X[:,t,:])(X)
  120. # ```
  121. # Look over the Keras documentation to figure out what this does. It is creating a "temporary" or "unnamed" function (that's what Lambda functions are) that extracts out the appropriate one-hot vector, and making this function a Keras `Layer` object to apply to `X`.
  122. #
  123. #     B. Reshape x to be (1,78). You may find the `reshapor()` layer (defined below) helpful.
  124. #
  125. #     C. Run x through one step of LSTM_cell. Remember to initialize the LSTM_cell with the previous step's hidden state $a$ and cell state $c$. Use the following formatting:
  126. # ```python
  127. # a, _, c = LSTM_cell(input_x, initial_state=[previous hidden state, previous cell state])
  128. # ```
  129. #
  130. #     D. Propagate the LSTM's output activation value through a dense+softmax layer using `densor`.
  131. #    
  132. #     E. Append the predicted value to the list of "outputs"
  133. #  
  134. #
  135.  
  136. # In[22]:
  137.  
  138. # GRADED FUNCTION: djmodel
  139.  
  140. def djmodel(Tx, n_a, n_values):
  141.     """
  142.    Implement the model
  143.    
  144.    Arguments:
  145.    Tx -- length of the sequence in a corpus
  146.    n_a -- the number of activations used in our model
  147.    n_values -- number of unique values in the music data
  148.    
  149.    Returns:
  150.    model -- a keras model with the
  151.    """
  152.    
  153.     # Define the input of your model with a shape
  154.     X = Input(shape=(Tx, n_values))
  155.    
  156.     # Define s0, initial hidden state for the decoder LSTM
  157.     a0 = Input(shape=(n_a,), name='a0')
  158.     c0 = Input(shape=(n_a,), name='c0')
  159.     a = a0
  160.     c = c0
  161.    
  162.     ### START CODE HERE ###
  163.     # Step 1: Create empty list to append the outputs while you iterate (≈1 line)
  164.     outputs = []
  165.    
  166.     # Step 2: Loop
  167.     for t in range(Tx):
  168.        
  169.         # Step 2.A: select the "t"th time step vector from X.
  170.         x = Lambda(lambda x: X[:,t,:])(X)
  171.         # Step 2.B: Use reshapor to reshape x to be (1, n_values) (≈1 line)
  172.         x = reshapor(x)
  173.         # Step 2.C: Perform one step of the LSTM_cell
  174.         a, _, c = LSTM_cell(x, initial_state=[a, c])
  175.         # Step 2.D: Apply densor to the hidden state output of LSTM_Cell
  176.         out = densor(a)
  177.         # Step 2.E: add the output to "outputs"
  178.         outputs.append(out)
  179.        
  180.     # Step 3: Create model instance
  181.     model = Model([X,a0,c0],outputs)
  182.    
  183.     ### END CODE HERE ###
  184.    
  185.     return model
  186.  
  187.  
  188. # Run the following cell to define your model. We will use `Tx=30`, `n_a=64` (the dimension of the LSTM activations), and `n_values=78`. This cell may take a few seconds to run.
  189.  
  190. # In[23]:
  191.  
  192. model = djmodel(Tx = 30 , n_a = 64, n_values = 78)
  193.  
  194.  
  195. # You now need to compile your model to be trained. We will Adam and a categorical cross-entropy loss.
  196.  
  197. # In[24]:
  198.  
  199. opt = Adam(lr=0.01, beta_1=0.9, beta_2=0.999, decay=0.01)
  200.  
  201. model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
  202.  
  203.  
  204. # Finally, lets initialize `a0` and `c0` for the LSTM's initial state to be zero.
  205.  
  206. # In[25]:
  207.  
  208. m = 60
  209. a0 = np.zeros((m, n_a))
  210. c0 = np.zeros((m, n_a))
  211.  
  212.  
  213. # Lets now fit the model! We will turn `Y` to a list before doing so, since the cost function expects `Y` to be provided in this format (one list item per time-step). So `list(Y)` is a list with 30 items, where each of the list items is of shape (60,78). Lets train for 100 epochs. This will take a few minutes.
  214. #
  215. #
  216.  
  217. # In[46]:
  218.  
  219. model.fit([X, a0, c0], list(Y), epochs=100)
  220.  
  221.  
  222. # You should see the model loss going down. Now that you have trained a model, lets go on the the final section to implement an inference algorithm, and generate some music!
  223.  
  224. # ## 3 - Generating music
  225. #
  226. # You now have a trained model which has learned the patterns of the jazz soloist. Lets now use this model to synthesize new music.
  227. #
  228. # #### 3.1 - Predicting & Sampling
  229. #
  230. #
  231. # At each step of sampling, you will take as input the activation `a` and cell state `c` from the previous state of the LSTM, forward propagate by one step, and get a new output activation as well as cell state. The new activation `a` can then be used to generate the output, using `densor` as before.
  232. #
  233. # To start off the model, we will initialize `x0` as well as the LSTM activation and and cell value `a0` and `c0` to be zeros.
  234. #
  235. #
  236. # <!--
  237. # You are about to build a function that will do this inference for you. Your function takes in your previous model and the number of time steps `Ty` that you want to sample. It will return a keras model that would be able to generate sequences for you. Furthermore, the function takes in a dense layer of `78` units and the number of activations.
  238. # !-->
  239. #
  240. #
  241. # **Exercise:** Implement the function below to sample a sequence of musical values. Here are some of the key steps you'll need to implement inside the for-loop that generates the $T_y$ output characters:
  242. #
  243. # Step 2.A: Use `LSTM_Cell`, which inputs the previous step's `c` and `a` to generate the current step's `c` and `a`.
  244. #
  245. # Step 2.B: Use `densor` (defined previously) to compute a softmax on `a` to get the output for the current step.
  246. #
  247. # Step 2.C: Save the output you have just generated by appending it to `outputs`.
  248. #
  249. # Step 2.D: Sample x to the be "out"'s one-hot version (the prediction) so that you can pass it to the next LSTM's step.  We have already provided this line of code, which uses a [Lambda](https://keras.io/layers/core/#lambda) function.
  250. # ```python
  251. # x = Lambda(one_hot)(out)
  252. # ```
  253. # [Minor technical note: Rather than sampling a value at random according to the probabilities in `out`, this line of code actually chooses the single most likely note at each step using an argmax.]
  254. #
  255.  
  256. # In[48]:
  257.  
  258. # GRADED FUNCTION: music_inference_model
  259.  
  260. def music_inference_model(LSTM_cell, densor, n_values = 78, n_a = 64, Ty = 100):
  261.     """
  262.    Uses the trained "LSTM_cell" and "densor" from model() to generate a sequence of values.
  263.    
  264.    Arguments:
  265.    LSTM_cell -- the trained "LSTM_cell" from model(), Keras layer object
  266.    densor -- the trained "densor" from model(), Keras layer object
  267.    n_values -- integer, umber of unique values
  268.    n_a -- number of units in the LSTM_cell
  269.    Ty -- integer, number of time steps to generate
  270.    
  271.    Returns:
  272.    inference_model -- Keras model instance
  273.    """
  274.    
  275.     # Define the input of your model with a shape
  276.     x0 = Input(shape=(1, n_values))
  277.    
  278.     # Define s0, initial hidden state for the decoder LSTM
  279.     a0 = Input(shape=(n_a,), name='a0')
  280.     c0 = Input(shape=(n_a,), name='c0')
  281.     a = a0
  282.     c = c0
  283.     x = x0
  284.  
  285.     ### START CODE HERE ###
  286.     # Step 1: Create an empty list of "outputs" to later store your predicted values (≈1 line)
  287.     outputs = []
  288.    
  289.     # Step 2: Loop over Ty and generate a value at every time step
  290.     for t in range(Ty):
  291.        
  292.         # Step 2.A: Perform one step of LSTM_cell (≈1 line)
  293.         a, _, c = LSTM_cell(x, initial_state=[a, c])
  294.        
  295.         # Step 2.B: Apply Dense layer to the hidden state output of the LSTM_cell (≈1 line)
  296.         out = densor(a)
  297.  
  298.         # Step 2.C: Append the prediction "out" to "outputs". out.shape = (None, 78) (≈1 line)
  299.         outputs.append(out)
  300.        
  301.         # Step 2.D: Select the next value according to "out", and set "x" to be the one-hot representation of the
  302.         #           selected value, which will be passed as the input to LSTM_cell on the next step. We have provided
  303.         #           the line of code you need to do this.
  304.         x = Lambda(one_hot)(out)
  305.        
  306.     # Step 3: Create model instance with the correct "inputs" and "outputs" (≈1 line)
  307.     inference_model = Model([x0,a0,c0],outputs)
  308.    
  309.     ### END CODE HERE ###
  310.    
  311.     return inference_model
  312.  
  313.  
  314. # Run the cell below to define your inference model. This model is hard coded to generate 50 values.
  315.  
  316. # In[49]:
  317.  
  318. inference_model = music_inference_model(LSTM_cell, densor, n_values = 78, n_a = 64, Ty = 50)
  319.  
  320.  
  321. # Finally, this creates the zero-valued vectors you will use to initialize `x` and the LSTM state variables `a` and `c`.
  322.  
  323. # In[50]:
  324.  
  325. x_initializer = np.zeros((1, 1, 78))
  326. a_initializer = np.zeros((1, n_a))
  327. c_initializer = np.zeros((1, n_a))
  328.  
  329.  
  330. # **Exercise**: Implement `predict_and_sample()`. This function takes many arguments including the inputs [x_initializer, a_initializer, c_initializer]. In order to predict the output corresponding to this input, you will need to carry-out 3 steps:
  331. # 1. 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).
  332. # 2. Convert `pred` into a numpy array of $T_y$ indices. Each index corresponds is computed by taking the `argmax` of an element of the `pred` list. [Hint](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html).
  333. # 3. Convert the indices into their one-hot vector representations. [Hint](https://keras.io/utils/#to_categorical).
  334.  
  335. # In[51]:
  336.  
  337. # GRADED FUNCTION: predict_and_sample
  338.  
  339. def predict_and_sample(inference_model, x_initializer = x_initializer, a_initializer = a_initializer,
  340.                        c_initializer = c_initializer):
  341.     """
  342.    Predicts the next value of values using the inference model.
  343.    
  344.    Arguments:
  345.    inference_model -- Keras model instance for inference time
  346.    x_initializer -- numpy array of shape (1, 1, 78), one-hot vector initializing the values generation
  347.    a_initializer -- numpy array of shape (1, n_a), initializing the hidden state of the LSTM_cell
  348.    c_initializer -- numpy array of shape (1, n_a), initializing the cell state of the LSTM_cel
  349.    
  350.    Returns:
  351.    results -- numpy-array of shape (Ty, 78), matrix of one-hot vectors representing the values generated
  352.    indices -- numpy-array of shape (Ty, 1), matrix of indices representing the values generated
  353.    """
  354.    
  355.     ### START CODE HERE ###
  356.     # Step 1: Use your inference model to predict an output sequence given x_initializer, a_initializer and c_initializer.
  357.     pred = inference_model.predict([x_initializer, a_initializer, c_initializer])
  358.     # Step 2: Convert "pred" into an np.array() of indices with the maximum probabilities
  359.     indices = np.argmax(pred,2)
  360.     # Step 3: Convert indices to one-hot vectors, the shape of the results should be (1, )
  361.     results = to_categorical(indices)
  362.     ### END CODE HERE ###
  363.    
  364.     return results, indices
  365.  
  366.  
  367. # In[52]:
  368.  
  369. results, indices = predict_and_sample(inference_model, x_initializer, a_initializer, c_initializer)
  370. print("np.argmax(results[12]) =", np.argmax(results[12]))
  371. print("np.argmax(results[17]) =", np.argmax(results[17]))
  372. print("list(indices[12:18]) =", list(indices[12:18]))
  373.  
  374.  
  375.  
  376. # #### 3.3 - Generate music
  377. #
  378. # Finally, you are ready to generate music. 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).
  379. #
  380. # Most computational music algorithms use some post-processing because it is difficult to generate music that sounds good without such post-processing. The post-processing does things such as clean up the generated audio by making sure the same sound is not repeated too many times, that two successive notes are not too far from each other in pitch, and so on. One could argue that a lot of these post-processing steps are hacks; also, a lot 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 RNN. But this post-processing does make a huge difference, so lets use it in our implementation as well.
  381. #
  382. # Lets make some music!
  383.  
  384. # Run the following cell to generate music and record it into your `out_stream`. This can take a couple of minutes.
  385.  
  386. # In[53]:
  387.  
  388. out_stream = generate_music(inference_model)
  389.  
  390.  
  391. # 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.  
  392. #
  393. # As reference, here also is a 30sec audio clip we generated using this algorithm.
  394.  
  395. # In[54]:
  396.  
  397. IPython.display.Audio('./data/30s_trained_model.mp3')
  398.  
  399.  
  400. # ### Congratulations!
  401. #
  402. # You have come to the end of the notebook.
  403. #
  404. # peated for the different time steps $1, \ldots, T_x$.
  405.  
  406. # Congratulations on completing this assignment and generating a jazz solo!
  407.  
  408. # **References**
  409. #
  410. # 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.
  411. #
  412. # - Ji-Sung Kim, 2016, [deepjazz](https://github.com/jisungk/deepjazz)
  413. # - Jon Gillick, Kevin Tang and Robert Keller, 2009. [Learning Jazz Grammars](http://ai.stanford.edu/~kdtang/papers/smc09-jazzgrammar.pdf)
  414. # - Robert Keller and David Morrison, 2007, [A Grammatical Approach to Automatic Improvisation](http://smc07.uoa.gr/SMC07%20Proceedings/SMC07%20Paper%2055.pdf)
  415. # - François Pachet, 1999, [Surprising Harmonies](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.5.7473&rep=rep1&type=pdf)
  416. #
  417. # We're also grateful to François Germain for valuable feedback.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement