1 #!/usr/bin/python 2 3 from __future__ import print_function 4 5 from keras.models import Sequential 6 from keras.layers import Dense 7 from keras.layers import LSTM 8 from keras.layers import GRU 9 from keras.models import load_model 10 from keras import backend as K 11 12 import numpy as np 13 14 def printVector(f, vector, name): 15 v = np.reshape(vector, (-1)); 16 #print('static const float ', name, '[', len(v), '] = \n', file=f) 17 f.write('static const opus_int16 {}[{}] = {{\n '.format(name, len(v))) 18 for i in range(0, len(v)): 19 f.write('{}'.format(int(round(8192*v[i])))) 20 if (i!=len(v)-1): 21 f.write(',') 22 else: 23 break; 24 if (i%8==7): 25 f.write("\n ") 26 else: 27 f.write(" ") 28 #print(v, file=f) 29 f.write('\n};\n\n') 30 return; 31 32 def binary_crossentrop2(y_true, y_pred): 33 return K.mean(2*K.abs(y_true-0.5) * K.binary_crossentropy(y_pred, y_true), axis=-1) 34 35 36 model = load_model("weights.hdf5", custom_objects={'binary_crossentrop2': binary_crossentrop2}) 37 38 weights = model.get_weights() 39 40 f = open('rnn_weights.c', 'w') 41 42 f.write('/*This file is automatically generated from a Keras model*/\n\n') 43 f.write('#ifdef HAVE_CONFIG_H\n#include "config.h"\n#endif\n\n#include "mlp.h"\n\n') 44 45 printVector(f, weights[0], 'layer0_weights') 46 printVector(f, weights[1], 'layer0_bias') 47 printVector(f, weights[2], 'layer1_weights') 48 printVector(f, weights[3], 'layer1_recur_weights') 49 printVector(f, weights[4], 'layer1_bias') 50 printVector(f, weights[5], 'layer2_weights') 51 printVector(f, weights[6], 'layer2_bias') 52 53 f.write('const DenseLayer layer0 = {\n layer0_bias,\n layer0_weights,\n 25, 16, 0\n};\n\n') 54 f.write('const GRULayer layer1 = {\n layer1_bias,\n layer1_weights,\n layer1_recur_weights,\n 16, 12\n};\n\n') 55 f.write('const DenseLayer layer2 = {\n layer2_bias,\n layer2_weights,\n 12, 2, 1\n};\n\n') 56 57 f.close() 58