0

I have a model with a relatively complicated computational graph and am about to train it on a large set of data. How can I save the trained model afterwards, so that I can just load its (structure + weights) without specifying the complicated model structure again? I just want to a single file "trained_model" that I can load from any other tensorflow code without the need to know how the internal structure looks like. Put in other words, I want to use the trained model as a black box later on. Is there something like this in tensorflow? I am a little bit confused by the stuff I find on the internet myself, maybe one of you experts can help me out. Thanks so much in advance!

So what I would like to have is the following:

trained_model_path = '.../trained_model/

trained_model = load_model_from_file(trained_model_path) # black box!

trained_model.predict(x)
Jonas G.
  • 129
  • 1
  • 1
  • 7
  • Possible duplicate of [How to save final model using keras?](https://stackoverflow.com/questions/42763094/how-to-save-final-model-using-keras) – OverLordGoldDragon Oct 16 '19 at 13:35

1 Answers1

1

You can save models in h5 file. And load them later on. You shouldn't rebuilt the whole thing again because then you have to train it every time you want to use it.

# Save the model
model.save('../resources/saved_models/my_model.h5')

# Recreate the exact same model purely from the file
new_model = keras.models.load_model('path_to_my_model.h5')

Check out the documentation (link bellow) for more details. You need to have Keras API for this. I assume everyone who works with tensorflow these days uses keras. It is just a pip install and then should be imported at the top of your code. (Like a normal python library)

https://www.tensorflow.org/guide/keras/save_and_serialize

Ball Hog
  • 104
  • 4
  • Thanks! Can the keras.models.load_model handle any type of network that is expressable with tensorflow? – Jonas G. Oct 16 '19 at 13:33
  • Keras is a part of tensorflow which later on was added to simplify the process of building and modifying models. So I assume your answer is yes. @JonasG. – Ball Hog Oct 16 '19 at 14:09