dump_to_simple_cpp.py
Go to the documentation of this file.
1 import numpy as np
2 np.random.seed(1337)
3 from keras.models import Sequential, model_from_json
4 import json
5 import argparse
6 
7 np.set_printoptions(threshold=np.inf)
8 parser = argparse.ArgumentParser(description='This is a simple script to dump Keras model into simple format suitable for porting into pure C++ model')
9 
10 parser.add_argument('-a', '--architecture', help="JSON with model architecture", required=True)
11 parser.add_argument('-w', '--weights', help="Model weights in HDF5 format", required=True)
12 parser.add_argument('-o', '--output', help="Ouput file name", required=True)
13 parser.add_argument('-v', '--verbose', help="Verbose", required=False)
14 args = parser.parse_args()
15 
16 print 'Read architecture from', args.architecture
17 print 'Read weights from', args.weights
18 print 'Writing to', args.output
19 
20 arch = open(args.architecture).read()
21 model = model_from_json(arch)
22 model.load_weights(args.weights)
23 model.compile(loss='categorical_crossentropy', optimizer='adadelta')
24 arch = json.loads(arch)
25 
26 with open(args.output, 'w') as fout:
27  fout.write('layers ' + str(len(model.layers)) + '\n')
28 
29  layers = []
30  for ind, l in enumerate(arch["config"]):
31  if args.verbose:
32  print ind, l
33  fout.write('layer ' + str(ind) + ' ' + l['class_name'] + '\n')
34 
35  if args.verbose:
36  print str(ind), l['class_name']
37  layers += [l['class_name']]
38  if l['class_name'] == 'Convolution2D':
39  #fout.write(str(l['config']['nb_filter']) + ' ' + str(l['config']['nb_col']) + ' ' + str(l['config']['nb_row']) + ' ')
40 
41  #if 'batch_input_shape' in l['config']:
42  # fout.write(str(l['config']['batch_input_shape'][1]) + ' ' + str(l['config']['batch_input_shape'][2]) + ' ' + str(l['config']['batch_input_shape'][3]))
43  #fout.write('\n')
44 
45  W = model.layers[ind].get_weights()[0]
46  if args.verbose:
47  print W.shape
48  fout.write(str(W.shape[0]) + ' ' + str(W.shape[1]) + ' ' + str(W.shape[2]) + ' ' + str(W.shape[3]) + ' ' + l['config']['border_mode'] + '\n')
49 
50  for i in range(W.shape[0]):
51  for j in range(W.shape[1]):
52  for k in range(W.shape[2]):
53  fout.write(str(W[i,j,k]) + '\n')
54  fout.write(str(model.layers[ind].get_weights()[1]) + '\n')
55 
56  if l['class_name'] == 'Activation':
57  fout.write(l['config']['activation'] + '\n')
58  if l['class_name'] == 'MaxPooling2D':
59  fout.write(str(l['config']['pool_size'][0]) + ' ' + str(l['config']['pool_size'][1]) + '\n')
60  #if l['class_name'] == 'Flatten':
61  # print l['config']['name']
62  if l['class_name'] == 'Dense':
63  #fout.write(str(l['config']['output_dim']) + '\n')
64  W = model.layers[ind].get_weights()[0]
65  if args.verbose:
66  print W.shape
67  fout.write(str(W.shape[0]) + ' ' + str(W.shape[1]) + '\n')
68 
69 
70  for w in W:
71  fout.write(str(w) + '\n')
72  fout.write(str(model.layers[ind].get_weights()[1]) + '\n')
procfile open("FD_BRL_v0.txt")