File size: 5,193 Bytes
564354e |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pickle, glob\n",
"import numpy as np\n",
"import keras.utils as keras_utils\n",
"from keras.models import Sequential\n",
"from keras.layers import Dense\n",
"from keras.layers import Dropout\n",
"from keras.layers import LSTM\n",
"from keras.layers import BatchNormalization as BatchNorm\n",
"from keras.layers import Activation\n",
"from keras.callbacks import ModelCheckpoint, EarlyStopping\n",
"from music21 import converter, instrument, note, chord"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# To generate a new list of notes to train against\n",
"# notes = []\n",
"# for file in glob.glob(\"./midi_songs/*.mid\"):\n",
"# midi = converter.parse(file)\n",
"# notes_to_parse = None\n",
"# parts = instrument.partitionByInstrument(midi)\n",
"# if parts: # file has instrument parts\n",
"# notes_to_parse = parts.parts[0].recurse()\n",
"# else: # file has notes in a flat structure\n",
"# notes_to_parse = midi.flat.notes\n",
"# for element in notes_to_parse:\n",
"# if isinstance(element, note.Note):\n",
"# notes.append(str(element.pitch))\n",
"# elif isinstance(element, chord.Chord):\n",
"# notes.append('.'.join(str(n) for n in element.normalOrder))\n",
"\n",
"# with open('data/music_notes.pkl', 'wb') as filepath:\n",
"# pickle.dump(notes, filepath)\n",
"# pickle.dump(pitchnames, filepath)\n",
"# pickle.dump(n_vocab, filepath)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open('data/music_notes.pkl', 'rb') as filepath:\n",
" notes = pickle.load(filepath)\n",
" pitchnames = pickle.load(filepath)\n",
" n_vocab = pickle.load(filepath)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"sequence_length = 100\n",
"# get all pitch names\n",
"pitchnames = sorted(set(item for item in notes))\n",
"# create a dictionary to map pitches to integers\n",
"note_to_int = dict((note, number) for number, note in enumerate(pitchnames))\n",
"network_input = []\n",
"network_output = []\n",
"# create input sequences and the corresponding outputs\n",
"for i in range(0, len(notes) - sequence_length, 1):\n",
" sequence_in = notes[i:i + sequence_length]\n",
" sequence_out = notes[i + sequence_length]\n",
" network_input.append([note_to_int[char] for char in sequence_in])\n",
" network_output.append(note_to_int[sequence_out])\n",
"n_patterns = len(network_input)\n",
"# reshape the input into a format compatible with LSTM layers\n",
"network_input = np.reshape(network_input, (n_patterns, sequence_length, 1))\n",
"# normalize input\n",
"network_input = network_input / float(n_vocab)\n",
"network_output = keras_utils.to_categorical(network_output)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model = Sequential()\n",
"model.add(LSTM(\n",
" 512,\n",
" input_shape=(network_input.shape[1], network_input.shape[2]),\n",
" recurrent_dropout=0.3,\n",
" return_sequences=True\n",
"))\n",
"model.add(LSTM(512, return_sequences=True, recurrent_dropout=0.3,))\n",
"model.add(LSTM(512))\n",
"model.add(BatchNorm())\n",
"model.add(Dropout(0.3))\n",
"model.add(Dense(256))\n",
"model.add(Activation('relu'))\n",
"model.add(BatchNorm())\n",
"model.add(Dropout(0.3))\n",
"model.add(Dense(n_vocab))\n",
"model.add(Activation('softmax'))\n",
"model.compile(loss='categorical_crossentropy', optimizer='rmsprop')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"checkpoint_filepath = \"./models/model.keras\" \n",
"checkpoint = ModelCheckpoint(\n",
" filepath=checkpoint_filepath,\n",
" monitor='loss',\n",
" mode='min',\n",
" save_best_only=True,\n",
" verbose=0\n",
")\n",
"early_stopping = EarlyStopping(\n",
" monitor=\"loss\",\n",
" patience=10,\n",
" min_delta=0.001,\n",
" restore_best_weights=True,\n",
")\n",
"callbacks_list = [early_stopping, checkpoint] \n",
"model.fit(network_input, network_output, epochs=1000, batch_size=64, callbacks=callbacks_list)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"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.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|