tensorflow 保存和调用模型

本文详细介绍使用TensorFlow保存和加载模型的过程。首先定义模型结构,包括变量和占位符,然后通过会话运行模型并保存。加载模型时,利用saver对象导入元图和参数,最后验证模型加载正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tensorflow 保存和调用模型

https://www.jianshu.com/p/50243b58b9e1

import tensorflow as tf

x1 = tf.placeholder(dtype=tf.float32, shape=[], name = 'x1')

x2 = tf.placeholder(dtype=tf.float32, shape=[], name = 'x2')

w = tf.Variable(tf.constant(2.), name = 'w')

ytmp = tf.multiply(w, x1, name = 'ytmp')

y = tf.add(ytmp, x2, name = 'y')

sess = tf.Session()

sess.run(tf.global_variables_initializer())

print (sess.run(y, feed_dict={x1: 1., x2: 2.}))

saver = tf.train.Saver()

saver.save(sess, 'model/test')

 

import tensorflow as tf

sess = tf.Session()

# 导入运算图
saver = tf.train.import_meta_graph('model/test.meta')

#加载相应参数
saver.restore(sess, tf.train.latest_checkpoint('model/'))

graph = tf.get_default_graph()

x1 = graph.get_tensor_by_name('x1:0')

x2 = graph.get_tensor_by_name('x2:0')

y = graph.get_tensor_by_name('y:0')

# restore之后不需要执行variable初始化
#sess.run(tf.global_variables_initializer())
print (sess.run(graph.get_tensor_by_name('w:0')))
print (sess.run(y, feed_dict={x1: 1., x2: 2.}))

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值