{ "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 }