Tensorflow会话和图形上下文

时间:2017-06-01 10:30:53

标签: tensorflow

我的问题是关于上下文和TensorFlow默认会话和图表。

问题: 在以下情形中,Tensorflow无法提供占位符: 函数Test定义图形。 函数Test_Once定义会话。 当函数Test调用Test_Once时 - >喂食失败。 当我更改代码时,函数Test声明图形+会话 - >一切正常。

以下是代码:

def test_once(g, saver, summary_writer, logits, images, summary_op):
  """Run a session once for a givven test image.

  Args:
    saver: Saver.
    summary_writer: Summary writer.
    logits: 
    summary_op: Summary op.
  """
  with tf.Session(graph=g) as sess:
    ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
    if ckpt and ckpt.model_checkpoint_path:
      # Restores from checkpoint
      saver.restore(sess, ckpt.model_checkpoint_path)

      # extract global_step from it.
      global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
    else:
      print('No checkpoint file found')
      return

    images.astype(np.float32)

    predictions = sess.run(logits, feed_dict={'InputPlaceHolder/TestInput:0':images})

    summary = tf.Summary()
    summary.ParseFromString(sess.run(summary_op))
    summary_writer.add_summary(summary, global_step)

    return (predictions)


def test():
  """Test LCPR with a test image"""
  with tf.Graph().as_default() as g:

    # Get image for testing
    images, labels = lcpr.test_input()

    # Build a Graph that computes the logits predictions from the
    # inference model.
    with tf.name_scope('InputPlaceHolder'):

        test_image_placeholder = tf.placeholder(tf.float32, (None,None,None,3), 'TestInput')
        # Display the training images in the visualizer.
        # The 'max_outputs' default is 3. Not stated. (Max number of batch elements to generate images for.)
        #tf.summary.image('input_images', test_image_placeholder)


    with tf.name_scope('Inference'):
        logits = lcpr.inference(test_image_placeholder)


    # Restore the moving average version of the learned variables for eval.
    variable_averages = tf.train.ExponentialMovingAverage(
        lcpr.MOVING_AVERAGE_DECAY)
    variables_to_restore = variable_averages.variables_to_restore()
    saver = tf.train.Saver(variables_to_restore)

    # Build the summary operation based on the TF collection of Summaries.
    writer = tf.summary.FileWriter("/tmp/lcpr/test")
    writer.add_graph(g) 

    summary_op = tf.summary.merge_all()
    summary_writer = tf.summary.FileWriter(FLAGS.test_dir, g)

    #Sadly, this will not work:     
    predictions = test_once(g, saver, summary_writer, logits, images, summary_op)

    '''Alternative working option :  
    with tf.Session() as sess:
        ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
        if ckpt and ckpt.model_checkpoint_path:
          # Restores from checkpoint
          saver.restore(sess, ckpt.model_checkpoint_path)
          # Assuming model_checkpoint_path looks something like:
          #   /my-favorite-path/cifar10_train/model.ckpt-0,
          # extract global_step from it.
          global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
        else:
          print('No checkpoint file found')
          return

        x = sess.run(logits, feed_dict={'InputPlaceHolder/TestInput:0':images})
        print(x)
    '''

以上代码显示占位符未送达的错误:

InvalidArgumentError(请参阅上面的回溯):您必须为占位符张量提供一个值" InputPlaceHolder / TestInput'使用dtype float

并不是说TensorFlow无法识别占位符。如果我从' InputPlaceHolder / TestInput更改名称:0'到' InputPlaceHolder / TestInput:1 '我收到一条消息,说明' InputPlaceHolder / TestInput '存在但只有1个输出。这是有道理的,我猜会话会在我的默认图表上运行。

如果我保持在相同的def范围内,事情只对我有用: 如果我通过直接从第一个函数中运行注释部分(以tf.Session()作为sess :)开始更改代码,则所有工作都可以。

我想知道我错过了什么? 我的猜测是与上下文相关的,可能没有将会话分配给图表?

1 个答案:

答案 0 :(得分:2)

解决。愚蠢的错误 test_once两次调用sess.run。在第二次,确实没有占位符被喂食....:summary.ParseFromString(sess.run(summary_op))