tensorflow 模型的保存与加载
代码
"""
Created on 2020/11/20 9:41
@Author: CY
@email: [email protected]
"""
import os
import tensorflow as tf
from tensorflow import keras
print(tf.version.VERSION)
print("# 1 数据集")
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
train_labels = train_labels[:1000]
test_labels = test_labels[:1000]
train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0
test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0
print("# 2 模型")
def create_model():
model = tf.keras.models.Sequential([
keras.layers.Dense(512, activation='relu', input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(10)
])
model.compile(optimizer='adam',
loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
return model
model = create_model()
model.summary()
print("#3. 在训练期间保存模型(以 checkpoints 形式保存)")
checkpoint_path = "tmp/training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
save_weights_only=True,
verbose=1)
model.fit(train_images,
train_labels,
epochs=10,
validation_data=(test_images, test_labels),
callbacks=[cp_callback])
print("#4 建立一个未训练的模型")
model = create_model()
loss, acc = model.evaluate(test_images, test_labels, verbose=2)
print("Untrained model, accuracy: {:5.2f}%".format(100 * acc))
print("#4. 加载权重...")
model.load_weights(checkpoint_path)
loss, acc = model.evaluate(test_images, test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100 * acc))
checkpoint_path = "tmp/training_2/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(
filepath=checkpoint_path,
verbose=1,
save_weights_only=True,
period=5)
model = create_model()
model.save_weights(checkpoint_path.format(epoch=0))
model.fit(train_images,
train_labels,
epochs=50,
callbacks=[cp_callback],
validation_data=(test_images, test_labels),
verbose=0)
latest = tf.train.latest_checkpoint(checkpoint_dir)
model = create_model()
model.load_weights(latest)
loss, acc = model.evaluate(test_images, test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100 * acc))
print("# 5.手动保存权重")
model.save_weights('./tmp/checkpoints/my_checkpoint')
model = create_model()
model.load_weights('./tmp/checkpoints/my_checkpoint')
loss, acc = model.evaluate(test_images, test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100 * acc))
print("#6 保存整个模型")
model = create_model()
model.fit(train_images, train_labels, epochs=5)
model.save('tmp/saved_model/my_model')
print("#7. 从保存的模型重新加载新的 Keras 模型")
new_model = tf.keras.models.load_model('tmp/saved_model/my_model')
new_model.summary()
loss, acc = new_model.evaluate(test_images, test_labels, verbose=2)
print('Restored model, accuracy: {:5.2f}%'.format(100*acc))
print(new_model.predict(test_images).shape)
print("#8 使用HDF5 格式 保存 模型 恢复模型")
model = create_model()
model.fit(train_images, train_labels, epochs=5)
model.save('tmp/my_model.h5')
new_model = tf.keras.models.load_model('tmp/my_model.h5')
new_model.summary()