tensorflow保存变量的本质

本文探讨了在TensorFlow中使用tf.Variable时命名的重要性,解释了如何通过自定义变量名来简化模型保存与加载的过程。当变量未被命名时,系统会自动分配名称,这可能在变量提取时造成不便。通过实例演示了命名变量与未命名变量的区别。

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

前面博客已经说过,tf.Variable的本质就是C++变量或者数组,所以在声明变量时,最好自己给定变量一个名字,如下代码:
import tensorflow as tf
import numpy as np
w = tf.Variable([[11,12,13],[22,23,25]],dtype=tf.float32,name=“w”)
save = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
save_path = save.save(sess,“my_net/save_net.ckpt”)
print(“保存路径:”,save_path)
执行sess.run(init后,相当于执行c++代码:float w[2][3]={{11,12,13},{22,23,25}}
tensorflow保存变量实际 上是保存的C++ 浮点二维数组w
如果声明tf.Variable时,不给名字,tensorflow会给一个名字,以后提取变量时,不能根据变量名字提取变量值,太依赖变量声明的顺序

看代码:
import tensorflow as tf
import numpy as np

data1=tf.Variable([1,2,3],dtype=tf.int32)
data2=tf.Variable([1,2,3],dtype=tf.int32,name=“data2”)
data3=tf.Variable([1,2,3],dtype=tf.int32)
data4=tf.Variable([1,2,3],dtype=tf.int32)

init = tf.global_variables_initializer()

with tf.Session() as sess:
sess.run(init)
print(data1)
print(data2)
print(data3)
print(data4)
输出为:
<tf.Variable ‘Variable:0’ shape=(3,) dtype=int32_ref>
<tf.Variable ‘data2:0’ shape=(3,) dtype=int32_ref>
<tf.Variable ‘Variable_1:0’ shape=(3,) dtype=int32_ref>
<tf.Variable ‘Variable_2:0’ shape=(3,) dtype=int32_ref>
变量data1,data3,data4的名字为系统给定的,data2的名字为自己给定的,系统的给定的名字格式为:Variable_n:0,其中n与变量声明的顺序有关

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值