无名商城论坛

搜索
查看: 304|回复: 0

[其他技术] 【HC】共享变量

[复制链接]

1万

主题

1万

帖子

3万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
32464
发表于 2022-5-8 18:36:11 | 显示全部楼层 |阅读模式

一、对 tf.Variable() 的讨论首先我们知道 tf.Variable() 函数的使用方法import tensorflow as tfvar1 = tf.Variable(tf.constant(0.5), name='var', dtype=tf.float32)print (var1.name)输出var:0现在思考,如果我想继续再其他的模型中使用这个变量怎么办,比如,GAN网络中的生成器和判别器,如果要是使用 tf.Variable()然后用同样的变量名字,那样会得到一个新的变量而不是我们原先需要。import tensorflow as tf var1 = tf.Variable(tf.constant(0.5), name='var', dtype=tf.float32)print (var1.name) var2 = tf.Variable(tf.constant(0.5), name='var', dtype=tf.float32)print (var2.name)输出var:0var_1:0可以看到,系统直接给了一个新的变量名字,而不是使用之前我们定义的那个 var1。二、摒弃 tf.Variable() 使用 tf.variable_scope() 与 tf.get_variable() 的组合tf.get_variable(),如果变量的名字没有被使用过,那么该语句就是建立一个新的变量,和 tf.Variable() 没有任何的区别,如果变量的名字之前在该“图”中被使用过,那么如果直接使用这个语句会报错,因为一个“图中” tf.get_variable()只能定义同一个名字的变量(样例:code_1),所以如果此时需要共享之前的那个变量,需要配合 tf.variable_scope()(样例:code_2)。tf.variable_scope() 相当于一个命名空间,然后可以嵌套使用,可以当作是一个地址,路径之类的东西。# code_1: import tensorflow as tf var3 = tf.get_variable(name='var_', dtype=tf.float32, initializer=tf.constant(3.3333))print (var3.name) var4 = tf.get_variable(name='var_', dtype=tf.float32)print (var4.name)输出,报错  File "D:/pycodeLIB/TensorFlow/test.py", line 22, in <module>    var4 = tf.get_variable(name='var_', dtype=tf.float32)  File "D:\python3.6.4\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 1328, in get_variable    constraint=constraint)  File "D:\python3.6.4\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 1090, in get_variable    constraint=constraint)  File "D:\python3.6.4\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 435, in get_variable    constraint=constraint)  File "D:\python3.6.4\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 404, in _true_getter    use_resource=use_resource, constraint=constraint)  File "D:\python3.6.4\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 743, in _get_single_variable    name, "".join(traceback.format_list(tb))))ValueError: Variable var_ already exists, disallow
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表