Keras-保存和恢复模型
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 training3.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_models7.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))總結
以上是生活随笔為你收集整理的Keras-保存和恢复模型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 国科大prml14-独立于算法的机器学习
- 下一篇: 论文学习6-(M2DNE)Tempora