TensorFlow-tf.variable_scope与tf.name_scope函数的区别

部署运行你感兴趣的模型镜像

这两个函数都提供了命名空间管理的功能,它们在大部分情况下是等价的,唯一的区别是在使用tf.get_variable函数时。以下代码简单地说明了这两个函数的区别:


import tensorflow as tf

with tf.variable_scope("foo"):
    # 在命名空间foo下获取变量"bar", 于是得到的变量名称为“foo/bar”
    a = tf.get_variable("bar", [1])
    print(a.name)            # 输出: foo/bar:0


with tf.variable_scope("bar"):
    # 在命名空间bar下获取变量“bar”,于是得到变量名称为“bar/bar”。
    # 此时,变量“bar/bar”和变量“foo/bar”并不冲突,于是可以正常运行
    b = tf.get_variable("bar", [1])
    print(b.name)            # 输出: bar/bar:0

with tf.name_scope("a"):
    # 使用tf.Variable函数生成变量会受tf.name_scope影响,于是这个变量的名称为“a/Variable"
    a = tf.Variable([1])
    print(a.name)       # 输出: a/Variable:0

    # tf.get_variable函数不受tf.name_scope函数影响,于是变量并不在a这个命名空间中。
    a = tf.get_variable("b", [1])
    print(a.name)         # 输出: b:0

with tf.name_scope("b"):
    # 因为tf.get_variable不受tf.name_scope影响,所以这时将试图获取名称为“b”的变量。
    # 然而这个变量已经被声明了,于是这里会报重复声明的错误:
    tf.get_variable("b", [1])

输出:

C:\ProgramData\Anaconda3\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2017.2.3\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 56737 --file D:/doc.pycharm/TFbook/p231_variable_scope_and_name_scope.py
pydev debugger: process 295916 is connecting

Connected to pydev debugger (build 172.3968.37)
foo/bar:0
bar/bar:0
a/Variable:0
b:0
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.2.3\helpers\pydev\pydevd.py", line 1599, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.2.3\helpers\pydev\pydevd.py", line 1026, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.2.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "D:/doc.pycharm/TFbook/p231_variable_scope_and_name_scope.py", line 34, in <module>
    tf.get_variable("b", [1])
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 1065, in get_variable
    use_resource=use_resource, custom_getter=custom_getter)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 962, in get_variable
    use_resource=use_resource, custom_getter=custom_getter)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 367, in get_variable
    validate_shape=validate_shape, use_resource=use_resource)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 352, in _true_getter
    use_resource=use_resource)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 664, in _get_single_variable
    name, "".join(traceback.format_list(tb))))
ValueError: Variable b already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1269, in __init__
    self._traceback = _extract_stack()
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2506, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op
    op_def=op_def)


Process finished with exit code 1

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

### TensorFlow 中 `variable_scope` 的变量共享分组 在 TensorFlow 中,`variable_scope` 是一个非常重要的工具,用于管理变量的创建、共享和分组。通过 `variable_scope`,可以实现变量的重用,从而避免重复创建相同的变量。以下是一个使用 `variable_scope` 和 `pre_batch` 的示例。 #### 代码示例 ```python import tensorflow as tf # 定义输入数据 input_data = tf.placeholder(tf.float32, shape=[None, 10], name="input_data") # 使用 variable_scope 创建变量并进行分组 with tf.variable_scope("shared_variables") as scope: # 第一层全连接层 weights1 = tf.get_variable("weights", [10, 20], initializer=tf.truncated_normal_initializer(stddev=0.01)) biases1 = tf.get_variable("biases", [20], initializer=tf.zeros_initializer()) layer1 = tf.matmul(input_data, weights1) + biases1 # 重用变量 scope.reuse_variables() weights1_reused = tf.get_variable("weights") biases1_reused = tf.get_variable("biases") layer1_reused = tf.matmul(input_data, weights1_reused) + biases1_reused # 打印变量名以验证变量共享 print(weights1.name) print(weights1_reused.name) # 模拟批处理操作 def pre_batch_processing(data): # 对数据进行预处理(如归一化) mean = tf.reduce_mean(data, axis=0) normalized_data = data - mean return normalized_data normalized_input = pre_batch_processing(input_data) # 使用预处理后的数据重新计算 with tf.variable_scope("shared_variables", reuse=True): layer1_normalized = tf.matmul(normalized_input, weights1) + biases1 # 初始化并运行会话 init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) result = sess.run([layer1, layer1_reused, layer1_normalized], feed_dict={input_data: [[1.0] * 10]}) print(result) ``` #### 说明 上述代码展示了如何使用 `variable_scope` 进行变量共享和分组。首先定义了一个名为 `shared_variables` 的作用域,并在其中创建了权重和偏置变量。通过调用 `scope.reuse_variables()`,可以在同一作用域内重用这些变量。此外,还展示了一个简单的批处理预处理函数 `pre_batch_processing`,该函数对输入数据进行归一化处理[^5]。 #### 注意事项 - 在使用 `variable_scope` 时,确保正确设置 `reuse` 参数。如果需要重用变量,则必须显式调用 `scope.reuse_variables()` 或将 `reuse=True` 传递给 `variable_scope`。 - 预处理函数(如 `pre_batch_processing`)可以根据具体需求自定义,例如标准化、归一化或数据增强等操作。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值