I work with python 3.6 and tensorflow 1.14.
I get a dynamically created tensorflow model and need to store it together with some other information. Therefore I want to serialize the whole trained model into a string. The string gets then later stored together with the other information as file (e.g. json or pickle).
In other words, I want to write the serialize and deserialize function in that example code:
import tensorflow as tf
from tensorflow import keras
def get_trained_model() -> tf.keras.Sequential:
"""
Dummy code to build a model.
"""
model = keras.Sequential([
keras.layers.Dense(8, activation=tf.nn.relu),
keras.layers.Dense(8, activation=tf.nn.relu),
keras.layers.Dense(2, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
def serialize(model:tf.keras.Sequential) -> str:
"""
Serializes the whole tensorflow model (architecture and weights) as string, so that it can be
saved, shared and later deserialized.
"""
pass
def deserialize(model_string: str) -> tf.keras.Sequential:
"""
Deserializes a string into a working tensorflow model object.
"""
pass
model = get_trained_model()
m = serialize(model)
new_model = deserialize(m)
My current solution is to use model.save(), to write the model into a file, read the string from there and to delete the file again. Since this solution is not very clean I search for a better one.
Thanks a lot for any help or suggestions.