利用MMdnn对比keras和mxnet

关键字 MMdnn,keras,mxnet,resnet50

需求:想测试一下keras下model转到MXNet框架下对于同一张图片各中间层输出结果有什么差异。

一. 前期准备

1. 依赖库的选择

由于各个库之间的依赖关系是存在限制关系的,最新的版本未必是最合适的,因此通过比较,最终确定的各个依赖库版本如下:

Python 3.5

Anaconda 4.2.0

Tensorflow 1.13.1

Mxnet 1.4.0

Mmdnn 0.2.4

Numpy 1.16.2

但是 mxnet 1.4.0.post0 要求numpy的版本<1.15.0,>=1.8.2,理论上来说是会出问题的,但是使用的时候没有报错。

2. 预训练模型的下载

使用resnet50为测试模型,按照MMdnn文档的指示,下载resnet50的预训练模型只需要如下命令:

mmdownload -f keras -n resnet50

二. 正式开始

将keras模型转化为Mxnet模型,官方提供了两种方法,为了对比keras和Mxnet便于调试,使用Step by Step方式,其步骤如下。

Step 1

mmtoir -f keras -w imagenet_resnet50.h5 -o converted

IR network structure is saved as [converted.json].

IR network structure is saved as [converted.pb].

IR weights are saved as [converted.npy].

Then you got the intermediate representation files converted.json for visualization, converted.pb and converted.npy for next steps.

Step 2

mmtocode -f mxnet -d converted_resnet50_mxnet.py -n converted.pb -w converted.npy -dw mxnet_converted-0000.param

And you will get a file named converted_resnet50_mxnet.py, which contains the mxnet codes to build the resnet50 network, the file named mxnet_converted-0000.param contains the parameters to build the network.

通过上述两个步骤即可得到keras到mxnet的resnet50的转换代码。

三. 框架对比

为了输出两种框架的中间结果,需要对代码进行处理(以最后一层为例)。

1. Keras

layer_model = Model(inputs=model.input, outputs=model.layers[-1].output)

其中-1表示的是resnet50最后一层输出的结果

features_keras =layer_model.predict(x_keras)

features_keras最后的数据就是最后的结果

2. Mxnet

fc1000_activation = mx.sym.SoftmaxOutput(data = fc1000, name = 'softmax')

group = mx.symbol.Group([fc1000_activation])

model = mx.mod.Module(symbol = group, context = mx.cpu(), data_names = ['input_1'])

model.forward(Batch([mx.nd.array(img)]))

features_mxnet = model.get_outputs()[0]

features_mxnet = features_mxnet.asnumpy()

features_keras最后的数据就是最后的结果

四. 结论

在预处理相同操作的情况下,比较了很多层基本上都是相同的,以最后一层为例,其误差量级是e-13左右,差值的方差是e-17左右。

clip_image001

参考:

[1]. https://github.com/Microsoft/MMdnn

[2]. https://github.com/Microsoft/MMdnn/blob/master/docs/keras2cntk.md

[3]. https://blog.csdn.net/u010414386/article/details/55668880

猜你喜欢

转载自www.cnblogs.com/shiML/p/10735758.html
今日推荐