UnboundLocalError:分配前已引用局部变量“ train_op”

时间:2019-07-28 07:21:54

标签: python tensorflow

在运行第一次迭代后,代码会告诉Train_op在使用之前已被引用。我也尝试在if语句之前初始化它,但是出现以下错误

  

TypeError:train_op必须为Operation或Tensor,给定为:{}

def cnn_model_fn(features, labels, mode):

    input_layer = tf.reshape(features["x"], [-1,32,32,3])
    conv1 = tf.layers.conv2d(inputs=input_layer, filters=32, kernel_size = [5,5],activation=tf.nn.relu)
    pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)
    conv2 = tf.layers.conv2d(inputs=pool1, filters=64, kernel_size = [5,5],activation=tf.nn.relu)
    pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

    pool2_flat = tf.reshape(pool2, [-1,5 * 5 * 64])
    dense = tf.layers.dense(inputs=pool2_flat, units=32, activation=tf.nn.relu)
    dropout = tf.layers.dropout(inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)

    logits = tf.layers.dense(inputs=dropout, units=2)
    #it will provide 2 outputs as cat or dog

    predictions = {
      "classes": tf.argmax(input=logits, axis=1),
      "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
    }
    if mode == tf.estimator.ModeKeys.PREDICT: 

        return tf.estimator.EstimatorSpec(mode-mode, predictions=predictions)

    #calculatng loss
    loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

    #traning op
    #train_op= ()
    if mode == tf.estimator.ModeKeys.TRAIN:
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
        train_op = optimizer.minimize(
          loss=loss,
          global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)    
    #evaluation matrix

    eval_metric_ops={"accuracy" : tf.metrics.accuracy(labels=labels, predictions=predictions["classes"])}
    return tf.estimator.EStimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)

1 个答案:

答案 0 :(得分:0)

好像您在train_op语句中创建if。是否更改了此内容?

if mode == tf.estimator.ModeKeys.TRAIN:
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
    train_op = optimizer.minimize(
      loss=loss,
      global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)  

对此:

if mode == tf.estimator.ModeKeys.TRAIN:
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
    train_op = optimizer.minimize(
      loss=loss,
      global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

解决您的问题?

请注意,您的第二个return是“不可访问的”,即,您将始终在到达第二个return语句之前从该函数返回。