【发布时间】:2018-04-02 23:15:38
【问题描述】:
我尝试使用 variable_scope 管理张量。问题是每次运行代码 sn-p 时,它都会创建一个带有索引的新张量
例如:
import tensorflow as tf
parameters = {}
with tf.variable_scope("layer1"):
parameters["b1"] = tf.add(1,1)
with tf.variable_scope("layer1"):
parameters["b2"] = tf.add(1,1)
print(parameters["b1"])
print(parameters["b2"])
你多次运行代码,它会创建
Tensor("layer1_1/Add:0", shape=(), dtype=int32)
Tensor("layer1_2/Add:0", shape=(), dtype=int32)
Tensor("layer1_3/Add:0", shape=(), dtype=int32)
Tensor("layer1_4/Add:0", shape=(), dtype=int32)
....
我怎样才能防止这种情况发生?
解决方案:
所以不关闭-重新打开范围将解决部分问题:
with tf.variable_scope("layer1"):
parameters["b1"] = tf.add(1,1)
parameters["b2"] = tf.add(1,1)
如果你想在两者之间做一些其他的事情,并且你必须关闭范围,那么你可以像这样捕获它:
with tf.variable_scope("layer1") as s: # remembering scope in s
[ create some tensors... ]
[ scope closed ]
with tf.variable_scope( s.original_name_scope ): # reopen same name scope again
[ declare new variables within same name scope ]
这将在两个 variable_scope 之间共享 name_scope
【问题讨论】:
标签: python tensorflow