利用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM