【发布时间】:2022-01-22 23:22:56
【问题描述】:
我正在尝试为我的模型拟合过程编写一个回调,如果在一个 Epoch 结束后,模型得到改进,我会将权重和保存为原型缓冲区。
最好是./tmp/weights.hdf5 和./tmp/model.pb 之类的东西。我为此使用了两个回调(下面的 mnist 示例,我使用的是 TF 2.6.0):
import tensorflow as tf
import numpy as np
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
def create_model():
return tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model = create_model()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
steps_per_execution=10)
callback_weights = tf.keras.callbacks.ModelCheckpoint(
filepath="./tmp/weights.hdf5", save_weights_only=True, save_best_only=True)
callback_model = tf.keras.callbacks.ModelCheckpoint(
filepath="./tmp/", save_weights_only=False, save_best_only=True)
model.fit(x=x_train,
y=y_train,
epochs=2,
validation_data=(x_test, y_test),
callbacks=[callback_weights, callback_model])
而ls tmp 给出:
assets keras_metadata.pb saved_model.pb variables weights.hdf5
我的问题:
- 我必须为此使用两个回调还是可以在一个回调中完成?
- 如何控制 protobuffer 文件的名称?在
save_weights_only=True有效时指定文件名,但当我使用save_weights_only=False执行此操作时,它会从filepath参数创建一个目录。
【问题讨论】:
标签: python tensorflow machine-learning keras tensorflow2.0