我創建了一個帶有自定義層的模型,其中包含矩陣運算和類似的東西。我現在想在訓練後保存我的模型。我試過了:
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)
我的問題是:通過使用這種方式,我可以做與保存可序列化模型(如順序模型)相同的事情,或者這個檢查點用於其他目的?
實際上有兩種格式可以用來保存模型。您可以簡單地使用較舊的 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
當您需要中斷訓練或它崩潰並且您想從保存的狀態恢復訓練模型時,這尤其有用。在推理過程中,您可以輕鬆加載模型的最新檢查點並進行預測,而無需重新編譯它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句