关键词

Keras-保存和恢复模型

1,share的内容

  • code to create the model, and
  • the trained weights, or parameters, for the model

2,ways

There are different ways to save TensorFlow models—depending on the API you're using

3,Checkpoint callback usage

3.1,以callback方式触发对checkpoint的在fit过程中的记录

checkpoint_path = "training_1/cp.ckpt"

checkpoint_dir = os.path.dirname(checkpoint_path)

# Create checkpoint callback

cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, 

                                                 save_weights_only=True,

                                                 verbose=1)

model = create_model()

model.fit(train_images, train_labels,  epochs = 10, 

          validation_data = (test_images,test_labels),

          callbacks = [cp_callback])  # pass callback to training

3.2,检查目录

! ls {checkpoint_dir}

3.3,找出最近的

latest=tf.train.latest_checkpoint(checkpoint_dir)

4,恢复至最近的checkpoint

model = create_model()

model.load_weights(latest)

loss, acc = model.evaluate(test_images, test_labels)

print("Restored model, accuracy: {:5.2f}%".format(100*acc))

tf.train.latest_checkpoint(checkpoint_dir)

5,手动save和restore

# Save the weights
model.save_weights('./checkpoints/my_checkpoint')

# Restore the weights
model = create_model()
model.load_weights('./checkpoints/my_checkpoint')

loss,acc = model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))

6,保存和恢复整个模型

6.1,save

contains the weight values, the model's configuration, and even the optimizer's configuration (depends on set up). This allows you to checkpoint a model and resume training later—from the exact same state—without access to the original code

model = create_model()

model.fit(train_images, train_labels, epochs=5)

# Save entire model to a HDF5 file
model.save('my_model.h5')

6.2,恢复

new_model = keras.models.load_model('my_model.h5')
new_model.summary()

7,keras如何保存和恢复模型

7.1,创建模型

model = create_model()

model.fit(train_images, train_labels, epochs=5)

7.2,保存模型

Keras saves models by inspecting the architecture. Currently, it is not able to save TensorFlow optimizers (from tf.train). When using those you will need to re-compile the model after loading, and you will lose the state of the optimizer.

saved_model_path = tf.contrib.saved_model.save_keras_model(model, "./saved_models")

!ls -l saved_models

7.3,恢复模型

new_model = tf.contrib.saved_model.load_keras_model(saved_model_path)
new_model.summary()

7.4,编译模型(因为不保存模型的优化器

# The model has to be compiled before evaluating.
# This step is not required if the saved model is only being deployed.

new_model.compile(optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])

# Evaluate the restored model.
loss, acc = new_model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))

 

本文链接:http://task.lmcjl.com/news/5884.html

展开阅读全文