【TF】TensorFlow的模型保存save和加载load

训练过程中保存checkpoints

checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

# Create a callback that saves the model's weights
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
                                                 save_weights_only=True,
                                                 verbose=1)

# Train the model with the new callback
model.fit(train_images, 
          train_labels,  
          epochs=10,
          validation_data=(test_images, test_labels),
          callbacks=[cp_callback])  # Pass callback to training

# This may generate warnings related to saving the state of the optimizer.
# These warnings (and similar warnings throughout this notebook)
# are in place to discourage outdated usage, and can be ignored.
# 保存模型weights
model.save_weights('./checkpoints/my_checkpoint')
# 加载模型weight
model.load_weights(checkpoint_path)
# 保存整个模型
model.save('saved_model/my_model')
# 加载整个模型
new_model = tf.keras.models.load_model('saved_model/my_model')
# 保存为h5格式
model.save('my_model.h5')
# 加载h5格式
new_model = tf.keras.models.load_model('my_model.h5')
# 展现模型结构 Display the model's architecture
model.summary()

你可能感兴趣的:(tensorflow,keras,深度学习)