3.1 KiB
Keras "inception_v3" to CNTK conversion example
Model: "inception_v3" for ImageNet
Source: Keras 2.1.3
Destination: CNTK 2.4
Framework Installation
Install Keras and CNTK in case
$ pip install keras
$ pip install https://cntk.ai/PythonWheel/CPU-Only/cntk-2.4-cp27-cp27mu-linux_x86_64.whl
or
$ pip install https://cntk.ai/PythonWheel/CPU-Only/cntk-2.4-cp35-cp35m-linux_x86_64.whl
Keras Model Preparation
You need to prepare your pre-trained keras model firstly. And there is a pre-trained model extractor for frameworks to help you. You can refer it to extract your Keras model structure and weights.
$ mmdownload -f keras -n inception_v3
Keras model inception_v3 is saved in [./imagenet_inception_v3.h5]
The you got the Keras pre-trained inception_v3 model which is downloaded to current working directory.
Convert Keras Model to CNTK
We provide two ways to convert models.
One-step Command
Above MMdnn@0.1.4, we provide one command to achieve the conversion
$ mmconvert -sf keras -iw imagenet_inception_v3.h5 -df cntk -om keras_to_cntk_inception_v3.dnn
.
.
.
CNTK model file is saved as [keras_to_cntk_inception_v3.dnn], generated by [2c33f7f278cb46be992f50226fcfdb5d.py] and [2c33f7f278cb46be992f50226fcfdb5d.npy].
Then you get the CNTK original model keras_to_cntk_inception_v3.dnn converted from Keras. 2c33f7f278cb46be992f50226fcfdb5d.py and 2c33f7f278cb46be992f50226fcfdb5d.npy are temporal files which will be removed automatically.
Step-by-step Command (for debugging)
Convert the pre-trained model files to intermediate representation
$ mmtoir -f keras -w imagenet_inception_v3.h5 -o converted
Using TensorFlow backend.
.
.
.
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.
Convert the IR files to CNTK models
$ mmtocode -f cntk -d converted_cntk.py -n converted.pb -w converted.npy
Parse file [converted.pb] with binary format successfully.
Target network code snippet is saved as [converted_cntk.py].
And you will get a filename converted_cntk.py, which contains the original CNTK codes to build the Inception V3 network.
With the three steps, you have already converted the pre-trained Keras Inception_v3 models to CNTK network file converted_cntk.py and weight file converted.npy. You can use these two files to fine-tune training or inference.
Dump the original CNTK model
$ mmtomodel -f cntk -in converted_cntk -iw converted.npy -o cntk_inception_v3.dnn
.
.
.
CNTK model file is saved as [cntk_inception_v3.dnn], generated by [converted_cntk.py] and [converted.npy].
The file cntk_inception_v3.dnn can be loaded by CNTK directly.