TensorFlow模型保存和加载方法

模型保存

import tensorflow as tfw1 = tf.Variable(tf.constant(2.0, shape=[1]), name="w1-name") w2 = tf.Variable(tf.constant(3.0, shape=[1]), name="w2-name") a = tf.placeholder(dtype=tf.float32, name="a-name") b = tf.placeholder(dtype=tf.float32, name="b-name") y = a * w1 + b * w2 init = tf.global_variables_initializer() saver = tf.train.Saver() with tf.Session() as sess: sess.run(init) print(a) # Tensor("a-name:0", dtype=float32) print(b) # Tensor("b-name:0", dtype=float32) print(y) # Tensor("add:0", dtype=float32) print(sess.run(y, feed_dict={a: 10, b: 10})) saver.save(sess, "./model/model.ckpt")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

这段代码中,通过saver.save函数将TensorFlow模型保存到了model/model.ckpt文件中,这里代码中指定路径为"model/model.ckpt",也就是保存到了当前程序所在文件夹里面的model文件夹中。

TensorFlow模型会保存在后缀为.ckpt的文件中。保存后在save这个文件夹中实际会出现3个文件,因为TensorFlow会将计算图的结构和图上参数取值分开保存。

  • model.ckpt.meta文件保存了TensorFlow计算图的结构,可以理解为神经网络的网络结构
  • model.ckpt文件保存了TensorFlow程序中每一个变量的取值
  • checkpoint文件保存了一个目录下所有的模型文件列表

模型加载:只加载变量,但是还是需要重新定义图结构

import tensorflow as tf# 使用和保存模型代码中一样的方式来声明变量
# 变量rw1, rw2 不需要进行初始化
rw1 = tf.Variable(tf.constant(2.0, shape=[1]), name="w1-name") rw2 = tf.Variable(tf.constant(3.0, shape=[1]), name="w2-name") # 重新定义图结构 result = 10 * rw1 + 10 * rw2 saver = tf.train.Saver() with tf.Session() as sess: saver.restore(sess, "./model/model.ckpt") print(sess.run(result))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

tf.train.Saver类也支持在保存和加载时给变量重命名

import tensorflow as tf# 声明的变量名称name与已保存的模型中的变量名称name不一致
rw1 = tf.Variable(tf.constant(2.0, shape=[1]), name="rw1-name") rw2 = tf.Variable(tf.constant(3.0, shape=[1]), name="rw2-name") # 重新定义图结构 result = 10 * rw1 + 10 * rw2 # 若直接生命Saver类对象,会报错变量找不到 # 使用一个字典dict重命名变量即可,{"已保存的变量的名称name": 重命名变量名} # 原来名称name为 w1-name 的变量现在加载到变量 rw1(名称name为 rw1-name)中 saver = tf.train.Saver({"w1-name": rw1, "w2-name": rw2}) with tf.Session() as sess: saver.restore(sess, "./model/model.ckpt") print(sess.run(result))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

模型加载: 不需要重新定义图结构

import tensorflow as tfsaver = tf.train.import_meta_graph("./model/model.ckpt.meta")
graph = tf.get_default_graph()# 通过 Tensor 名获取变量
a = graph.get_tensor_by_name("a-name:0") b = graph.get_tensor_by_name("b-name:0") y = graph.get_tensor_by_name("add:0") with tf.Session() as sess: saver.restore(sess, "./model/model.ckpt") print(sess.run(y, feed_dict={a: 10, b: 10}))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

convert_variables_to_constants

# 通过convert_variables_to_constants函数将计算图中的变量及其取值通过常量的方式保存于一个文件中import tensorflow as tf
from tensorflow.python.framework import graph_util v1 = tf.Variable(tf.constant(1.0, shape=[1]), name="v1") v2 = tf.Variable(tf.constant(2.0, shape=[1]), name="v2") result = v1 + v2 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # 导出当前计算图的GraphDef部分,即从输入层到输出层的计算过程部分 graph_def = tf.get_default_graph().as_graph_def() output_graph_def = graph_util.convert_variables_to_constants(sess, graph_def, ['add']) with tf.gfile.GFile("Model/combined_model.pb", 'wb') as f: f.write(output_graph_def.SerializeToString()) # 载入包含变量及其取值的模型 import tensorflow as tf from tensorflow.python.platform import gfile with tf.Session() as sess: model_filename = "Model/combined_model.pb" with gfile.FastGFile(model_filename, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) result = tf.import_graph_def(graph_def, return_elements=["add:0"]) print(sess.run(result)) # [array([ 3.], dtype=float32)]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

