'How to save and load model with tf.gradienttape in tenworflow2
I am using tf.gradienttape for model training and it is successful to save checkpoints for every epoch.
with train_summary_writer.as_default():
with tf.summary.record_if(True):
for epoch in range(epochs):
for train_id in range(train_start_id, train_end_id):
batch_data_path= train_data_path + 'train_data_' + str(train_id).zfill(6) + ".npy"
batch_data = np.load(data_path)
batch_data = np.transpose(batch_data, (0, 2, 3, 1))
x_inp = np.reshape(np.asarray(batch_data), [-1, 5, 5, 5, 3])
train(loss, model, opt, x_inp)
loss_values = loss(model, x_inp)
reconstructed = np.reshape(model(x_inp), [1, sensor_n, sensor_n, scale_n])
# if int(train_id) % 2000:
tf.summary.scalar('loss',loss_values, step = train_id)
tf.summary.image('original', tf.reshape(x_inp, (step_max, sensor_n, sensor_n, scale_n)), max_outputs=10, step=train_id)
tf.summary.image('reconstructed', reconstructed, max_outputs=10, step=train_id)
print("Epoch: {} ///// Step: {}/{} ===========================> Loss: {} ".format(epoch, train_id, train_end_id, loss_values))
save_path = manager.save()
print("Saved checkpoint for epoch {}: {}".format(epoch, save_path))
print("loss : {}".format(loss_values.numpy()))
Two following questions, 1. How can I save this model? 2. How can I load this model later on?
My model is kind of auto-encoder typed model, so it is necessary to create reconstructed model to compare and see errors.
Solution 1:[1]
Save and load the model using load_model API.
model.save(model_path)
and
loaded = tf.keras.models.load_model(model_path)
Solution 2:[2]
This guide may help: https://www.tensorflow.org/guide/saved_model
tf.saved_model.save(model, "Path")
Solution 3:[3]
if (epoch + 1) % 10 == 0: # Change the frequency for model saving, if needed
if g_val_loss_f < BEST_VAL_G_LOSS: # BEST_VAL_G_LOSS=50, assign some high value initially
BEST_VAL_G_LOSS = g_val_loss_f
model.save("model" + str(epoch + 1) + ".h5")
else: None
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Suraj Rao |
Solution 2 | Suraj Rao |
Solution 3 | R S |