forked from magenta/magenta
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmelody_rnn_model.py
196 lines (166 loc) · 7.3 KB
/
melody_rnn_model.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
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
# Copyright 2019 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Melody RNN model."""
import copy
import magenta
from magenta.models.shared import events_rnn_model
import magenta.music as mm
import tensorflow as tf
DEFAULT_MIN_NOTE = 48
DEFAULT_MAX_NOTE = 84
DEFAULT_TRANSPOSE_TO_KEY = 0
class MelodyRnnModel(events_rnn_model.EventSequenceRnnModel):
"""Class for RNN melody generation models."""
def generate_melody(self, num_steps, primer_melody, temperature=1.0,
beam_size=1, branch_factor=1, steps_per_iteration=1):
"""Generate a melody from a primer melody.
Args:
num_steps: The integer length in steps of the final melody, after
generation. Includes the primer.
primer_melody: The primer melody, a Melody object.
temperature: A float specifying how much to divide the logits by
before computing the softmax. Greater than 1.0 makes melodies more
random, less than 1.0 makes melodies less random.
beam_size: An integer, beam size to use when generating melodies via beam
search.
branch_factor: An integer, beam search branch factor to use.
steps_per_iteration: An integer, number of melody steps to take per beam
search iteration.
Returns:
The generated Melody object (which begins with the provided primer
melody).
"""
melody = copy.deepcopy(primer_melody)
transpose_amount = melody.squash(
self._config.min_note,
self._config.max_note,
self._config.transpose_to_key)
melody = self._generate_events(num_steps, melody, temperature, beam_size,
branch_factor, steps_per_iteration)
melody.transpose(-transpose_amount)
return melody
def melody_log_likelihood(self, melody):
"""Evaluate the log likelihood of a melody under the model.
Args:
melody: The Melody object for which to evaluate the log likelihood.
Returns:
The log likelihood of `melody` under this model.
"""
melody_copy = copy.deepcopy(melody)
melody_copy.squash(
self._config.min_note,
self._config.max_note,
self._config.transpose_to_key)
return self._evaluate_log_likelihood([melody_copy])[0]
class MelodyRnnConfig(events_rnn_model.EventSequenceRnnConfig):
"""Stores a configuration for a MelodyRnn.
You can change `min_note` and `max_note` to increase/decrease the melody
range. Since melodies are transposed into this range to be run through
the model and then transposed back into their original range after the
melodies have been extended, the location of the range is somewhat
arbitrary, but the size of the range determines the possible size of the
generated melodies range. `transpose_to_key` should be set to the key
that if melodies were transposed into that key, they would best sit
between `min_note` and `max_note` with having as few notes outside that
range.
Attributes:
details: The GeneratorDetails message describing the config.
encoder_decoder: The EventSequenceEncoderDecoder object to use.
hparams: The HParams containing hyperparameters to use.
min_note: The minimum midi pitch the encoded melodies can have.
max_note: The maximum midi pitch (exclusive) the encoded melodies can have.
transpose_to_key: The key that encoded melodies will be transposed into, or
None if it should not be transposed.
"""
def __init__(self, details, encoder_decoder, hparams,
min_note=DEFAULT_MIN_NOTE, max_note=DEFAULT_MAX_NOTE,
transpose_to_key=DEFAULT_TRANSPOSE_TO_KEY):
super(MelodyRnnConfig, self).__init__(details, encoder_decoder, hparams)
if min_note < mm.MIN_MIDI_PITCH:
raise ValueError('min_note must be >= 0. min_note is %d.' % min_note)
if max_note > mm.MAX_MIDI_PITCH + 1:
raise ValueError('max_note must be <= 128. max_note is %d.' % max_note)
if max_note - min_note < mm.NOTES_PER_OCTAVE:
raise ValueError('max_note - min_note must be >= 12. min_note is %d. '
'max_note is %d. max_note - min_note is %d.' %
(min_note, max_note, max_note - min_note))
if (transpose_to_key is not None and
(transpose_to_key < 0 or transpose_to_key > mm.NOTES_PER_OCTAVE - 1)):
raise ValueError('transpose_to_key must be >= 0 and <= 11. '
'transpose_to_key is %d.' % transpose_to_key)
self.min_note = min_note
self.max_note = max_note
self.transpose_to_key = transpose_to_key
# Default configurations.
default_configs = {
'basic_rnn': MelodyRnnConfig(
magenta.protobuf.generator_pb2.GeneratorDetails(
id='basic_rnn',
description='Melody RNN with one-hot encoding.'),
magenta.music.OneHotEventSequenceEncoderDecoder(
magenta.music.MelodyOneHotEncoding(
min_note=DEFAULT_MIN_NOTE,
max_note=DEFAULT_MAX_NOTE)),
tf.contrib.training.HParams(
batch_size=128,
rnn_layer_sizes=[128, 128],
dropout_keep_prob=0.5,
clip_norm=5,
learning_rate=0.001)),
'mono_rnn': MelodyRnnConfig(
magenta.protobuf.generator_pb2.GeneratorDetails(
id='mono_rnn',
description='Monophonic RNN with one-hot encoding.'),
magenta.music.OneHotEventSequenceEncoderDecoder(
magenta.music.MelodyOneHotEncoding(
min_note=0,
max_note=128)),
tf.contrib.training.HParams(
batch_size=128,
rnn_layer_sizes=[128, 128],
dropout_keep_prob=0.5,
clip_norm=5,
learning_rate=0.001),
min_note=0,
max_note=128,
transpose_to_key=None),
'lookback_rnn': MelodyRnnConfig(
magenta.protobuf.generator_pb2.GeneratorDetails(
id='lookback_rnn',
description='Melody RNN with lookback encoding.'),
magenta.music.LookbackEventSequenceEncoderDecoder(
magenta.music.MelodyOneHotEncoding(
min_note=DEFAULT_MIN_NOTE,
max_note=DEFAULT_MAX_NOTE)),
tf.contrib.training.HParams(
batch_size=128,
rnn_layer_sizes=[128, 128],
dropout_keep_prob=0.5,
clip_norm=5,
learning_rate=0.001)),
'attention_rnn': MelodyRnnConfig(
magenta.protobuf.generator_pb2.GeneratorDetails(
id='attention_rnn',
description='Melody RNN with lookback encoding and attention.'),
magenta.music.KeyMelodyEncoderDecoder(
min_note=DEFAULT_MIN_NOTE,
max_note=DEFAULT_MAX_NOTE),
tf.contrib.training.HParams(
batch_size=128,
rnn_layer_sizes=[128, 128],
dropout_keep_prob=0.5,
attn_length=40,
clip_norm=3,
learning_rate=0.001))
}