TensorFlow 模型保存/载入的两种方法

我们在上线使用一个算法模型的时候,首先必须将已经训练好的模型保存下来。tensorflow保存模型的方式与sklearn不太一样,sklearn很直接,一个sklearn.externals.joblib的dump与load方法就可以保存与载入使用。而tensorflow由于有graph,operation 这些概念,保存与载入模型稍显麻烦。

一、基本方法

网上搜索tensorflow模型保存,搜到的大多是基本的方法。即

保存

  1. 定义变量
  2. 使用saver.save()方法保存

载入

  1. 定义变量
  2. 使用saver.restore()方法载入

如 保存 代码如下

import tensorflow as tf
import numpy as np  W = tf.Variable([[1,1,1],[2,2,2]],dtype = tf.float32,name='w') b = tf.Variable([[0,1,2]],dtype = tf.float32,name='b') init = tf.initialize_all_variables() saver = tf.train.Saver() with tf.Session() as sess: sess.run(init) save_path = saver.save(sess,"save/model.ckpt") 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

载入代码如下:

import tensorflow as tf
import numpy as np  W = tf.Variable(tf.truncated_normal(shape=(2,3)),dtype = tf.float32,name='w') b = tf.Variable(tf.truncated_normal(shape=(1,3)),dtype = tf.float32,name='b') saver = tf.train.Saver() with tf.Session() as sess: saver.restore(sess,"save/model.ckpt") 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

这种方法不方便的在于,在使用模型的时候,必须把模型的结构重新定义一遍,然后载入对应名字的变量的值。但是很多时候我们都更希望能够读取一个文件然后就直接使用模型,而不是还要把模型重新定义一遍。所以就需要使用另一种方法。

二、不需重新定义网络结构的方法

tf.train.import_meta_graph

