我創建了一個帶有自定義層的模型,其中包含矩陣運算和類似的東西。我現在想在訓練后保存我的模型。我試過了:
model.save("model.h5", save_format='tf')
但是出現了一個錯誤:
NotImplementedError: Saving the model to HDF5 format requires the model to be
a Functional model or a Sequential model. It does not work for subclassed models,
because such models are defined via the body of a Python method, which isn't safely serializable.
Consider saving to the Tensorflow SavedModel format (by setting save_format="tf") or using `save_weights`.
我發現了一些有用的東西:
checkpoint_path = "checkpoints"
ckpt = tf.train.Checkpoint(model=model,
optimizer=optimizer)
ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)
# if a checkpoint exists, restore the latest checkpoint.
if ckpt_manager.latest_checkpoint:
ckpt.restore(ckpt_manager.latest_checkpoint)
我的問題是:通過使用這種方式,我可以做與保存可序列化模型(如順序模型)相同的事情,或者這個檢查點用于其他目的?
uj5u.com熱心網友回復:
實際上有兩種格式可以用來保存模型。您可以簡單地使用較舊的 Keras H5 格式保存模型,model.save("test", save_format='h5')也可以Tensorflow SavedModel format通過顯式設定model.save("test", save_format='tf')或簡單地使用model.save("test"),因為tf呼叫時默認使用該格式model.save。使用model.save("model.h5", save_format='tf'),您似乎試圖同時使用這兩種格式,這看起來不起作用。使用該tf格式保存模型應該可以。可以在此處找到更多資訊。例如,以下模型只能在使用model.save或時保存model.save("test", save_format='tf'):
import tensorflow as tf
class SomeModel(tf.keras.Model):
def __init__(self):
super(SomeModel, self).__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu, )
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = SomeModel()
model.compute_output_shape(input_shape=(1,1))
model.save("model")
呼叫model.save("test", save_format='h5')或者model.save("test.h5")甚至model.save("model.h5", save_format='tf')在這個子類模型上都會導致錯誤。
Checkpoints當您需要中斷訓練或它崩潰并且您想從保存的狀態恢復訓練模型時,這尤其有用。在推理程序中,您可以輕松加載模型的最新檢查點并進行預測,而無需重新編譯它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362366.html
上一篇:通用Lambda之間的區別
