Tensorflow(二十六) —— 模型加载与保存
1. 训练测试模型
import tensorflow as tf
from tensorflow.keras import Sequential,optimizers,layers,datasets
# 训练测试模型
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)
model = Sequential([
layers.Dense(256,activation = tf.nn.relu),
layers.Dense(128,activation = tf.nn.relu),
layers.Dense(64,activation = tf.nn.relu),
layers.Dense(32,activation = tf.nn.relu),
layers.Dense(10)
])
model.build(input_shape = [None,28*28])
(x,y),(x_test,y_test) = datasets.fashion_mnist.load_data()
def preprocess(x,y):
x = tf.cast(x,dtype=tf.float32)/255.
x = tf.reshape(x,[-1,28*28])
y = tf.cast(y,dtype=tf.int32)
y = tf.one_hot(y,depth=10)
return x,y
db = tf.data.Dataset.from_tensor_slices((x,y))
db_test = tf.data.Dataset.from_tensor_slices((x_test,y_test))
db = db.map(preprocess).shuffle(10000).batch(128)
db_test = db_test.map(preprocess).shuffle(10000).batch(128)
optimizer = optimizers.Adam(lr = 1e-3)
model.compile(optimizer = optimizer,loss = tf.losses.CategoricalCrossentropy(from_logits=True),metrics=["accuracy"])
model.fit(db,epochs = 2,validation_data=db_test,validation_freq=2)
model.evaluate(db_test)
2. save the weights
# ***************** save the weights
"""
modle.save_weights("./.../weights.ckpt")
model.load_weights("./.../weights.ckpt")
del model
"""
model.save_weights("./model/2020_07_14.ckpt")
model2 = Sequential([
layers.Dense(256,activation = tf.nn.relu),
layers.Dense(128,activation = tf.nn.relu),
layers.Dense(64,activation = tf.nn.relu),
layers.Dense(32,activation = tf.nn.relu),
layers.Dense(10)
])
model2.build(input_shape = [None,28*28])
model2.compile(optimizer = optimizer,loss = tf.losses.CategoricalCrossentropy(from_logits=True),metrics=["accuracy"])
model2.load_weights("./model/2020_07_14.ckpt")
model2.evaluate(db_test)
3. 保存整个模型状态
# ******************* 保存整个模型状态
model.save("./model/wj_07_14.h5")
model3 = tf.keras.models.load_model("./model/wj_07_14.h5")
model3.evaluate(db_test)
4. 工业环境布置
# *********** 工业环境布置
tf.saved_model.save(model,"./model/saved_model")
model4 = tf.saved_model.load("./model/saved_model")
model4 = model4.signatures["serving_default"]
model4(tf.ones([1,28,28]))
本文为参考龙龙老师的“深度学习与TensorFlow 2入门实战“课程书写的学习笔记
by CyrusMay 2022 04 18