笔记 - tensorflow中 Variable 与 get_variable 的用法

这篇笔记探讨了在TensorFlow中Variable和get_variable的使用差异,指出在name_scope下,Variable无法实现变量重复使用,而get_variable可以。文章引发思考何时需要对变量进行重复使用。

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

莫烦 scope 命名方法


  • 我们为什么要对变量命名
举个例子:在迁移学习中我们是通过变量名加载相应的值
# restore variables
# redefine the same shape and same type for your variables
W = tf.Variable(np.arange(6).reshape((2, 3)), dtype=tf.float32, name="weights")  # 这个name必须是保存变量时的名字
b = tf.Variable(np.arange(3).reshape((1, 3)), dtype=tf.float32, name="biases")

# not need init step

saver = tf.train.Saver()
with tf.Session() as sess:
    saver.restore(sess, "my_net/save_net.ckpt")
    print("weights:", sess.run(W))
    print("biases:", sess.run(b))

"""
完整代码:https://github.com/MorvanZhou/tutorials/blob/master/tensorflowTUT/tf19_saver.py
"""

对创建变量的方式有两种

tf.Variable()
tf.get_variable()

和命名相关的还有

tf.name_scope() 与 tf.variable_scope()
提问:
  • 在name_scope下,使用Variable命名与使用get_variable命名有什么区别
Variable的name会受name_scope影响
get_variable的name不受name_scope影响
相关结论
  • name_scope Variable做不到变量重复使用的效果
进一步思考
  • 什么时候需要对变量重复使用

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值