Reputation: 159
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)
Upvotes: 0
Views: 339
Reputation: 104
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
Upvotes: 1