/
3-zeldic-musical-RNN.ipynb
577 lines (577 loc) · 19.8 KB
/
3-zeldic-musical-RNN.ipynb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Imports\n",
"from music21 import converter, instrument, note, chord, stream, midi\n",
"import glob\n",
"import time\n",
"import numpy as np\n",
"import tensorflow.keras.utils as utils\n",
"import pandas as pd"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Music Generation with an RNN\n",
"\n",
"- Music is a complex phenomenon with many representations (e.g., digital audio, musical scores, lead sheets)\n",
"- A simple representation of music is as a sequence of notes and rests:\n",
" - (equivalent to one line of melody)\n",
"- This can be one-hot encoded and applied to a CharRNN!\n",
"\n",
"## A simple music representation\n",
"\n",
"- Our musical representation is going be a sequence of integers between 0 and 129.\n",
"- Each integer represents a musical instruction lasting for one sixteenth note (one semiquaver) of duration.\n",
" - This is a typical level of detail for electronic music sequencers.\n",
"- MIDI is a standard way of encoding instructions for synthesised instruments and can represent whole musical scores.\n",
" - Standard MIDI allows 128 pitches (there are only 88 on a piano keyboard) where number 60 is 'middle C'.\n",
" \n",
"#### Melody-RNN Encoding\n",
"\n",
"- 0-127 play a note at that MIDI note number. (`MELODY_NOTE_ON`)\n",
"- 128 stop whatever note was playing. (`MELODY_NOTE_OFF`)\n",
"- 129 do nothing. (`MELODY_NO_EVENT`)\n",
" \n",
"This encoding should allow long notes (a note-on followed by one or more no-change events, then a note-off), and rests (a note-off followed by one or more no-change events).\n",
"\n",
"Here's a standard melody converted into this format:\n",
"\n",
"![](figures/wm_score_example.png)\n",
"\n",
"NB: Google's [Magenta project](https://magenta.tensorflow.org/) have created some really great musical RNNs, with lots of advanced features. This script focusses on simplicity and clarity instead!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Convert between MIDI files and numpy arrays in melody format\n",
"\n",
"- Music is more complex than text (e.g., more than one note might happen at once). \n",
"- We use the Music21 library to read MIDI music filescand then convert to our Melody-RNN format.\n",
"- The functions below turn a Music21 \"stream\" (of notes) into a numpy array of 8-bit integers.\n",
"- All complex rhythms are simplified to sixteenth note versions.\n",
"- Chords are simplified to the highest note.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Melody-RNN Format is a sequence of 8-bit integers indicating the following:\n",
"# MELODY_NOTE_ON = [0, 127] # (note on at that MIDI pitch)\n",
"MELODY_NOTE_OFF = 128 # (stop playing all previous notes)\n",
"MELODY_NO_EVENT = 129 # (no change from previous event)\n",
"# Each element in the sequence lasts for one sixteenth note.\n",
"# This can encode monophonic music only.\n",
"\n",
"def streamToNoteArray(stream):\n",
" \"\"\"\n",
" Convert a Music21 sequence to a numpy array of int8s into Melody-RNN format:\n",
" 0-127 - note on at specified pitch\n",
" 128 - note off\n",
" 129 - no event\n",
" \"\"\"\n",
" # Part one, extract from stream\n",
" total_length = int(np.round(stream.flat.highestTime / 0.25)) # in semiquavers\n",
" stream_list = []\n",
" for element in stream.flat:\n",
" if isinstance(element, note.Note):\n",
" stream_list.append([np.round(element.offset / 0.25), np.round(element.quarterLength / 0.25), element.pitch.midi])\n",
" elif isinstance(element, chord.Chord):\n",
" stream_list.append([np.round(element.offset / 0.25), np.round(element.quarterLength / 0.25), element.sortAscending().pitches[-1].midi])\n",
" np_stream_list = np.array(stream_list, dtype=int)\n",
" df = pd.DataFrame({'pos': np_stream_list.T[0], 'dur': np_stream_list.T[1], 'pitch': np_stream_list.T[2]})\n",
" df = df.sort_values(['pos','pitch'], ascending=[True, False]) # sort the dataframe properly\n",
" df = df.drop_duplicates(subset=['pos']) # drop duplicate values\n",
" # part 2, convert into a sequence of note events\n",
" output = np.zeros(total_length+1, dtype=np.int16) + np.int16(MELODY_NO_EVENT) # set array full of no events by default.\n",
" # Fill in the output list\n",
" for i in range(total_length):\n",
" if not df[df.pos==i].empty:\n",
" n = df[df.pos==i].iloc[0] # pick the highest pitch at each semiquaver\n",
" output[i] = n.pitch # set note on\n",
" output[i+n.dur] = MELODY_NOTE_OFF\n",
" return output\n",
"\n",
"\n",
"def noteArrayToDataFrame(note_array):\n",
" \"\"\"\n",
" Convert a numpy array containing a Melody-RNN sequence into a dataframe.\n",
" \"\"\"\n",
" df = pd.DataFrame({\"code\": note_array})\n",
" df['offset'] = df.index\n",
" df['duration'] = df.index\n",
" df = df[df.code != MELODY_NO_EVENT]\n",
" df.duration = df.duration.diff(-1) * -1 * 0.25 # calculate durations and change to quarter note fractions\n",
" df = df.fillna(0.25)\n",
" return df[['code','duration']]\n",
"\n",
"\n",
"def noteArrayToStream(note_array):\n",
" \"\"\"\n",
" Convert a numpy array containing a Melody-RNN sequence into a music21 stream.\n",
" \"\"\"\n",
" df = noteArrayToDataFrame(note_array)\n",
" melody_stream = stream.Stream()\n",
" for index, row in df.iterrows():\n",
" if row.code == MELODY_NO_EVENT:\n",
" new_note = note.Rest() # bit of an oversimplification, doesn't produce long notes.\n",
" elif row.code == MELODY_NOTE_OFF:\n",
" new_note = note.Rest()\n",
" else:\n",
" new_note = note.Note(row.code)\n",
" new_note.quarterLength = row.duration\n",
" melody_stream.append(new_note)\n",
" return melody_stream\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"## Play a melody stream\n",
"# sp = midi.realtime.StreamPlayer(melody_stream)\n",
"# sp.play()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# for setting up musescore and musicxml rendering on linux:\n",
"# from music21 import environment\n",
"# us = environment.UserSettings()\n",
"# us.create()\n",
"# us['musescoreDirectPNGPath'] = '/usr/bin/mscore3'\n",
"# us['musicxmlPath'] = '/usr/bin/mscore3'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"wm_mid = converter.parse(\"../datasets/waltzing-matilda.mid\")\n",
"wm_mid.show()\n",
"wm_mel_rnn = streamToNoteArray(wm_mid)\n",
"print(wm_mel_rnn)\n",
"noteArrayToStream(wm_mel_rnn).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Construct a dataset of popular melodies\n",
"\n",
"Open some midi files and extract the melodies as numpy note sequence arrays."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"midi_files = glob.glob(\"../datasets/*.mid\") # this won't work, no files there.\n",
"\n",
"training_arrays = []\n",
"for f in midi_files:\n",
" start = time.perf_counter()\n",
" try:\n",
" s = converter.parse(f)\n",
" except:\n",
" continue\n",
"# for p in s.parts: # extract all voices\n",
"# arr = streamToNoteArray(p)\n",
"# training_arrays.append(p)\n",
" arr = streamToNoteArray(s.parts[0]) # just extract first voice\n",
" training_arrays.append(arr)\n",
" print(\"Converted:\", f, \"it took\", time.perf_counter() - start)\n",
"\n",
"training_dataset = np.array(training_arrays)\n",
"np.savez('melody_training_dataset.npz', train=training_dataset)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Load Training Data and Create RNN\n",
"\n",
"In the following we load in the training dataset, slice the melodies into example sequences and build our Melody RNN."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Training Hyperparameters:\n",
"VOCABULARY_SIZE = 130 # known 0-127 notes + 128 note_off + 129 no_event\n",
"SEQ_LEN = 30\n",
"BATCH_SIZE = 64\n",
"HIDDEN_UNITS = 256\n",
"EPOCHS = 30\n",
"SEED = 2345 # 2345 seems to be good.\n",
"np.random.seed(SEED)\n",
"\n",
"## Load up some melodies I prepared earlier...\n",
"with np.load('../datasets/melody_training_dataset.npz', allow_pickle=True) as data:\n",
" train_set = data['train']\n",
"\n",
"print(\"Training melodies:\", len(train_set))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def slice_sequence_examples(sequence, num_steps):\n",
" \"\"\"Slice a sequence into redundant sequences of lenght num_steps.\"\"\"\n",
" xs = []\n",
" for i in range(len(sequence) - num_steps - 1):\n",
" example = sequence[i: i + num_steps]\n",
" xs.append(example)\n",
" return xs\n",
"\n",
"def seq_to_singleton_format(examples):\n",
" \"\"\"\n",
" Return the examples in seq to singleton format.\n",
" \"\"\"\n",
" xs = []\n",
" ys = []\n",
" for ex in examples:\n",
" xs.append(ex[:-1])\n",
" ys.append(ex[-1])\n",
" return (xs,ys)\n",
"\n",
"# Prepare training data as X and Y.\n",
"# This slices the melodies into sequences of length SEQ_LEN+1.\n",
"# Then, each sequence is split into an X of length SEQ_LEN and a y of length 1.\n",
"\n",
"# Slice the sequences:\n",
"slices = []\n",
"for seq in train_set:\n",
" slices += slice_sequence_examples(seq, SEQ_LEN+1)\n",
"\n",
"# Split the sequences into Xs and ys:\n",
"X, y = seq_to_singleton_format(slices)\n",
"# Convert into numpy arrays.\n",
"X = np.array(X)\n",
"y = np.array(y)\n",
"\n",
"# Look at the size of the training corpus:\n",
"print(\"Total Training Corpus:\")\n",
"print(\"X:\", X.shape)\n",
"print(\"y:\", y.shape)\n",
"print()\n",
"\n",
"# Have a look at one example:\n",
"print(\"Looking at one example:\")\n",
"print(\"X:\", X[95])\n",
"print(\"y:\", y[95])\n",
"# Note: Music data is sparser than text, there's lots of 129s (do nothing)\n",
"# and few examples of any particular note on.\n",
"# As a result, it's a bit harder to train a melody-rnn."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Do some stats on the corpus.\n",
"all_notes = np.concatenate(train_set)\n",
"print(\"Number of notes:\")\n",
"print(all_notes.shape)\n",
"all_notes_df = pd.DataFrame(all_notes)\n",
"print(\"Notes that do appear:\")\n",
"unique, counts = np.unique(all_notes, return_counts=True)\n",
"print(unique)\n",
"print(\"Notes that don't appear:\")\n",
"print(np.setdiff1d(np.arange(0,129),unique))\n",
"\n",
"print(\"Plot the relative occurences of each note:\")\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"\n",
"#plt.style.use('dark_background')\n",
"plt.bar(unique, counts)\n",
"plt.yscale('log')\n",
"plt.xlabel('melody RNN value')\n",
"plt.ylabel('occurences (log scale)')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Define the Training RNN\n",
"\n",
"- The training RNN will be more complex than in the text examples.\n",
"- Using 2 layers of LSTM 256 LSTM cells each.\n",
"- Using an Embedding layer on the input (saves some effort in creating one-hot examples)\n",
"- Using sparse categorical cross entropy for loss (so that ys don't have to be one-hot)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow import keras\n",
"from tensorflow.keras.models import Sequential\n",
"from tensorflow.keras.layers import Dense, Activation\n",
"from tensorflow.keras.layers import LSTM, Dropout\n",
"from tensorflow.keras.layers import Embedding\n",
"from tensorflow.keras.optimizers import RMSprop\n",
"from tensorflow.keras.utils import get_file\n",
"from tensorflow.keras.models import load_model\n",
"\n",
"# build the model: 2-layer LSTM network.\n",
"# Using Embedding layer and sparse_categorical_crossentropy loss function \n",
"# to save some effort in preparing data.\n",
"\n",
"print('Build model...')\n",
"model_train = Sequential()\n",
"model_train.add(Embedding(VOCABULARY_SIZE, HIDDEN_UNITS, input_length=SEQ_LEN))\n",
"\n",
"# LSTM part\n",
"model_train.add(LSTM(HIDDEN_UNITS, return_sequences=True))\n",
"model_train.add(LSTM(HIDDEN_UNITS))\n",
"\n",
"# Project back to vocabulary\n",
"model_train.add(Dense(VOCABULARY_SIZE, activation='softmax'))\n",
"model_train.compile(loss='sparse_categorical_crossentropy', optimizer='adam')\n",
"model_train.summary()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Training\n",
"\n",
"- I trained this model on Google's Colaboratory system (free online Python machine learning environment, including GPU).\n",
"- Good to train for lots of epochs, I tried for 100: less is possible.\n",
"- Takes around 3 minutes per epoch on an NVidia K80 GPU = 5 hours to train.\n",
"\n",
"Here's the training diagram:\n",
"\n",
"<img src=\"figures/training_melody_rnn.png\" style=\"width: 600px;\"/>\n",
"\n",
"Probably could have stopped after about 50 epochs to save some time!\n",
"\n",
"This trained model is included in the repo, so you can go ahead and load that, or train again with your own dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Train the model (this takes time)\n",
"model_train.fit(X, y, batch_size=BATCH_SIZE, epochs=EPOCHS)\n",
"model_train.save(\"zeldic-rnn.h5\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Load if necessary - don't need to do this.\n",
"# model_train = keras.models.load_model(\"zeldic-rnn.h5\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Decoding Model\n",
"\n",
"Now we build a 1-in, 1-out model for encoding. This is the same model as for training, just with a input length of 1, and LSTM statefulness turned on.\n",
"\n",
"- Much faster to use the network with this model!\n",
"- The weights are loaded directly from the saved `train_model` file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Build a decoding model (input length 1, batch size 1, stateful)\n",
"model_dec = Sequential()\n",
"model_dec.add(Embedding(VOCABULARY_SIZE, HIDDEN_UNITS, input_length=1, batch_input_shape=(1,1)))\n",
"# LSTM part\n",
"model_dec.add(LSTM(HIDDEN_UNITS, stateful=True, return_sequences=True))\n",
"model_dec.add(LSTM(HIDDEN_UNITS, stateful=True))\n",
"\n",
"# project back to vocabulary\n",
"model_dec.add(Dense(VOCABULARY_SIZE, activation='softmax'))\n",
"model_dec.compile(loss='sparse_categorical_crossentropy', optimizer='adam')\n",
"model_dec.summary()\n",
"# set weights from training model\n",
"#model_dec.set_weights(model_train.get_weights())\n",
"model_dec.load_weights(\"zeldic-rnn.h5\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Sampling from the Model\n",
"\n",
"- We need define two functions for sampling:\n",
" - `sample`: samples from the categorical distribution output by the model, with a diversity adjustment procedure.\n",
" - `sample_model`: samples number of notes from the model using a one-note seed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def sample(preds, temperature=1.0):\n",
" \"\"\" helper function to sample an index from a probability array\"\"\"\n",
" preds = np.asarray(preds).astype('float64')\n",
" preds = np.log(preds) / temperature\n",
" exp_preds = np.exp(preds)\n",
" preds = exp_preds / np.sum(exp_preds)\n",
" probas = np.random.multinomial(1, preds, 1)\n",
" return np.argmax(probas)\n",
"\n",
"## Sampling function\n",
"\n",
"def sample_model(seed, model_name, length=400, temperature=1.0):\n",
" '''Samples a musicRNN given a seed sequence.'''\n",
" generated = [] \n",
" generated.append(seed)\n",
" next_index = seed\n",
" for i in range(length):\n",
" x = np.array([next_index])\n",
" x = np.reshape(x,(1,1))\n",
" preds = model_name.predict(x, verbose=0)[0]\n",
" next_index = sample(preds, temperature) \n",
" generated.append(next_index)\n",
" return np.array(generated)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Let's sample some music!\n",
"\n",
"- Generate 127 notes + the starting note 60 (middle C) - this corresponds to 8 bars of melody\n",
"- Turn the sequence back into a music21 stream\n",
"- Show as musial score, play it back, or save as a MIDI file!\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_dec.reset_states() # Start with LSTM state blank\n",
"o = sample_model(68, model_dec, length=127, temperature=1.2) # generate 8 bars of melody\n",
"\n",
"melody_stream = noteArrayToStream(o) # turn into a music21 stream\n",
"melody_stream.show() # show the score.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Score example:\n",
"\n",
"<!-- ![](figures/music_example.png) -->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Play generated Melody\n",
"\n",
"music21 can even play back a generated melody right in Jupyter! Cool!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"## Pay a melody stream\n",
"sp = midi.realtime.StreamPlayer(melody_stream)\n",
"sp.play()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# figure out where the user settings are kept.\n",
"from music21 import *\n",
"us = environment.UserSettings()\n",
"us.getSettingsPath()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 4
}