2017-07-20 3 views
1

TensorFlowを使用していて、変数の再利用の問題に関するエラーが発生しました。次のように私のコードは次のとおりです。私は、コードを実行しようとしたTensorFlow、変数weightes/layer1は既に存在し、許可されていません

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: 

。問題は、

with tf.variable_scope(): 

またはTensorFlowのバージョンの使用に関連しているようです。誰でもこの問題に対処できますか?どうもありがとう!

答えて

0

あなたは一部#with other codes follows#inferenceを呼び出そう場合は、追加のパラメータ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) 

    .... 

スコープで変数を作成まず、時間と次の回あなたがそれを「再利用」。

+0

ありがとうございました!しかし、実際は私は後の部分で推論関数を呼び出さなかった。このコードは、https://github.com/caicloud/tensorflow-tutorial/blob/master/Deep_Learning_with_TensorFlow/1.0.0/Chapter05/5.%20MNIST%E6%9C%80%E4%BD%のチュートリアルからわずかに変更されています。 B3%E5%AE%9E%E8%B7%B5/mnist_train.py、ここでソースコードを見ることができます。 –

+0

エラーが発生したコードを表示すると、より具体的に話すことができます。 同じ名前で同じスコープ内で変数reuse = Trueを使用せずに変数を2回取得しようとすると、このエラーが表示されることがあります。 –

+0

あなたは正しいです。この関数は明示的には呼び出されませんが、トレーニングプロセスで繰り返し呼び出されるため、エラーが発生します。このリンクをクリックすると、それに続くコードが表示されます。問題を指摘してくれてありがとう。私は最初に呼び出された後、パラメータの再利用をTrueに設定する方法を理解する必要があります。 –

関連する問題