tf.variable_scope()用法详解

本文深入探讨了TensorFlow中变量作用域的概念,演示了如何使用tf.variable_scope创建新变量,以及如何通过tf.AUTO_REUSE和reuse=True选项实现变量的复用,确保了变量在不同作用域下的唯一性和共享。

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

https://www.tensorflow.org/api_docs/python/tf/variable_scope?hl=en
在这里插入图片描述
本质是一个上下文管理器。

创建新变量

import tensorflow as tf
with tf.variable_scope("foo"):
    with tf.variable_scope("bar"):
        v = tf.get_variable("v", [1])
        assert v.name == "foo/bar/v:0"

通过tf.AUTO_REUSE分享变量

def foo():
  with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
    v = tf.get_variable("v", [1])
  return v

v1 = foo()  # Creates v.
v2 = foo()  # Gets the same, existing v.
assert v1 == v2

通过reuse=True分享变量

with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1])
with tf.variable_scope("foo", reuse=True):
    v1 = tf.get_variable("v", [1])
assert v1 == v
关于我之前问你的代码,有几个问题,@property是什么用法 def call(self, inputs, state, scope=‘convLSTM’): “”“Long short-term memory cell (LSTM).”“” with tf.variable_scope(scope or type(self).name): # “BasicLSTMCell” # Parameters of gates are concatenated into one multiply for efficiency. if self._state_is_tuple: c, h = state else: c, h = tf.split(state, 2, 3) concat = _conv_linear([inputs, h], self.filter_size, self.num_features * 4, True) # i = input_gate, j = new_input, f = forget_gate, o = output_gate i, j, f, o = tf.split(concat, 4, 3) new_c = (c * tf.nn.sigmoid(f + self._forget_bias) + tf.nn.sigmoid(i) * self._activation(j)) new_h = self._activation(new_c) * tf.nn.sigmoid(o) if self._state_is_tuple: new_state = LSTMStateTuple(new_c, new_h) else: new_state = tf.concat([new_c, new_h], 3) return new_h, new_state 这一段我需要更详细解释 def _conv_linear(args, filter_size, num_features, bias, bias_start=0.0, scope=None): dtype = [a.dtype for a in args][0] with slim.arg_scope([slim.conv2d], stride=1, padding='SAME', activation_fn=None, scope=scope, weights_initializer=tf.truncated_normal_initializer(mean=0.0, stddev=1.0e-3), biases_initializer=bias and tf.constant_initializer(bias_start, dtype=dtype)): if len(args) == 1: res = slim.conv2d(args[0], num_features, [filter_size[0], filter_size[1]], scope='LSTM_conv') else: res = slim.conv2d(tf.concat(args, 3), num_features, [filter_size[0], filter_size[1]], scope='LSTM_conv') return res 这一段也详细解释
03-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值