• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python
2
3from __future__ import print_function
4
5from keras.models import Sequential
6from keras.models import Model
7from keras.layers import Input
8from keras.layers import Dense
9from keras.layers import LSTM
10from keras.layers import GRU
11from keras.models import load_model
12from keras import backend as K
13import sys
14
15import numpy as np
16
17def printVector(f, vector, name):
18    v = np.reshape(vector, (-1));
19    #print('static const float ', name, '[', len(v), '] = \n', file=f)
20    f.write('static const opus_int8 {}[{}] = {{\n   '.format(name, len(v)))
21    for i in range(0, len(v)):
22        f.write('{}'.format(max(-128,min(127,int(round(128*v[i]))))))
23        if (i!=len(v)-1):
24            f.write(',')
25        else:
26            break;
27        if (i%8==7):
28            f.write("\n   ")
29        else:
30            f.write(" ")
31    #print(v, file=f)
32    f.write('\n};\n\n')
33    return;
34
35def binary_crossentrop2(y_true, y_pred):
36        return K.mean(2*K.abs(y_true-0.5) * K.binary_crossentropy(y_pred, y_true), axis=-1)
37
38
39#model = load_model(sys.argv[1], custom_objects={'binary_crossentrop2': binary_crossentrop2})
40main_input = Input(shape=(None, 25), name='main_input')
41x = Dense(32, activation='tanh')(main_input)
42x = GRU(24, activation='tanh', recurrent_activation='sigmoid', return_sequences=True)(x)
43x = Dense(2, activation='sigmoid')(x)
44model = Model(inputs=main_input, outputs=x)
45model.load_weights(sys.argv[1])
46
47weights = model.get_weights()
48
49f = open(sys.argv[2], 'w')
50
51f.write('/*This file is automatically generated from a Keras model*/\n\n')
52f.write('#ifdef HAVE_CONFIG_H\n#include "config.h"\n#endif\n\n#include "mlp.h"\n\n')
53
54printVector(f, weights[0], 'layer0_weights')
55printVector(f, weights[1], 'layer0_bias')
56printVector(f, weights[2], 'layer1_weights')
57printVector(f, weights[3], 'layer1_recur_weights')
58printVector(f, weights[4], 'layer1_bias')
59printVector(f, weights[5], 'layer2_weights')
60printVector(f, weights[6], 'layer2_bias')
61
62f.write('const DenseLayer layer0 = {\n   layer0_bias,\n   layer0_weights,\n   25, 32, 0\n};\n\n')
63f.write('const GRULayer layer1 = {\n   layer1_bias,\n   layer1_weights,\n   layer1_recur_weights,\n   32, 24\n};\n\n')
64f.write('const DenseLayer layer2 = {\n   layer2_bias,\n   layer2_weights,\n   24, 2, 1\n};\n\n')
65
66f.close()
67