def note(self, pitch=60, dur=1, velocity=80, layer=0, keycode=None, affect=True): if pitch in self.locked_pitches and keycode != self.locked_pitches[pitch]: #print 'restricted pitch',pitch return if self.silence: return if velocity <= 1 and type(velocity) is float: adjusted_velocity = int(round(scale(velocity, 0., 1., *self.velocity_scale))) else: adjusted_velocity = int(round(scale(velocity, 0, 127, *self.velocity_scale))) if self.sustain: dur = 0.1 # set duration to minimum, since pedal will be down anyway. if affect: self._addFunc(MidiPlayer.note, self, pitch, dur, adjusted_velocity, layer) else: MidiPlayer.note(self, pitch, dur, velocity, layer)
def generate_train(self): batch_size = self.batch_size indexes = self.tr_indexes samples = len(indexes) self.random_state.shuffle(indexes) iteration = 0 pointer = 0 while True: # Reset pointer if pointer >= samples: pointer = 0 self.random_state.shuffle(indexes) # Get batch indexes batch_indexes = indexes[pointer : pointer + batch_size] pointer += batch_size iteration += 1 if self.scale: batch_x = scale(self.x[batch_indexes], self.mean, self.std) batch_y = self.y[batch_indexes] yield batch_x, batch_y
def transform(self, x): """Transform data. Args: x: (batch_x, seq_len, freq_bins) | (seq_len, freq_bins) Returns: Transformed data. """ return scale(x, self.mean, self.std)
def _play(self): self.jazziness = Jazziness.retrieve() i = 0 skip = False self.time = time.time() while self.playing: swing = self.jazziness.swing jaggedness = self.jazziness.jaggedness if jaggedness > .5: midi.setSustain(False) else: midi.setSustain(True) for beattype in 'long', 'short': pitch = self.pitch_map.pick() dur = self.dur if self.rhythm[self.i] == 1: i += 1 elif self.rhythm[self.i] == 2 and not skip: skip = True elif skip: skip = False i += 1 if beattype == 'long': dur *= swing else: dur *= (1 - swing) self.time += dur time.sleep(self.time - time.time()) continue velocity = int( scale(self.velocity_map.pick(), 0, 127, (1. - jaggedness) * .4 * 127, 127 - (1. - jaggedness) * .6 * 127)) self._out(pitch, 0.2, velocity, 1) self.skip = 0 self.i = (self.i + 1) % len(self.rhythm) if beattype == 'long': dur *= swing else: dur *= (1 - swing) self.time += dur time.sleep(self.time - time.time())
def _play(self): self.jazziness = Jazziness.retrieve() i = 0 skip = False self.time = time.time() while self.playing: swing = self.jazziness.swing jaggedness = self.jazziness.jaggedness if jaggedness > .5: midi.setSustain(False) else: midi.setSustain(True) for beattype in 'long', 'short': pitch = self.pitch_map.pick() dur = self.dur if self.rhythm[self.i] == 1: i+=1 elif self.rhythm[self.i] == 2 and not skip: skip = True elif skip: skip = False i += 1 if beattype == 'long': dur *= swing else: dur *= (1-swing) self.time += dur time.sleep(self.time - time.time()) continue velocity = int(scale(self.velocity_map.pick(), 0, 127, (1.-jaggedness)*.4*127, 127-(1.-jaggedness)*.6*127)) self._out(pitch, 0.2, velocity, 1) self.skip = 0 self.i = (self.i + 1) % len(self.rhythm) if beattype == 'long': dur *= swing else: dur *= (1-swing) self.time += dur time.sleep(self.time - time.time())
def _play(self): if self.crescendo: self.ramp(self.velocity, self.velocity + 30, 15) duration = 0. while self.playing: if len(self.pitches) > 2: random.shuffle(self.pitches) for pitch in self.pitches: vel = scale(self.velocity, 0, 127, 10, 127) vel = int(self.velocity + random.randint(-5, 5)) vel = min(max(vel, 0), 127) self._out(pitch, 0.03, vel) wait = 0.05 + random.randint(0, 10) / 1000. time.sleep(wait) duration += wait if duration > 15 and self.crescendo: events.send('long_tremolo') duration = 0.
def _play(self): if self.crescendo: self.ramp(self.velocity, self.velocity+30, 15) duration = 0. while self.playing: if len(self.pitches) > 2: random.shuffle(self.pitches) for pitch in self.pitches: vel = scale(self.velocity, 0, 127, 10, 127) vel = int(self.velocity + random.randint(-5, 5)) vel = min(max(vel, 0), 127) self._out(pitch, 0.03, vel) wait = 0.05 + random.randint(0, 10) / 1000. time.sleep(wait) duration += wait if duration > 15 and self.crescendo: events.send('long_tremolo') duration = 0.
def generate_validate(self, data_type, max_iteration): batch_size = self.batch_size if data_type == 'train': indexes = self.tr_indexes elif data_type == 'validate': indexes = self.va_indexes else: raise Exception("Invalid data_type!") samples = len(indexes) iteration = 0 pointer = 0 while True: if iteration == max_iteration: break # Reset pointer if pointer >= samples: break # Get batch indexes batch_indexes = indexes[pointer : pointer + batch_size] pointer += batch_size iteration += 1 if self.scale: batch_x = scale(self.x[batch_indexes], self.mean, self.std) batch_y = self.y[batch_indexes] yield batch_x, batch_y
def transform(self, x): '''Transform data. ''' return scale(x, self.scalar['mean'], self.scalar['std'])
def transform_harmonic(self, x): return scale(x, self.scalar_harmonic['mean'], self.scalar_harmonic['std'])
def transform_percussive(self, x): return scale(x, self.scalar_percussive['mean'], self.scalar_percussive['std'])
def transform_right(self, x): return scale(x, self.scalar_right['mean'], self.scalar_right['std'])
def transform_side(self, x): return scale(x, self.scalar_side['mean'], self.scalar_side['std'])
def scale(self, width, height): if hasattr(self, 'bezier') and self.bezier: utilities.scale(self.nodes, width, height, True) else: utilities.scale(self.nodes, width, height)
def scale(self, width, height): utilities.scale(self.nodes, width, height)
def transform_mfcc(self, x): return scale(x, self.scalar['mean_mfcc'], self.scalar['std_mfcc'])
def transform(self, x): return scale(x, self.scalar['mean'], self.scalar['std'])
ignored_test_truncated += 1 if settings.ignore_difficult and data.difficult: create = False ignored_test_difficult += 1 if create: crop = utilities.crop_image(img, data.x1, data.y1, data.x2, data.y2) crop_size = crop.shape[0] + crop.shape[1] if settings.use_size_threshold and crop_size <= settings.size_threshold: ignored_test_size_thresh += 1 ignored_test += 1 create = False else: resized64 = utilities.scale(64, crop, 256) cv2.imwrite(new_path_64, resized64) resized256 = utilities.scale(256, crop, 256) cv2.imwrite(new_path_256, resized256) new_test_filelist.append(filepath + ' ' + str(data.classid) + '\n') else: ignored_test += 1 filelist64 = open(settings.result_path + '64/test/filelist.txt', 'w') filelist256 = open(settings.result_path + '256/test/filelist.txt', 'w') filelist64.writelines(new_test_filelist) filelist64.close() filelist256.writelines(new_test_filelist) filelist256.close() print ''
def transform_gamm(self, x): return scale(x, self.scalar['mean_gamm'], self.scalar['std_gamm'])
def transform(self, x): return scale(x, self.mean, self.std)
def transform_panns(self, x): return scale(x, self.scalar['mean_panns'], self.scalar['std_panns'])
def train(D, G, n_epochs, print_every=50): """Trains adversarial networks for some number of epochs param, D: the discriminator network param, G: the generator network param, n_epochs: number of epochs to train for param, print_every: when to print and record the models' losses return: D and G losses""" # move models to GPU if args.train_on_gpu: D.cuda() G.cuda() # keep track of loss and generated, "fake" samples samples = [] losses = [] # Get some fixed data for sampling. These are images that are held # constant throughout training, and allow us to inspect the model's performance sample_size = 16 fixed_z = np.random.uniform(-1, 1, size=(sample_size, args.z_size)) fixed_z = torch.from_numpy(fixed_z).float() # move z to GPU if available if args.train_on_gpu: fixed_z = fixed_z.cuda() # epoch training loop for epoch in range(n_epochs): # batch training loop for batch_i, (real_images, _) in enumerate(celeba_train_loader): batch_size = real_images.size(0) real_images = scale(real_images) # =============================================== # YOUR CODE HERE: TRAIN THE NETWORKS # =============================================== # 1. Train the discriminator on real and fake images d_optimizer.zero_grad() if args.train_on_gpu: real_images = real_images.cuda() D_real = D(real_images) d_real_loss = real_loss(D_real) z = np.random.uniform(-1, 1, size=(batch_size, args.z_size)) z = torch.from_numpy(z).float() if args.train_on_gpu: z = z.cuda() fake_images = G(z) D_fake = D(fake_images) d_fake_loss = fake_loss(D_fake) d_loss = d_real_loss + d_fake_loss d_loss.backward() d_optimizer.step() # 2. Train the generator with an adversarial loss g_optimizer.zero_grad() z = np.random.uniform(-1, 1, size=(batch_size, args.z_size)) z = torch.from_numpy(z).float() if args.train_on_gpu: z = z.cuda() fake_images = G(z) D_fake = D(fake_images) g_loss = real_loss(D_fake) g_loss.backward() g_optimizer.step() # =============================================== # END OF YOUR CODE # =============================================== # Print some loss stats if batch_i % print_every == 0: # append discriminator loss and generator loss losses.append((d_loss.item(), g_loss.item())) # print discriminator and generator loss print( 'Epoch [{:5d}/{:5d}] | d_loss: {:6.4f} | g_loss: {:6.4f}'. format(epoch + 1, n_epochs, d_loss.item(), g_loss.item())) ## AFTER EACH EPOCH## # this code assumes your generator is named G, feel free to change the name # generate and save sample, fake images G.eval() # for generating samples samples_z = G(fixed_z) samples.append(samples_z) G.train() # back to training mode # Save training generator samples with open('train_samples.pkl', 'wb') as f: pkl.dump(samples, f) # finally return losses return losses