Path: blob/master/site/en-snapshot/tutorials/audio/music_generation.ipynb
25118 views
Copyright 2021 The TensorFlow Authors.
Generate music with an RNN
This tutorial shows you how to generate musical notes using a simple recurrent neural network (RNN). You will train a model using a collection of piano MIDI files from the MAESTRO dataset. Given a sequence of notes, your model will learn to predict the next note in the sequence. You can generate longer sequences of notes by calling the model repeatedly.
This tutorial contains complete code to parse and create MIDI files. You can learn more about how RNNs work by visiting the Text generation with an RNN tutorial.
Setup
This tutorial uses the pretty_midi
library to create and parse MIDI files, and pyfluidsynth
for generating audio playback in Colab.
Download the Maestro dataset
The dataset contains about 1,200 MIDI files.
Process a MIDI file
First, use pretty_midi
to parse a single MIDI file and inspect the format of the notes. If you would like to download the MIDI file below to play on your computer, you can do so in colab by writing files.download(sample_file)
.
Generate a PrettyMIDI
object for the sample MIDI file.
Play the sample file. The playback widget may take several seconds to load.
Do some inspection on the MIDI file. What kinds of instruments are used?
Extract notes
You will use three variables to represent a note when training the model: pitch
, step
and duration
. The pitch is the perceptual quality of the sound as a MIDI note number. The step
is the time elapsed from the previous note or start of the track. The duration
is how long the note will be playing in seconds and is the difference between the note end and note start times.
Extract the notes from the sample MIDI file.
It may be easier to interpret the note names rather than the pitches, so you can use the function below to convert from the numeric pitch values to note names. The note name shows the type of note, accidental and octave number (e.g. C#4).
To visualize the musical piece, plot the note pitch, start and end across the length of the track (i.e. piano roll). Start with the first 100 notes
Plot the notes for the entire track.
Check the distribution of each note variable.
Create a MIDI file
You can generate your own MIDI file from a list of notes using the function below.
Play the generated MIDI file and see if there is any difference.
As before, you can write files.download(example_file)
to download and play this file.
Create the training dataset
Create the training dataset by extracting notes from the MIDI files. You can start by using a small number of files, and experiment later with more. This may take a couple minutes.
Next, create a tf.data.Dataset
from the parsed notes.
You will train the model on batches of sequences of notes. Each example will consist of a sequence of notes as the input features, and the next note as the label. In this way, the model will be trained to predict the next note in a sequence. You can find a diagram describing this process (and more details) in Text classification with an RNN.
You can use the handy window function with size seq_length
to create the features and labels in this format.
Set the sequence length for each example. Experiment with different lengths (e.g. 50, 100, 150) to see which one works best for the data, or use hyperparameter tuning. The size of the vocabulary (vocab_size
) is set to 128 representing all the pitches supported by pretty_midi
.
The shape of the dataset is (100,1)
, meaning that the model will take 100 notes as input, and learn to predict the following note as output.
Batch the examples, and configure the dataset for performance.
Create and train the model
The model will have three outputs, one for each note variable. For step
and duration
, you will use a custom loss function based on mean squared error that encourages the model to output non-negative values.
Testing the model.evaluate
function, you can see that the pitch
loss is significantly greater than the step
and duration
losses. Note that loss
is the total loss computed by summing all the other losses and is currently dominated by the pitch
loss.
One way balance this is to use the loss_weights
argument to compile:
The loss
then becomes the weighted sum of the individual losses.
Train the model.
Generate notes
To use the model to generate notes, you will first need to provide a starting sequence of notes. The function below generates one note from a sequence of notes.
For note pitch, it draws a sample from the softmax distribution of notes produced by the model, and does not simply pick the note with the highest probability. Always picking the note with the highest probability would lead to repetitive sequences of notes being generated.
The temperature
parameter can be used to control the randomness of notes generated. You can find more details on temperature in Text generation with an RNN.
Now generate some notes. You can play around with temperature and the starting sequence in next_notes
and see what happens.
You can also download the audio file by adding the two lines below:
Visualize the generated notes.
Check the distributions of pitch
, step
and duration
.
In the above plots, you will notice the change in distribution of the note variables. Since there is a feedback loop between the model's outputs and inputs, the model tends to generate similar sequences of outputs to reduce the loss. This is particularly relevant for step
and duration
, which uses the MSE loss. For pitch
, you can increase the randomness by increasing the temperature
in predict_next_note
.
Next steps
This tutorial demonstrated the mechanics of using an RNN to generate sequences of notes from a dataset of MIDI files. To learn more, you can visit the closely related Text generation with an RNN tutorial, which contains additional diagrams and explanations.
One of the alternatives to using RNNs for music generation is using GANs. Rather than generating audio, a GAN-based approach can generate an entire sequence in parallel. The Magenta team has done impressive work on this approach with GANSynth. You can also find many wonderful music and art projects and open-source code on Magenta project website.