TensorFlow,可变权重/ layer1已经存在,不允许

时间:2017-07-20 18:32:26

标签: tensorflow

我使用的是TensorFlow,遇到了与变量重用问题相关的错误。我的代码如下:

INPUT_NODE = 3000
OUTPUT_NODE = 20
LAYER1_NODE = 500

def get_weight_variable(shape, regularizer):
    weights = tf.get_variable(
            "weights", shape,
            initializer = tf.truncated_normal_initializer(stddev=0.1))

    if regularizer != None:
        tf.add_to_collection('losses', regularizer(weights))
    return weights


def inference(input_tensor, regularizer):
    with tf.variable_scope('layer1'):
        weights = get_weight_variable(
                [INPUT_NODE, LAYER1_NODE], regularizer)
        biases = tf.get_variable(
                "biases",[LAYER1_NODE],
                initializer = tf.constant_initializer(0.0))
        layer1 = tf.nn.relu(tf.matmul(input_tensor,weights) + biases)

    with tf.variable_scope('layer2'):
        weights = get_weight_variable(
                [LAYER1_NODE, OUTPUT_NODE], regularizer)
        biases = tf.get_variable(
                "biases",[OUTPUT_NODE],
                initializer = tf.constant_initializer(0.0))
        layer2 = tf.matmul(layer1,weights) + biases

    return layer2

def train():
    x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input')
    y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE], name='y-input')

    regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)

    y = inference(x, regularizer)

    #with other codes follows#

def main(argv=None):
    train()

if __name__ == '__main__':
    tf.app.run()

当我尝试运行代码时,会发生错误:

ValueError: Variable layer1/weights already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:

我在Stack Overflow上检查了其他答案。似乎问题与

的使用有关
with tf.variable_scope():

或者可能是TensorFlow的版本?有人可以帮我解决这个问题吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

如果您尝试拨打部分inference中的#with other codes follows#,则需要增加参数reuse,如下所示:

....

def inference(input_tensor, regularizer, reuse):
    with tf.variable_scope('layer1', reuse = reuse):
     ....

def train():
    x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input')
    y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE], name='y-input')

    regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)

    y = inference(x, regularizer, False)

    #with other codes follows#

    z = inference(x, None, True)

    ....

首次在范围内创建变量,然后再次使用"重复使用"它