在name_scope之外访问类似名称的tf.Variable对象

时间:2017-09-18 12:39:53

标签: tensorflow

我引用了here的Tensorflow图表(完整代码text classification using CNN)中的以下内容(convolution-relu-maxpool):

    ...
    pooled_outputs = []
    for i, filter_size in enumerate(filter_sizes):
        with tf.name_scope("conv-maxpool-%s" % filter_size):
            # Convolution Layer
            filter_shape = [filter_size, embedding_size, 1, num_filters]
            W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
            b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
            conv = tf.nn.conv2d(
                self.embedded_chars_expanded,
                W,
                strides=[1, 1, 1, 1],
                padding="VALID",
                name="conv")
            # Apply nonlinearity
            h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
            # Maxpooling over the outputs
            pooled = tf.nn.max_pool(
                h,
                ksize=[1, sequence_length - filter_size + 1, 1, 1],
                strides=[1, 1, 1, 1],
                padding='VALID',
                name="pool")
                pooled_outputs.append(pooled)
    ...

(修订版)

现在,请考虑以下示例代码:

    import tensorflow as tf

    shape = [1, 1, 1, 1]

    for idx in [1, 2]:
        with tf.name_scope("test%s" % idx):
            W = tf.Variable(tf.truncated_normal(shape, stddev=0.1), name="W")

如何使用标识符W访问这些权重变量/对象中的每一个,这些变量/对象都在各自的name_scope之外(我需要执行手动更新)。或者是否有另一种方法来共享这些对象而不会丢失范围?

我尝试将共享变量与variable_scope一起使用,如下所示:

shape = [1, 1, 1, 1]
for idx in [1, 2]:
    with tf.name_scope("test%s" % idx):
        with tf.variable_scope("in_scope%s" % idx, reuse=None):
            W = tf.get_variable("W%s" % idx, shape, dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1))

但是,在W.name内打印with tf.variable_scope("in_scope1", reuse=True)会按预期和要求返回in_scope2/W2:0而不是in_scope1/W1:0

我不确定我明白这里发生了什么。请有人澄清一下吗?

1 个答案:

答案 0 :(得分:-1)

也许这可以帮到你。在name_scope之外:

    for v in tf.trainable_variables():
        # print v.name

        if 'W' in v.name:
            # operate