dump_rnn.py 1.9 KB

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