-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.py
126 lines (98 loc) · 3.77 KB
/
generate.py
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
# -*- coding: utf-8 -*-
"""predict.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1cG7NsSItxTTiFGeb7a-bFHmr4ZYzFYYa
"""
import pickle
import numpy
from music21 import instrument, note, stream, chord
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.layers import BatchNormalization as BatchNorm
from keras.layers import Activation
def generate():
with open('drive/My Drive/music generation with tensorflow/data/notes', 'rb') as filepath:
notes = pickle.load(filepath)
pitchnames = sorted(set(item for item in notes))
n_vocab = len(set(notes))
network_input, normalized_input = prepare_sequences(notes, pitchnames, n_vocab)
model = create_network(normalized_input, n_vocab)
prediction_output = generate_notes(model, network_input, pitchnames, n_vocab)
generate_midi(prediction_output)
def prepare_sequences(notes, pitchnames, n_vocab):
note_to_int = dict((note, number) for number, note in enumerate(pitchnames))
sequence_length = 100
network_input = []
output = []
for i in range(0, len(notes) - sequence_length, 1):
sequence_in = notes[i:i + sequence_length]
sequence_out = notes[i + sequence_length]
network_input.append([note_to_int[char] for char in sequence_in])
output.append(note_to_int[sequence_out])
n_patterns = len(network_input)
normalized_input = numpy.reshape(network_input, (n_patterns, sequence_length, 1))
normalized_input = normalized_input / float(n_vocab)
return (network_input, normalized_input)
def create_network(network_ip, n_vocab):
model = Sequential()
model.add(LSTM(
512,
input_shape=(network_ip.shape[1], network_ip.shape[2]),
recurrent_dropout = 0.3,
return_sequences = True
))
model.add(LSTM(512, return_sequences=True, recurrent_dropout=0.3))
model.add(LSTM(512))
model.add(BatchNorm())
model.add(Dropout(0.3))
model.add(Dense(256))
model.add(Activation('relu'))
model.add(BatchNorm())
model.add(Dropout(0.3))
model.add(Dense(n_vocab))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.load_weights('drive/My Drive/music generation with tensorflow/weights.hdf5')
return model
def generate_notes(model, network_ip, pitchnames, n_vocab):
start = numpy.random.randint(0, len(network_ip)-1)
int_to_note = dict((number, note) for number, note in enumerate(pitchnames))
patt = network_ip[start]
pred_op = []
for note_index in range(500):
pred_ip = numpy.reshape(patt, (1, len(patt), 1))
pred_ip = pred_ip / float(n_vocab)
prediction = model.predict(pred_ip, verbose=0)
index = numpy.argmax(prediction)
result = int_to_note[index]
pred_op.append(result)
patt.append(index)
patt = patt[1:len(patt)]
return pred_op
def generate_midi(pred_op):
offset = 0
output_notes = []
for pattern in pred_op:
if ('.' in pattern) or pattern.isdigit():
notes_in_chord = pattern.split('.')
notes = []
for curr_note in notes_in_chord:
new_note = note.Note(int(curr_note))
new_note.storedInstrument = instrument.Piano()
notes.append(new_note)
new_chord = chord.Chord(notes)
new_chord.offset = offset
output_notes.append(new_chord)
else:
new_note = note.Note(pattern)
new_note.offset = offset
new_note.storedInstrument = instrument.Piano()
output_notes.append(new_note)
offset += 0.5
midi_stream = stream.Stream(output_notes)
midi_stream.write('midi', fp='test2.mid')
if __name__ == '__main__':
generate()