按名称访问TensorFlow变量的问题

时间:2017-06-21 18:09:03

标签: python tensorflow

在下面的块中,我们为每个convo图层创建权重变量W,其名称为"hidden0/weights",用于我们网络的第一个卷积层。

def convo_layer(num_in, num_out, width, prev, num, relu=True):
    with tf.variable_scope('hidden' + str(num)):
        initial = tf.truncated_normal([width, width, num_in, num_out], stddev=(2 / math.sqrt(width * width * num_in)))
        W = tf.Variable(initial, name = 'weights')
        initial = tf.constant(0.1, shape=[num_out])
        b = tf.Variable(initial, name='biases')
        if relu:
            h = tf.nn.relu(conv2d(prev, W, num) + b)
        else:
            h = conv2d(prev, W, num) + b
     return h

但是,当我们尝试稍后在带有

的代码中按名称访问此变量时
def get_vars(num):
    with tf.variable_scope('hidden' + str(num), reuse = True):
      tf.get_variable_scope().reuse_variables()
      weights = tf.get_variable('weights')

我们收到以下错误消息:

ValueError: Variable hidden0/weights does not exist, or was not 
created with tf.get_variable(). Did you mean to set reuse=None in VarScope?

我们尝试使用tf.get_variable()以下列方式创建W:

def convo_layer(num_in, num_out, width, prev, num, relu=True):
    with tf.variable_scope('hidden' + str(num)):
        initial = tf.truncated_normal([width, width, num_in, num_out], stddev=(2 / math.sqrt(width * width * num_in)))
        W = tf.get_variable("weights", initial)
        initial = tf.constant(0.1, shape=[num_out])
        b = tf.Variable(initial, name='biases')
        if relu:
            h = tf.nn.relu(conv2d(prev, W, num) + b)
        else:
            h = conv2d(prev, W, num) + b
        return h

但是,在构建我们的网络时,我们会收到错误

TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use 
`if t is not None:` instead of `if t:` to test if a tensor is 
defined, and use TensorFlow ops such as tf.cond to execute subgraphs 
conditioned on the value of a tensor.

这让我们感到难过。

我们应该如何创建和检索权重?

1 个答案:

答案 0 :(得分:0)

使用tf.Variable创建的变量对于变量范围是不可见的,您需要使用tf.get_variable创建变量。

你看到的错误来自你的代码中的“if relu”,我认为(它肯定来自if,堆栈跟踪应该清楚地指出哪一个)。