XifengGuo / CapsNet-Keras

A Keras implementation of CapsNet in NIPS2017 paper "Dynamic Routing Between Capsules". Now test error = 0.34%.
MIT License
2.47k stars 651 forks source link

How to save the trained model (including weights)? #95

Closed Garfield2013 closed 4 years ago

Garfield2013 commented 5 years ago

How to save the trained model (including weights)?

I can pickle and save the model on disk - but afterwards when I try to un-pickle the saved file it fails. It complains about a custom layer in the capsnet-model.

Any help would be highly appreciated!

GaganaB commented 4 years ago

Hi @Garfield2013

This worked for me. Along with the saved training weights (for which code is already available here), also save the json architecture. `

 model_json = model.to_json()
 with open("my_model.json", "w") as json_file:
            json_file.write(model_json)

Reading the model from JSON file

json_file = open('my_model.json', 'r')

loaded_model_json = json_file.read()

json_file.close()

from keras.models import model_from_json

model = model_from_json(loaded_model_json, custom_objects={'CapsuleLayer': CapsuleLayer, 'Mask':Mask, 'Length':Length})

model.load_weights("trained_model.h5")

print("Loaded model from disk")

model.compile(optimizer=optimizers.Adam(lr=0.001),
              loss=[margin_loss, 'mse'],
              loss_weights=[1., 0.392],
              metrics={'capsnet': 'accuracy'})

model.summary()

`

Hope this helps.

Garfield2013 commented 4 years ago

I'm not using it any longer - but thank you so much for reaching out to me :)