TensorFlow模型保存和加载方法

模型保存

  1. import tensorflow as tf
  2. w1 = tf.Variable(tf.constant(2.0, shape=[1]), name="w1-name")
  3. w2 = tf.Variable(tf.constant(3.0, shape=[1]), name="w2-name")
  4. a = tf.placeholder(dtype=tf.float32, name="a-name")
  5. b = tf.placeholder(dtype=tf.float32, name="b-name")
  6. y = a * w1 + b * w2
  7. init = tf.global_variables_initializer()
  8. saver = tf.train.Saver()
  9. with tf.Session() as sess:
  10. sess.run(init)
  11. print(a) # Tensor("a-name:0", dtype=float32)
  12. print(b) # Tensor("b-name:0", dtype=float32)
  13. print(y) # Tensor("add:0", dtype=float32)
  14. print(sess.run(y, feed_dict={a: 10, b: 10}))
  15. 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文件保存了一个目录下所有的模型文件列表

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

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

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

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

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

  1. import tensorflow as tf
  2. saver = tf.train.import_meta_graph("./model/model.ckpt.meta")
  3. graph = tf.get_default_graph()
  4. # 通过 Tensor 名获取变量
  5. a = graph.get_tensor_by_name("a-name:0")
  6. b = graph.get_tensor_by_name("b-name:0")
  7. y = graph.get_tensor_by_name("add:0")
  8. with tf.Session() as sess:
  9. saver.restore(sess, "./model/model.ckpt")
  10. 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

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

如 保存 代码如下

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

载入代码如下:

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

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

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

tf.train.import_meta_graph

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

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

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

保存

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

载入

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

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

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

restore.py

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

TensorFlow模型保存和加载方法的更多相关文章

  1. tensorflow 模型保存和加载

    使用 tf.train.Saver 保存:tf.train.Saver.save(sess, save_path, global_step=None, latest_filename=None, me ...

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

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

  3. 从头学pytorch(十二):模型保存和加载

    模型读取和存储 总结下来,就是几个函数 torch.load()/torch.save() 通过python的pickle完成序列化与反序列化.完成内存<-->磁盘转换. Module.s ...

  4. 使用Pytorch在多GPU下保存和加载训练模型参数遇到的问题

    最近使用Pytorch在学习一个深度学习项目,在模型保存和加载过程中遇到了问题,最终通过在网卡查找资料得已解决,故以此记之,以备忘却. 首先,是在使用多GPU进行模型训练的过程中,在保存模型参数时,应 ...

  5. tensorflow 模型保存与加载 和TensorFlow serving + grpc + docker项目部署

    TensorFlow 模型保存与加载 TensorFlow中总共有两种保存和加载模型的方法.第一种是利用 tf.train.Saver() 来保存,第二种就是利用 SavedModel 来保存模型,接 ...

  6. Tensorflow模型保存与加载

    在使用Tensorflow时,我们经常要将以训练好的模型保存到本地或者使用别人已训练好的模型,因此,作此笔记记录下来. TensorFlow通过tf.train.Saver类实现神经网络模型的保存和提 ...

  7. TensorFlow模型保存和提取方法

    一.TensorFlow模型保存和提取方法 1. TensorFlow通过tf.train.Saver类实现神经网络模型的保存和提取.tf.train.Saver对象saver的save方法将Tens ...

  8. TensorFlow 模型保存/载入

    我们在上线使用一个算法模型的时候,首先必须将已经训练好的模型保存下来.tensorflow保存模型的方式与sklearn不太一样,sklearn很直接,一个sklearn.externals.jobl ...

  9. 10 Tensorflow模型保存与读取

    我们的模型训练出来想给别人用,或者是我今天训练不完,明天想接着训练,怎么办?这就需要模型的保存与读取.看代码: import tensorflow as tf import numpy as np i ...

随机推荐

  1. Uncaught DOMException: Blocked a frame with origin "http://localhost

    ajaxFileUpload上传时报错 :Uncaught DOMException: Blocked a frame with origin "http://localhost..... ...

  2. Linux.超级管理员root-密码破解

    Linux.超级管理员root-密码破解 环境: 我是在虚拟机中安装的Linux,然后进行破解的.实体机,应该也是可以的,但我没有尝试过.如果你有实体机,试试吧... 又不要钱~ 在系统启动的时候,会 ...

  3. 解决乱码的方法是,在执行SQL语句之前,将MySQL以下三个系统参数设置为与服务器字符集character-set-server相同的字符集

    character-set-server/default-character-set:服务器字符集,默认情况下所采用的. character-set-database:数据库字符集. characte ...

  4. 导入转储文件的时候:Error Code: 1406. Data too long for column - MySQL

    MySQL will truncate any insert value that exceeds the specified column width. to make this without e ...

  5. idea上更新文件到github上

    1.不是最新文件,那么文件颜色就不一样.操作如下: 2.本地提交   .提交文件列表,提交说明,文件前后对比,确定了后就提交 3.推送到github. (1) (2)

  6. 通过改hosts访问wikipedia

    能访问https://www.wikipedia.org 大部分时候我们是可以访问的wikipedia的主页或是英文首页的,但中文页面却经常被墙,这时候你可以通过在命令行下ping www.wikip ...

  7. Vue系列之 => 结合ajax完成列表增删查

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. Nginx技术研究系列3-OpenResty安装配置

    上两篇中介绍了: Ngnix技术研究系列1-通过应用场景看Nginx的反向代理 Ngnix技术研究系列2-基于Redis实现动态路由 发现,应该加一篇OpenResty的安装部署说明,方便大家按图索骥 ...

  9. https://scrapingclub.com/exercise/detail_cookie/

    def parse(self, response): pattern=re.compile('token=(.*?);') token=pattern.findall( response.header ...

  10. 20155228 获取技能的成功经验和关于C语言学习的调查

    内容提要 你有什么技能比大多人(超过90%以上)更好?针对这个技能的获取你有什么成功的经验?与老师博客中的学习经验有什么共通之处? 有关C语言学习的调查 你是怎么学习C语言的?(作业,实验,教材,其他 ...