tensorflow变量作用域

1.tf.Variable

2.tf.get_variable和tf.variable_scope

import tensorflow as tf
# 方式一
def my_func(x):
    w1 = tf.Variable(tf.random_normal([1]))[0]  # tf.random_normal([1])得到一个服从正态分布的一维数组,后面[0]意思是将值取了出来
    b1 = tf.Variable(tf.random_normal([1]))[0]
    r1 = w1*x+b1

    w2 = tf.Variable(tf.random_normal([1]))[0]
    b2 = tf.Variable(tf.random_normal([1]))[0]
    r2 = w2*r1+b2

    return r1, w1, b1, r2, w2, b2

# 下面两行代码还是属于图的构建
x = tf.constant(3, dtype=tf.float32)
r = my_func(x)
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    tf.global_variables_initializer().run()
    print(sess.run(r))
'''


'''
# 方式二
def my_func(x):
    w = tf.Variable(tf.random_normal([1]))[0]  # tf.random_normal([1])得到一个服从正态分布的一维数组,后面[0]意思是将值取了出来
    b = tf.Variable(tf.random_normal([1]))[0]
    r = w * x + b
    return r, w, b


def func(x):  # 使得上面my_func()初始化了两次w和b,若想每次都使用相同的w和b值用tf.get_variable和tf.variable_scope
    r1 = my_func(x)
    r2 = my_func(r1[0])
    return r1, r2

# 下面两行代码还是属于图的构建
x = tf.constant(3, dtype=tf.float32)
r = func(x)
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    tf.global_variables_initializer().run()
    print(sess.run(r))
'''



'''
# 方式三
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))]
    ''
'''

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值