欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

TensorFlow实现保存训练模型为pd文件并恢复

时间:2021-02-17 14:01:41|栏目:Python代码|点击:

TensorFlow保存模型代码

import tensorflow as tf
from tensorflow.python.framework import graph_util
var1 = tf.Variable(1.0, dtype=tf.float32, name='v1')
var2 = tf.Variable(2.0, dtype=tf.float32, name='v2')
var3 = tf.Variable(2.0, dtype=tf.float32, name='v3')
x = tf.placeholder(dtype=tf.float32, shape=None, name='x')
x2 = tf.placeholder(dtype=tf.float32, shape=None, name='x2')
addop = tf.add(x, x2, name='add')
addop2 = tf.add(var1, var2, name='add2')
addop3 = tf.add(var3, var2, name='add3')
initop = tf.global_variables_initializer()
model_path = './Test/model.pb'
with tf.Session() as sess:
  sess.run(initop)
  print(sess.run(addop, feed_dict={x: 12, x2: 23}))
  output_graph_def = graph_util.convert_variables_to_constants(sess, sess.graph_def, ['add', 'add2', 'add3'])
  # 将计算图写入到模型文件中
  model_f = tf.gfile.FastGFile(model_path, mode="wb")
  model_f.write(output_graph_def.SerializeToString())

读取模型代码

import tensorflow as tf
with tf.Session() as sess:
  model_f = tf.gfile.FastGFile("./Test/model.pb", mode='rb')
  graph_def = tf.GraphDef()
  graph_def.ParseFromString(model_f.read())
  c = tf.import_graph_def(graph_def, return_elements=["add2:0"])
  c2 = tf.import_graph_def(graph_def, return_elements=["add3:0"])
  x, x2, c3 = tf.import_graph_def(graph_def, return_elements=["x:0", "x2:0", "add:0"])

  print(sess.run(c))
  print(sess.run(c2))
  print(sess.run(c3, feed_dict={x: 23, x2: 2}))

上一篇:详解如何为eclipse安装合适版本的python插件pydev

栏    目:Python代码

下一篇:详解在Python程序中解析并修改XML内容的方法

本文标题:TensorFlow实现保存训练模型为pd文件并恢复

本文地址:http://www.codeinn.net/misctech/64449.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有