对tf.get_variable()的进一步理解

情况一:w = tf.get_variable

在with tf.variable_scope(name=‘op’):下有使用w的相关代码,这样,会话中第一次执行到with tf.variable_scope(name=‘op’):的w相关代码时,用的w是第一次用初始化器构造的值,下一次用,发现w已经有值了,直接拿来用。

情况二w = tf.get_variable

既在with tf.variable_scope(‘op1’):下,又在with tf.variable_scope(‘op2’):下,都有使用w的代码,这样,会话中第一次执行with tf.variable_scope(‘op1’):下的w相关代码时,用到的w是第一次用初始化器构造的值w
1,紧接着又执行with tf.variable_scope(‘op2’):下的w相关的代码,会再次用初始化器构造值w2,然后去使用。 那后面,执行with tf.variable_scope(‘op1’):下的w的相关代码时,用的w现在已经有值了,就是w1;;;;执行with tf.variable_scope(‘op2’):下的w的相关代码时,用的w现在也已经有值了,就是w2。 这样,w就实现了共享

def my_func(x):
    # initializer:初始化器 第一次运行没问题,第二次运行时那个值已经存在了,但默认情况下它是不能存在的
    w = tf.get_variable(name='w', shape=[1], initializer=tf.random_normal_initializer())[0]
    # tf.random_normal_initializer()同tf.random_normal()类似
    
    b = tf.get_variable(name='b', shape=[1], initializer=tf.random_normal_initializer())[0]
    # 有对应名称(比如:name='w')的变量就获取,没有就创建
    
    r = w * x + b

    return r, w, b

def func(x):
    with tf.variable_scope("op1", reuse=tf.AUTO_REUSE):
        r1 = my_func(x)
    with tf.variable_scope("op2", reuse=tf.AUTO_REUSE):
        r2 = my_func(r1[0])
    return r1, r2


# 下面两行代码还是属于图的构建
x1 = tf.constant(3, dtype=tf.float32)
x2 = tf.constant(4, dtype=tf.float32)
r1 = func(x1)
r2 = func(x2)

with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    tf.global_variables_initializer().run()
    print(sess.run([r1, r2]))

    # 运行结果如下:
    # [((5.179422, 1.2175516, 1.5267673), (1.7860048, 0.3359851, 0.045796324)),
    # ((6.3969736, 1.2175516, 1.5267673), (2.195084, 0.3359851, 0.045796324))]

小理解

a = tf.Variable(1.0, name='a', dtype=tf.float32)
b = tf.get_variable(name='b', shape=[1], initializer=tf.random_normal_initializer())[0]
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(a, feed_dict={a: 2.0}))  # 2.0
    print(sess.run(b))  # -1.0582993
    print(sess.run(b, feed_dict={b: 2.0}))  # 2.0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值