4

I'm using CNTK as the backend for Keras. I'm trying to use my model which I have trained using Keras in C++.

I have trained and saved my model using Keras which is in HDF5. How do I now use CNTK API to save it in their model-v2 format?

I tried this:

model = load_model('model2.h5')
cntk.ops.functions.Function.save(model, 'CNTK_model2.pb')

but i got the following error:

TypeError: save() missing 1 required positional argument: 'filename'

If tensorflow were the backend I would have done this:

model = load_model('model2.h5')
sess = K.get_session()
tf_saver = tf.train.Saver()
tf_saver.save(sess=sess, save_path=checkpoint_path)

How can I achieve the same thing?

Lenni
  • 41
  • 2

3 Answers3

3

As per the comments here, I was able to use this:

import cntk as C
import keras.backend as K

keras_model = K.load_model('my_keras_model.h5')

C.combine(keras_model.model.outputs).save('my_cntk_model')
cntk_model = C.load_model('my_cntk_model')
Jacob Manning
  • 31
  • 1
  • 4
0

You can do something like this model.outputs[0].save('CNTK_model2.pb') I'm assuming here you have called model.compile (i.e. that's the only case I have tried :-)

  • I tired that @nikosk:- `model=load_model('model2.h5') model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.outputs[0].save('CNTK_model2.pb')` but when loading the model:- `C.load_model('CNTK_model2.pb')` I got the following error:- `if is_file: return cntk_py.Function.load(model, device) raise ValueError('Cannot load a model that is neither a file nor a byte buffer.') RuntimeError: SWIG director method error.` – Lenni Jun 12 '17 at 02:18
0

The reason you see this error is because keras' cntk backend use a user defined function to do reshape on batch axis, which can't been serialized. We have fixed this issue in CNTK v2.2. Please upgrade your cntk to v2.2, and upgrade keras to last master. Please see this pull request: https://github.com/fchollet/keras/pull/7907

Cheng Tang
  • 26
  • 1