tf.Variable与tf.get_variable的区别

尽量使用tf.get_variable,当你想共享这个变量时,这样能够更容易重构代码。

tf.Variable所在的层次更低,更接近底层,有时候tf.get_variable不能使用时,tf.Variable仍然能够使用。

tf.Variable
__init__(
    initial_value=None,
    trainable=None,
    collections=None,
    validate_shape=True,
    caching_device=None,
    name=None,
    variable_def=None,
    dtype=None,
    expected_shape=None,
    import_scope=None,
    constraint=None,
    use_resource=None,
    synchronization=tf.VariableSynchronization.AUTO,
    aggregation=tf.VariableAggregation.NONE,
    shape=None
)
tf.get_variable(
    name,
    shape=None,
    dtype=None,
    initializer=None, #可以是一个初始化的对象或者张量
    regularizer=None,
    trainable=None,
    collections=None,
    caching_device=None,
    partitioner=None,
    validate_shape=True,
    use_resource=None,
    custom_getter=None,
    constraint=None,
    synchronization=tf.VariableSynchronization.AUTO,
    aggregation=tf.VariableAggregation.NONE
)

参考1
参考2
参考3

`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、付费专栏及课程。

余额充值