tf.Variable()与tf.get_variable()的区别

关于tf.Variable()与tf.get_variable()的区别,很多博客都在罗列传入参数的不同,然后推荐使用tf.get_variable(),因为更适合复用。本人才疏学浅,看不出参数不同怎么就会影响复用。通过阅读这篇博客,加以自己的理解,阐述两者的区别和为何tf.get_variable()更适合参数复用。

tf.Variable()

对于tf.Variable()定义的变量,如x = tf.Variable(3, name="x")。当多次调用x时,系统会自动给变量编号x,x_1,x_2来解决命名冲突。例如,定义如下的加法:

def add_function():
    x = tf.Variable(3, name="x_scalar")
    y = tf.Variable(2, name="y_scalar")
    addition = tf.add(x,  y, name="add_function")
    print("=== checking Variables ===")
    print("x:", x, "\ny:", y, "\n")
    return addition

并分两次调用该函数:

result1 = add_function()
result2 = add_function()

得到的结果是:

=== checking Variables ===
x: <tf.Variable 'x_scalar:0' shape=() dtype=int32_ref> 
y: <tf.Variable 'y_scalar:0' shape=() dtype=int32_ref> 

=== checking Variables ===
x: <tf.Variable 'x_scalar_1:0' shape=() dtype=int32_ref> 
y
`tf.variable_scope` 是 TensorFlow 的一个函数,用于管理变量的命名空间。它可以用来创建和共享变量,并控制变量命名的规则和作用域。使用 `tf.variable_scope` 可以避免变量名冲突的问题,也可以方便地查看和管理变量。 在 TensorFlow 中,变量是我们需要训练的模型参数,`tf.variable_scope` 可以让我们对这些变量进行管理。例如,我们可以使用 `tf.variable_scope` 来给变量命名,如: ``` with tf.variable_scope('my_variable_scope'): weights = tf.get_variable('weights', [784, 256], initializer=tf.random_normal_initializer()) ``` 这里,我们使用 `tf.get_variable` 创建了一个名为 `weights` 的变量,并将其放在了一个名为 `my_variable_scope` 的命名空间中。这样,在后续的代码中,我们就可以通过 `tf.variable_scope` 和 `tf.get_variable` 来方便地获取这个变量,而不用担心变量名冲突的问题。 除了命名空间的管理,`tf.variable_scope` 还可以控制变量的共享。例如,我们可以使用 `reuse` 参数来共享变量: ``` with tf.variable_scope('my_variable_scope'): weights1 = tf.get_variable('weights', [784, 256], initializer=tf.random_normal_initializer()) with tf.variable_scope('my_variable_scope', reuse=True): weights2 = tf.get_variable('weights') ``` 这里,在第一个 `with` 块中,我们创建了一个名为 `weights` 的变量。在第二个 `with` 块中,我们通过将 `reuse` 参数设置为 `True` 来告诉 TensorFlow 我们要共享变量。然后,我们再次调用 `tf.get_variable('weights')` 来获取这个变量,这次 TensorFlow 将返回之前创建的那个变量,而不是创建一个新的变量。这样,我们就可以方便地在不同的代码块中共享变量了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>