Tensorflow - tf.cond(...) 下的未初始化变量

数据挖掘 机器学习 神经网络 张量流
2022-02-12 08:40:09

我有张量流的问题。我在其构造函数中创建了一个带有参数的全连接层类,通过该类is_hidden_layer我决定在层输出上使用或不使用 relu 和批量标准化。代码如下:

class FullLayer(object):
  def __init__(self, neurons, is_hidden_layer):
    self.is_hidden_layer = is_hidden_layer
    self.neurons = neurons

  def build(self, input):
    # ... uninteresting initialization code ... 
    W = tf.Variable(tf.truncated_normal([input_shape, self.neurons], stddev=0.1))
    b = tf.Variable(tf.truncated_normal([self.neurons], stddev=0.1))
    hidden = tf.Variable(tf.constant(self.is_hidden_layer), name="is_hidden")
    output = tf.matmul(input, W) + b
    output = self.batch_norm(output)
    return tf.cond(tf.equal(hidden, True), lambda: tf.nn.relu(output), lambda: output)

  def batch_norm(self, input):
    with tf.variable_scope('batch_normalize'):
      mean = tf.Variable(tf.constant(0.0, shape=[input.shape[-1]]),
                        trainable=True)
      # ... not interesting batch normalization code ...

这段代码工作正常。但是,如果将最后两行更改build为这一行:

return tf.cond(tf.equal(hidden, True), lambda: tf.nn.relu(self.batch_norm(output)), lambda: output)

(我把)我batch_norm得到cond一个错误:

FailedPreconditionError(参见上面的回溯):尝试使用未初始化的值 fc1/is_hidden [[Node: fc1/is_hidden/read = IdentityT=DT_BOOL, _class=["loc:@fc1/is_hidden"], _device="/job:localhost /replica:0/task:0/cpu:0"]]

这里抛出异常:

with tf.Session() as session:
  session.run(tf.global_variables_initializer())

当我替换为方法中的变量时hiddenhidden.initialized_value()我得到相同的错误batch_norm我也会在那里进行相同的更改,但是会发生其他副作用,例如global_step变量(我传递给 AdamOptimizer 以计算步数的变量)不会递增并且始终保持等于 0。这是我完全不明白的事情。

这背后的原因是什么?

0个回答
没有发现任何回复~