tensorflow模型的保存与加载
模型的保存与加载一般有三种模式:save/load weights(最干净、最轻量级的方式,只保存网络参数,不保存网络状态),save/load entire model(最简单粗暴的方式,把网络所有的状态都保存起来),saved_model(更通用的方式,以固定模型格式保存,该格式是各种语言通用的)
具体使用方法如下:
# 保存模型
model.save_weights('./checkpoints/my_checkpoint')
# 加载模型
model = keras.create_model()
model.load_weights('./checkpoints/my_checkpoint')
示例:
import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics def preprocess(x, y):
x = tf.cast(x, dtype=tf.float32) / 255.
x = tf.reshape(x, [28 * 28])
y = tf.cast(y, dtype=tf.int32)
y = tf.one_hot(y, depth=10)
return x, y batchsz = 128
(x, y), (x_val, y_val) = datasets.mnist.load_data()
print('datasets:', x.shape, y.shape, x.min(), x.max()) db = tf.data.Dataset.from_tensor_slices((x, y))
db = db.map(preprocess).shuffle(60000).batch(batchsz)
ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
ds_val = ds_val.map(preprocess).batch(batchsz) sample = next(iter(db))
print(sample[0].shape, sample[1].shape) network = Sequential([layers.Dense(256, activation='relu'),
layers.Dense(128, activation='relu'),
layers.Dense(64, activation='relu'),
layers.Dense(32, activation='relu'),
layers.Dense(10)])
network.build(input_shape=(None, 28 * 28))
network.summary() network.compile(optimizer=optimizers.Adam(lr=0.01),
loss=tf.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy']
) network.fit(db, epochs=3, validation_data=ds_val, validation_freq=2) network.evaluate(ds_val) network.save_weights('weights.ckpt')
print('saved weights.')
del network network = Sequential([layers.Dense(256, activation='relu'),
layers.Dense(128, activation='relu'),
layers.Dense(64, activation='relu'),
layers.Dense(32, activation='relu'),
layers.Dense(10)])
network.compile(optimizer=optimizers.Adam(lr=0.01),
loss=tf.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy']
)
network.load_weights('weights.ckpt')
print('loaded weights!')
network.evaluate(ds_val)
运行效果如下:
可以看到保存前后的精度和损失差距不大,这是由于神经网络的运算过程中会有很多不确定因子,这些不确定因子不会通过save_weights方法保存,要想保存前后运行结果一致,就需要完整的保存网络模型。即model.save方法
使用方法如下:
# 模型保存
network.save('model.h5')
print('saved total model.')
# 模型加载
print('load model from file')
network = tf.keras.models.load_model('model.h5')
# 评估
network.evaluate(x_val,y_val)
除了这种方法之外,tensorflow还支持保存为标准的可以给其他语言使用的模型,使用saved_model即可
使用方法如下:
tf.saved_model.save(m,'/tmp/saved_model/')
imported = tf.saved_model.load(path)
f = imported.signatures["serving_default"]
print(f(x=tf.ones([1,28,28,3])))
tensorflow模型的保存与加载的更多相关文章
- tensorflow 之模型的保存与加载(二)
上一遍博文提到 有些场景下,可能只需要保存或加载部分变量,并不是所有隐藏层的参数都需要重新训练. 在实例化tf.train.Saver对象时,可以提供一个列表或字典来指定需要保存或加载的变量. #!/ ...
- tensorflow 之模型的保存与加载(三)
前面的两篇博文 第一篇:简单的模型保存和加载,会包含所有的信息:神经网络的op,node,args等; 第二篇:选择性的进行模型参数的保存与加载. 本篇介绍,只保存和加载神经网络的计算图,即前向传播的 ...
- tensorflow 之模型的保存与加载(一)
怎样让通过训练的神经网络模型得以复用? 本文先介绍简单的模型保存与加载的方法,后续文章再慢慢深入解读. #!/usr/bin/env python3 #-*- coding:utf-8 -*- ### ...
- Python之TensorFlow的模型训练保存与加载-3
一.TensorFlow的模型保存和加载,使我们在训练和使用时的一种常用方式.我们把训练好的模型通过二次加载训练,或者独立加载模型训练.这基本上都是比较常用的方式. 二.模型的保存与加载类型有2种 1 ...
- Tensorflow 模型持久化saver及加载图结构
主要内容: 1. 直接保存,加载模型; (可以指定加载,保存的var_list) 2. 加载,保存指定变量的模型 3. slim加载模型使用 4. 加载模型图结构和参数等 tensorflow 恢复部 ...
- (sklearn)机器学习模型的保存与加载
需求: 一直写的代码都是从加载数据,模型训练,模型预测,模型评估走出来的,但是实际业务线上咱们肯定不能每次都来训练模型,而是应该将训练好的模型保存下来 ,如果有新数据直接套用模型就行了吧?现在问题就是 ...
- pytorch_模型参数-保存,加载,打印
1.保存模型参数(gen-我自己的模型名字) torch.save(self.gen.state_dict(), os.path.join(self.gen_save_path, 'gen_%d.pt ...
- pytorch 中模型的保存与加载,增量训练
让模型接着上次保存好的模型训练,模型加载 #实例化模型.优化器.损失函数 model = MnistModel().to(config.device) optimizer = optim.Adam( ...
- fashion_mnist多分类训练,两种模型的保存与加载
from tensorflow.python.keras.preprocessing.image import load_img,img_to_array from tensorflow.python ...
随机推荐
- 《java多线程编程核心技术》不使用等待通知机制 实现线程间通信的 疑问分析
不使用等待通知机制 实现线程间通信的 疑问分析 2018年04月03日 17:15:08 ayf 阅读数:33 编辑 <java多线程编程核心技术>一书第三章开头,有如下案例: ...
- Shiro自动登录
Shiro RememberMe spring.xml <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager& ...
- Go语言实现:【剑指offer】矩阵覆盖
该题目来源于牛客网<剑指offer>专题. 我们可以用21的小矩形横着或者竖着去覆盖更大的矩形.请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法? 先放21,则f(n ...
- qt creator源码全方面分析(2-0)
目录 Extending Qt Creator Manual 生成领域特定的代码和模板 代码片段 文件和项目模板 自定义向导 支持其他文件类型 MIME类型 高亮和缩进 自定义文本编辑器 其他自定义编 ...
- LwIP的udp学习笔记
* Bind an UDP PCB. * * @param pcb UDP PCB to be bound with a local address ipaddr and port. * @param ...
- Keepalived 配置文件
keepalived的配置文件: keepalived只有一个配置文件keepalived.conf,里面主要包括以下几个配置区域,分别是global_defs. 全局定义及 ...
- [Redis-CentOS7]Python操作Redis(十一)
Python 操作redis #!/usr/bin/env pyhton # coding:utf-8 # @Time : 2020-02-16 21:36 # @Author : LeoShi # ...
- pip 安装源-Python学习
1.国内常用的安装源 -- 豆瓣:https://pypi.douban.com/simple -- 阿里:https://mirrors.aliyun.com/pypi/simple --中国科技大 ...
- codewars--js--Large Factorials--阶乘+大数阶乘
问题描述: In mathematics, the factorial of integer n is written as n!. It is equal to the product of n a ...
- C# 多线程之通过Timer开启线程的例子
本例通过Timer的tick()方法触发TimerCallback委托来开辟新的线程,线程中的具体工作通过一个静态方法作为参数给TimerCallback委托. using System; using ...