import_meta_graph(meta_graph_or_file,clear_devices=False,import_scope=None,**kwargs
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这个方法可以从文件中将保存的graph的所有节点加载到当前的default graph中,并返回一个saver。也就是说,我们在保存的时候,除了将变量的值保存下来,其实还有将对应graph中的各种节点保存下来,所以模型的结构也同样被保存下来了。

比如我们想要保存计算最后预测结果的y,则应该在训练阶段将它添加到collection中。具体代码如下 :

保存

### 定义模型
input_x = tf.placeholder(tf.float32, shape=(None, in_dim), name='input_x')
input_y = tf.placeholder(tf.float32, shape=(None, out_dim), name='input_y') w1 = tf.Variable(tf.truncated_normal([in_dim, h1_dim], stddev=0.1), name='w1') b1 = tf.Variable(tf.zeros([h1_dim]), name='b1') w2 = tf.Variable(tf.zeros([h1_dim, out_dim]), name='w2') b2 = tf.Variable(tf.zeros([out_dim]), name='b2') keep_prob = tf.placeholder(tf.float32, name='keep_prob') hidden1 = tf.nn.relu(tf.matmul(self.input_x, w1) + b1) hidden1_drop = tf.nn.dropout(hidden1, self.keep_prob) ### 定义预测目标 y = tf.nn.softmax(tf.matmul(hidden1_drop, w2) + b2) # 创建saver saver = tf.train.Saver(...variables...) # 假如需要保存y,以便在预测时使用 tf.add_to_collection('pred_network', y) sess = tf.Session() for step in xrange(1000000): sess.run(train_op) if step % 1000 == 0: # 保存checkpoint, 同时也默认导出一个meta_graph # graph名为'my-model-{global_step}.meta'. saver.save(sess, 'my-model', global_step=step)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

载入

with tf.Session() as sess:new_saver = tf.train.import_meta_graph('my-save-dir/my-model-10000.meta')new_saver.restore(sess, 'my-save-dir/my-model-10000')# tf.get_collection() 返回一个list. 但是这里只要第一个参数即可 y = tf.get_collection('pred_network')[0] graph = tf.get_default_graph() # 因为y中有placeholder,所以sess.run(y)的时候还需要用实际待预测的样本以及相应的参数来填充这些placeholder,而这些需要通过graph的get_operation_by_name方法来获取。 input_x = graph.get_operation_by_name('input_x').outputs[0] keep_prob = graph.get_operation_by_name('keep_prob').outputs[0] # 使用y进行预测 sess.run(y, feed_dict={input_x:...., keep_prob:1.0})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

具体示例

save.py

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data# 加载数据集 mnist = input_data.read_data_sets("data", one_hot=True) # Parameters learning_rate = 0.001 batch_size = 100 display_step = 10 model_path = "save/model.ckpt" # Network Parameters n_hidden_1 = 256 # 1st layer number of features n_hidden_2 = 256 # 2st layer number of features n_input = 784 # MNIST data input (img shape: 28*28) n_classes = 10 # MNIST total classes (0-9 digits) # tf Graph input x = tf.placeholder(tf.float32, [None, n_input], name="input_x") y = tf.placeholder(tf.float32, [None, n_classes], name="input_y") # Store layers weight & bias weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_classes])) } # Create model def multilayer_perceptron(x, weights, biases): # layer1 h1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) h1 = tf.nn.relu(h1) # layer2 h2 = tf.add(tf.matmul(h1, weights['h2']), biases['b2']) h2 = tf.nn.relu(h2) # out out = tf.add(tf.matmul(h2, weights['out']), biases['out']) return out # Construct model logits = multilayer_perceptron(x, weights, biases) pred = tf.nn.softmax(logits) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) corrcet_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(corrcet_pred, tf.float32)) # Initializing the variables init = tf.global_variables_initializer() # 保存模型 saver = tf.train.Saver() tf.add_to_collection("pred", pred) tf.add_to_collection('acc', accuracy) with tf.Session() as sess: sess.run(init) step = 0 while step * batch_size < 180000: batch_xs, batch_ys = mnist.train.next_batch(batch_size) loss, _, acc = sess.run([cost, optimizer, accuracy], feed_dict={x: batch_xs, y: batch_ys}) if step % display_step == 0: # step: 1790 loss: 16.9724 acc: 0.95 print("step: ", step, "loss: ", loss, "acc: ", acc) saver.save(sess, save_path=model_path, global_step=step) step += 1 print("Train Finish!")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

checkpoint:

model_checkpoint_path: "model.ckpt-1790"
all_model_checkpoint_paths: "model.ckpt-1750"
all_model_checkpoint_paths: "model.ckpt-1760" all_model_checkpoint_paths: "model.ckpt-1770" all_model_checkpoint_paths: "model.ckpt-1780" all_model_checkpoint_paths: "model.ckpt-1790"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

restore.py

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data# load mnist data mnist = input_data.read_data_sets("data", one_hot=True) with tf.Session() as sess: new_saver = tf.train.import_meta_graph("save/model.ckpt-1790.meta") new_saver.restore(sess, "save/model.ckpt-1790") # tf.get_collection() 返回一个list. 但是这里只要第一个参数即可 pred = tf.get_collection("pred")[0] acc = tf.get_collection("acc")[0] # 因为 pred, acc 中有 placeholder,所以 sess.run(acc)的时候还需要用实际待预测的样本以及相应的参数来填充这些placeholder, # 而这些需要通过graph的get_operation_by_name方法来获取。 graph = tf.get_default_graph() x = graph.get_operation_by_name("input_x").outputs[0] y = graph.get_operation_by_name("input_y").outputs[0] test_xs = mnist.test.images test_ys = mnist.test.labels #test set acc: [0.91820002] print("test set acc: ", sess.run([acc], feed_dict={ x: test_xs, y: test_ys }))原文:https://blog.csdn.net/u011026329/article/details/79190347

TensorFlow模型保存和加载方法相关推荐

  1. keras中的模型保存和加载

    tensorflow中的模型常常是protobuf格式,这种格式既可以是二进制也可以是文本.keras模型保存和加载与tensorflow不同,keras中的模型保存和加载往往是保存成hdf5格式. ...

  2. pytorch模型保存和加载

    定义2个测试脚本test.py和test2.py,用于测试保存和加载,models文件夹保存模型,整个测试的项目文件结构如下: E:. │ test.py │ test2.py └─ modelsdo ...

  3. keras模型保存和加载

    (一)保存和加载整个模型 ​ 包含模型的结构.权重.训练配置项(损失函数.优化器).优化器状态,允许准确地从上次结束的地方开始训练. 1.训练完模型后 path='.../.../xxx.h5' mo ...

  4. 【NLP】from glove import Glove的使用、模型保存和加载

    1 引言 不要被stackflow的上的一个的回答所误导. 2 使用方法举例 # 语料 sentense = [['你', '是', '谁'], ['我', '是', '中国人']] corpus_m ...

  5. paddlepaddle模型的保存和加载

    导读 深度学习中模型的计算图可以被分为两种,静态图和动态图,这两种模型的计算图各有优劣. 静态图需要我们先定义好网络的结构,然后再进行计算,所以静态图的计算速度快,但是debug比较的困难,因为只有当 ...

  6. tensorflow 保存训练loss_tensorflow2.0保存和加载模型 (tensorflow2.0官方教程翻译)

    最新版本:https://www.mashangxue123.com/tensorflow/tf2-tutorials-keras-save_and_restore_models.html 英文版本: ...

  7. 加载dict_PyTorch 7.保存和加载pytorch模型的两种方法

    众所周知,python的对象都可以通过torch.save和torch.load函数进行保存和加载(不知道?那你现在知道了(*^_^*)),比如: x1 = {"d":" ...

  8. python保存模型与参数_基于pytorch的保存和加载模型参数的方法

    当我们花费大量的精力训练完网络,下次预测数据时不想再(有时也不必再)训练一次时,这时候torch.save(),torch.load()就要登场了. 保存和加载模型参数有两种方式: 方式一: torc ...

  9. TensorFlow 保存和加载模型

    参考: 保存和恢复模型官方教程 tensorflow2保存和加载模型 TensorFlow2.0教程-keras模型保存和序列化

最新文章

  1. 漫画:垃圾男人分类图鉴
  2. 小分子溶液当硬盘!布朗大学逆天研究:用代谢分子存储照片,准确率达99%
  3. 【深度学习】基于Torch的Python开源机器学习库PyTorch卷积神经网络
  4. Python类访问限制
  5. 吴恩达深度学习课程deeplearning.ai课程作业:Class 1 Week 2 assignment2_1
  6. QT的Q3DScatter类的使用
  7. Mysql和Oracle 数据库操作工具类
  8. ibdata1 mysql_ibdata1 mysql-bin
  9. grafana导入json文件没有数据_基于SpringBoot将Json数据导入到数据库
  10. vfp access mysql具体_详细介绍Visual FoxPro数据表的索引
  11. Operations-ansible-01
  12. 读书笔记 摘自:《跟任何人都聊得来》
  13. 关于左对齐和左对齐的一些简单理解和杨辉3角的算法思想
  14. 程序员做外包有前途吗?谈谈外包的利与弊,字字扎心
  15. 这一次,彻底解决Java的值传递和引用传递
  16. 【论文解读】关于基于视觉无人机自主降落平台的论文梳理
  17. 数据可视化、信息可视化与知识可视化
  18. 名词解释:Web3 账户相关概念大梳理
  19. Cheng MeiChun团队的技术支持
  20. 【系统安全学习4】口令破解

热门文章

  1. 三点弯曲弹性模量怎么计算公式_?怎么计算弯管的尺寸和弯管的张力
  2. mysql数据库存储数据的过程_[数据库]MySql存储过程总结
  3. war 发布后页面不更新_一文看懂tomcat8如何配置web页面管理
  4. cnn_mnist_案例详解
  5. php 屏蔽ip段,php禁止ip段的方法
  6. ubuntu c mysql_Ubuntu下MySql和C连接的一些问题
  7. html5 水波式按钮_css3+jQuery实现按钮水波纹效果
  8. ipv6 端口号_计算机网络之IP、MAC、端口号、子网掩码、默认网关、DNS
  9. linux下软件如何防破裂,linux下管道破裂的處理
  10. 德云斗笑社何九华为什么没参加_江西省会为什么是南昌?