tensorflow 保存模型和取出中间权重例子

作者:binqiang2wang 时间:2021-05-11 07:30:11 

下面代码的功能是先训练一个简单的模型,然后保存模型,同时保存到一个pb文件当中,后续可以从pd文件里读取权重值。


import tensorflow as tf
import numpy as np
import os
import h5py
import pickle
from tensorflow.python.framework import graph_util
from tensorflow.python.platform import gfile
#设置使用指定GPU
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
#下面这段代码是在训练好之后将所有的权重名字和权重值罗列出来,训练的时候需要注释掉
reader = tf.train.NewCheckpointReader('./model.ckpt-100')
variables = reader.get_variable_to_shape_map()
for ele in variables:
 print(ele)
 print(reader.get_tensor(ele))

x = tf.placeholder(tf.float32, shape=[None, 1])
y = 4 * x + 4

w = tf.Variable(tf.random_normal([1], -1, 1))
b = tf.Variable(tf.zeros([1]))
y_predict = w * x + b

loss = tf.reduce_mean(tf.square(y - y_predict))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

isTrain = False#设成True去训练模型
train_steps = 100
checkpoint_steps = 50
checkpoint_dir = ''

saver = tf.train.Saver() # defaults to saving all variables - in this case w and b
x_data = np.reshape(np.random.rand(10).astype(np.float32), (10, 1))

with tf.Session() as sess:
 sess.run(tf.global_variables_initializer())
 if isTrain:
   for i in xrange(train_steps):
     sess.run(train, feed_dict={x: x_data})
     if (i + 1) % checkpoint_steps == 0:
       saver.save(sess, checkpoint_dir + 'model.ckpt', global_step=i+1)
 else:
   ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
   if ckpt and ckpt.model_checkpoint_path:
     saver.restore(sess, ckpt.model_checkpoint_path)
   else:
     pass  
   print(sess.run(w))
   print(sess.run(b))
   graph_def = tf.get_default_graph().as_graph_def()
   #通过修改下面的函数,个人觉得理论上能够实现修改权重,但是很复杂,如果哪位有好办法,欢迎指教
   output_graph_def = graph_util.convert_variables_to_constants(sess, graph_def, ['Variable'])
   with tf.gfile.FastGFile('./test.pb', 'wb') as f:
     f.write(output_graph_def.SerializeToString())

with tf.Session() as sess:
#对应最后一部分的写,这里能够将对应的变量取出来
 with gfile.FastGFile('./test.pb', 'rb') as f:
   graph_def = tf.GraphDef()
   graph_def.ParseFromString(f.read())
 res = tf.import_graph_def(graph_def, return_elements=['Variable:0'])
 print(sess.run(res))
 print(sess.run(graph_def))

来源:https://blog.csdn.net/m0_37052320/article/details/79845537

标签:tensorflow,保存模型,权重
0
投稿

猜你喜欢

  • ASP中ServerVariables集合用法详解

    2007-09-14 10:26:00
  • PHP中重启php-fpm的几种方法汇总

    2023-06-12 21:05:24
  • Django 后台获取文件列表 InMemoryUploadedFile的例子

    2021-09-25 11:19:38
  • django框架之cookie/session的使用示例(小结)

    2023-06-24 08:24:42
  • 详解Python的文件处理

    2022-07-16 23:46:15
  • Python面向对象程序设计类变量与成员变量、类方法与成员方法用法分析

    2022-08-11 15:43:43
  • 快速掌握怎样选择准备安装的 MySQL版本

    2008-12-17 16:42:00
  • Python使用shutil模块实现文件拷贝

    2021-02-01 14:46:28
  • python定时截屏实现

    2021-01-28 22:04:09
  • 分析Python中设计模式之Decorator装饰器模式的要点

    2021-12-06 12:04:01
  • 模拟实现 Range 的 insertNode() 方法

    2010-11-30 21:39:00
  • Python数据结构与算法中的栈详解

    2023-09-28 17:16:14
  • 一篇文章教你用Python实现一键文件重命名

    2022-09-21 20:18:38
  • 基本的页面设计元素布局比例

    2007-12-15 09:43:00
  • sqlserver中如何查询出连续日期记录的代码

    2011-09-30 11:16:56
  • python中文文本切词Kmeans聚类

    2023-06-01 18:35:57
  • 解决Python httpx 运行过程中无限阻塞的问题

    2023-03-26 12:17:05
  • 小看了setTimeout()

    2009-12-04 12:44:00
  • python中子类与父类的关系基础知识点

    2022-11-26 23:45:12
  • Python selenium把歌词评论做成词云图

    2022-12-29 10:17:35
  • asp之家 网络编程 m.aspxhome.com