Tensorflow中的模型保存与加载

本文详细介绍了Tensorflow 1.x中模型的保存与加载,包括ckpt、pb和pkl格式。讨论了ckpt模型的优缺点,推荐使用pb格式,因其语言独立且适合移动端。还提及了在TF2.0中的相关操作,但未展开详细内容。
摘要由CSDN通过智能技术生成

Tensorflow中,模型的保存与加载有多种方法。这篇文章主要是把这些方法整理在一起,方便查看。

TF1.x

保存和加载ckpt格式的模型

一般在训练模型的过程中,需要保存模型和权重,常见的方式是保存为ckpt格式的文件,具体的函数如下:

tf.train.Saver().save(sess,ckpt_file_path,max_to_keep=4,keep_checkpoint_every_n_hours=2) 

再使用类似下面的code来恢复模型:

saver.restore(sess,tf.train.latest_checkpoint('./ckpt'))

使用tf.train.Saver保存和加载模型

(a)保存模型

# 保存模型
import tensorflow as tf

# Create some variables.
v1 = tf.Variable([1,2,3], name='v1', dtype=float)
v2 = tf.Variable([4,5,6,7,8], name='v2', dtype=float)

inc_v1 = v1.assign(v1+1)
dec_v2 = v2.assign(v2-1)

# Add an op to initialize the variables.
init_op = tf.global_variables_initializer()

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, initialize the variables, do some work, and save the
# variables to disk.
with tf.Session() as sess:
  sess.run(init_op)
  # Do some work with the model.
  inc_v1.op.run()
  dec_v2.op.run()
  # Save the variables to disk.
  save_path = saver.save(sess, "./models/model.ckpt") # 这里,./models是模型保存的目录
  print("Model saved in path: %s" % save_path)

保存的模型如下:
在这里插入图片描述
其中,checkpoint文件,记录了保存的最新的checkpoint文件以及其它checkpoint文件列表。
.data-xxxx文件是二进制文件,保存了所有的weights、biases、gradients等变量。
.index文件中保存了各种变量名称
.meta文件保存的是图结构,meta文件是pb(protocol buffer)格式文件,包含Variables、op、集合等

(2)加载模型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值