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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值