1#!/usr/bin/python 2 3from __future__ import print_function 4 5from keras.models import Sequential 6from keras.layers import Dense 7from keras.layers import LSTM 8from keras.layers import GRU 9from keras.models import load_model 10from keras import backend as K 11 12import numpy as np 13 14def 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 32def 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 36model = load_model("weights.hdf5", custom_objects={'binary_crossentrop2': binary_crossentrop2}) 37 38weights = model.get_weights() 39 40f = open('rnn_weights.c', 'w') 41 42f.write('/*This file is automatically generated from a Keras model*/\n\n') 43f.write('#ifdef HAVE_CONFIG_H\n#include "config.h"\n#endif\n\n#include "mlp.h"\n\n') 44 45printVector(f, weights[0], 'layer0_weights') 46printVector(f, weights[1], 'layer0_bias') 47printVector(f, weights[2], 'layer1_weights') 48printVector(f, weights[3], 'layer1_recur_weights') 49printVector(f, weights[4], 'layer1_bias') 50printVector(f, weights[5], 'layer2_weights') 51printVector(f, weights[6], 'layer2_bias') 52 53f.write('const DenseLayer layer0 = {\n layer0_bias,\n layer0_weights,\n 25, 16, 0\n};\n\n') 54f.write('const GRULayer layer1 = {\n layer1_bias,\n layer1_weights,\n layer1_recur_weights,\n 16, 12\n};\n\n') 55f.write('const DenseLayer layer2 = {\n layer2_bias,\n layer2_weights,\n 12, 2, 1\n};\n\n') 56 57f.close() 58