class E():
def __init__(self):
self.sess = tf.Session()
xav_init = tf.contrib.layers.xavier_initializer
self.b_Wi = tf.get_variable(name='b_Wi', shape=[2,3], dtype=tf.float32, initializer=xav_init())
e = E()
e1 = E()
执行上述代码时出现以下错误。
ValueError: Variable b_Wi already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:
我知道他们是解决方法,但我更想了解上面背后的逻辑。实例不应该有自己单独的变量。为什么它们与上面的 b/we 和 e1 共享?
from itertools import count
import tensorflow as tf
class E():
_ids = count(0)
def __init__(self):
self.id = next(self._ids)
self.sess = tf.Session()
xav_init = tf.contrib.layers.xavier_initializer
with tf.variable_scope("share") as sp:
print(self.id)
if self.id > 0:
tf.get_variable_scope().reuse_variables()
self.b_Wi = tf.get_variable(name='b_Wi', shape=[2,3], dtype=tf.float32, initializer=xav_init())
e1 = E()
e2 = E()
assert(e1.b_Wi == e2.b_Wi) # thus they are exactly the same object in the same graph and hence affect each other.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句