|
| 1 | +from common import get_layer_output_function, WINDOW_SIZE, WINDOW_STRIDE |
| 2 | +from keras.models import model_from_yaml |
| 3 | +import librosa as lbr |
| 4 | +import numpy as np |
| 5 | +from functools import partial |
| 6 | +from optparse import OptionParser |
| 7 | +import cPickle |
| 8 | +import os |
| 9 | + |
| 10 | +def compose(f, g): |
| 11 | + return lambda x: f(g(x)) |
| 12 | + |
| 13 | +def undo_layer(length, stride, (i, j)): |
| 14 | + return (stride * i, stride * (j - 1) + length) |
| 15 | + |
| 16 | +def extract_filters(model, data, filters_path, count0): |
| 17 | + x = data['x'] |
| 18 | + track_paths = data['track_paths'] |
| 19 | + |
| 20 | + conv_layer_names = [] |
| 21 | + i = 1 |
| 22 | + while True: |
| 23 | + name = 'convolution_' + str(i) |
| 24 | + if model.get_layer(name) is None: |
| 25 | + break |
| 26 | + conv_layer_names.append(name) |
| 27 | + i += 1 |
| 28 | + |
| 29 | + # Generate undoers for every convolutional layer. Undoer is a function |
| 30 | + # translating a pair of coordinates in feature space (mel spectrograms or |
| 31 | + # features extracted by convolutional layers) to the sample space (raw |
| 32 | + # audio signal). |
| 33 | + conv_layer_undoers = [] |
| 34 | + |
| 35 | + # undo the mel spectrogram extraction |
| 36 | + undoer = partial(undo_layer, WINDOW_SIZE, WINDOW_STRIDE) |
| 37 | + |
| 38 | + for name in conv_layer_names: |
| 39 | + layer = model.get_layer(name) |
| 40 | + length = layer.filter_length |
| 41 | + stride = layer.subsample_length |
| 42 | + |
| 43 | + # undo the convolution layer |
| 44 | + undoer = compose(partial(undo_layer, length, stride), undoer) |
| 45 | + conv_layer_undoers.append(undoer) |
| 46 | + |
| 47 | + # undo the pooling layer |
| 48 | + undoer = compose(partial(undo_layer, 2, 2), undoer) |
| 49 | + conv_layer_output_funs = \ |
| 50 | + map(partial(get_layer_output_function, model), conv_layer_names) |
| 51 | + |
| 52 | + # Extract track chunks with highest activations for each filter in each |
| 53 | + # convolutional layer. |
| 54 | + for (layer_index, output_fun) in enumerate(conv_layer_output_funs): |
| 55 | + layer_path = os.path.join(filters_path, conv_layer_names[layer_index]) |
| 56 | + if not os.path.exists(layer_path): |
| 57 | + os.makedirs(layer_path) |
| 58 | + |
| 59 | + print 'Computing outputs for layer', conv_layer_names[layer_index] |
| 60 | + output = output_fun(x) |
| 61 | + |
| 62 | + # matrices of shape n_tracks x time x n_filters |
| 63 | + max_over_time = np.amax(output, axis=1) |
| 64 | + argmax_over_time = np.argmax(output, axis=1) |
| 65 | + |
| 66 | + # number of input chunks to extract for each filter |
| 67 | + count = count0 // 2 ** layer_index |
| 68 | + argmax_over_track = \ |
| 69 | + np.argpartition(max_over_time, -count, axis=0)[-count :, :] |
| 70 | + |
| 71 | + undoer = conv_layer_undoers[layer_index] |
| 72 | + |
| 73 | + for filter_index in xrange(argmax_over_track.shape[1]): |
| 74 | + print 'Processing layer', conv_layer_names[layer_index], \ |
| 75 | + 'filter', filter_index |
| 76 | + |
| 77 | + track_indices = argmax_over_track[:, filter_index] |
| 78 | + time_indices = argmax_over_time[track_indices, filter_index] |
| 79 | + sample_rate = [None] |
| 80 | + |
| 81 | + def extract_sample_from_track(undoer, (track_index, time_index)): |
| 82 | + track_path = track_paths[track_index] |
| 83 | + (track_samples, sample_rate[0]) = lbr.load(track_path, |
| 84 | + mono=True) |
| 85 | + (t1, t2) = undoer((time_index, time_index + 1)) |
| 86 | + return track_samples[t1 : t2] |
| 87 | + |
| 88 | + samples_for_filter = np.concatenate( |
| 89 | + map(partial(extract_sample_from_track, undoer), |
| 90 | + zip(track_indices, time_indices))) |
| 91 | + |
| 92 | + filter_path = os.path.join(layer_path, |
| 93 | + '{}.wav'.format(filter_index)) |
| 94 | + lbr.output.write_wav(filter_path, samples_for_filter, |
| 95 | + sample_rate[0]) |
| 96 | + |
| 97 | +if __name__ == '__main__': |
| 98 | + parser = OptionParser() |
| 99 | + parser.add_option('-m', '--model_path', dest='model_path', |
| 100 | + default=os.path.join(os.path.dirname(__file__), |
| 101 | + 'models/model.yaml'), |
| 102 | + help='path to the model YAML file', metavar='MODEL_PATH') |
| 103 | + parser.add_option('-w', '--weights_path', dest='weights_path', |
| 104 | + default=os.path.join(os.path.dirname(__file__), |
| 105 | + 'models/weights.h5'), |
| 106 | + help='path to the model weights hdf5 file', |
| 107 | + metavar='WEIGHTS_PATH') |
| 108 | + parser.add_option('-d', '--data_path', dest='data_path', |
| 109 | + default=os.path.join(os.path.dirname(__file__), |
| 110 | + 'data/data.pkl'), |
| 111 | + help='path to the data pickle', |
| 112 | + metavar='DATA_PATH') |
| 113 | + parser.add_option('-f', '--filters_path', dest='filters_path', |
| 114 | + default=os.path.join(os.path.dirname(__file__), |
| 115 | + 'filters'), |
| 116 | + help='path to the output filters directory', |
| 117 | + metavar='FILTERS_PATH') |
| 118 | + parser.add_option('-c', '--count0', dest='count0', |
| 119 | + default='4', |
| 120 | + help=('number of chunks to extract from the first convolutional ' + |
| 121 | + 'layer, this number is halved for each next layer'), |
| 122 | + metavar='COUNT0') |
| 123 | + options, args = parser.parse_args() |
| 124 | + |
| 125 | + with open(options.model_path, 'r') as f: |
| 126 | + model = model_from_yaml(f.read()) |
| 127 | + model.load_weights(options.weights_path) |
| 128 | + |
| 129 | + with open(options.data_path, 'r') as f: |
| 130 | + data = cPickle.load(f) |
| 131 | + |
| 132 | + extract_filters(model, data, options.filters_path, int(options.count0)) |
0 commit comments