有一个MNIST神经网络的Python代码,我们已使用该代码来识别脚本中的古吉拉特语字符。为此,我们借助QT框架以C ++语言开发了一个GUI。目前,神经网络代码是在python中执行的,但是在通过C ++执行MNIST模型代码时,我们遇到了问题。我找到了一个名为Keras2CPP的GitHub,它具有一个dump_to_simple_cpp.py文件。该文件接受weights.h5权重文件和model_json文件,然后生成dumped.nnet文件。 dump_to_simple_cpp.py文件如下:
import numpy as np
np.random.seed(1337)
from keras.models import Sequential, model_from_json
import json
import argparse
np.set_printoptions(threshold=np.inf)
parser = argparse.ArgumentParser(description='This is a simple script
to dump Keras model into simple format suitable for porting into pure
C++ model')
parser.add_argument('-a', '--architecture', help="JSON with model
architecture", required=True)
parser.add_argument('-w', '--weights', help="Model weights in HDF5
format", required=True)
parser.add_argument('-o', '--output', help="Ouput file name",
required=True)
parser.add_argument('-v', '--verbose', help="Verbose", required=False)
args = parser.parse_args()
print('Read architecture from', args.architecture)
print('Read weights from', args.weights)
print('Writing to', args.output)
arch = open(args.architecture).read()
model = model_from_json(arch)
model.load_weights(args.weights)
model.compile(loss='categorical_crossentropy', optimizer='adadelta')
arch = json.loads(arch)
with open(args.output, 'w') as fout:
fout.write('layers ' + str(len(model.layers)) + '\n')
layers = []
for ind, l in enumerate(arch["config"]):
if args.verbose:
print(ind, l)
fout.write('layer ' + str(ind) + ' ' + l['class_name'] + '\n') #line number: 33
if args.verbose:
print(str(ind), l['class_name'])
layers += [l['class_name']]
if l['class_name'] == 'Convolution2D':
W = model.layers[ind].get_weights()[0]
if args.verbose:
print(W.shape)
fout.write(str(W.shape[0]) + ' ' + str(W.shape[1]) + ' ' + str(W.shape[2]) + ' ' + str(W.shape[3]) + ' ' + l['config']['border_mode'] + '\n')
for i in range(W.shape[0]):
for j in range(W.shape[1]):
for k in range(W.shape[2]):
fout.write(str(W[i,j,k]) + '\n')
fout.write(str(model.layers[ind].get_weights()[1]) + '\n')
if l['class_name'] == 'Activation':
fout.write(l['config']['activation'] + '\n')
if l['class_name'] == 'MaxPooling2D':
fout.write(str(l['config']['pool_size'][0]) + ' ' + str(l['config']['pool_size'][1]) + '\n')
if l['class_name'] == 'Dense':
W = model.layers[ind].get_weights()[0]
if args.verbose:
print(W.shape)
fout.write(str(W.shape[0]) + ' ' + str(W.shape[1]) + '\n')
for w in W:
fout.write(str(w) + '\n')
fout.write(str(model.layers[ind].get_weights()[1]) + '\n')
在以下命令的帮助下执行以上代码:
python3 dump_to_simple_cpp.py -a model_json -w model.h5 -o dumped.nnet
将引发以下错误:
File "dump_to_simple_cpp.py", line 33, in <module>
fout.write('layer ' + str(ind) + ' ' + l['class_name'] + '\n')
TypeError: string indices must be integers
有人可以帮助我解决上述错误吗?