【问题标题】:How to define a layer only for training phase in TensorFlow?如何为TensorFlow中的训练阶段定义一个层?
【发布时间】:2017-07-02 01:56:11
【问题描述】:

我想知道是否可以仅为 TensorFlow 中的训练阶段定义一个层(卷积、元素求和等)。

例如,我想在我的网络中有一个元素求和层,仅用于训练阶段,我想在测试阶段忽略这个层。

这在 Caffe 中很容易实现,我想知道在 TensorFlow 中是否也可以这样做。

【问题讨论】:

    标签: tensorflow neural-network deep-learning caffe conv-neural-network


    【解决方案1】:

    我认为您可以在 tf.cond() 中使用布尔占位符。 就像这样:

    train_phase = tf.placeholder(tf.bool, [])
    x = tf.constant(2)
    def f1(): return tf.add(x, 1)
    def f2(): return tf.identity(x)
    r = tf.cond(train_phase, f1, f2)
    sess.run(r, feed_dict={train_phase: True})  # training phase, r = tf.add(x, 1) = x + 1
    sess.run(r, feed_dict={train_phase: False})  # testing phase, r = tf.identity(x) = x
    

    【讨论】:

      【解决方案2】:

      您可能希望使用“tf.cond”control_flow 操作来执行此操作。 https://www.tensorflow.org/api_docs/python/control_flow_ops/control_flow_operations#cond

      【讨论】:

      • 谢谢。但是我应该在“pred”参数中加入什么来将训练阶段与测试阶段分开?
      • 根据文档:一个标量,确定是返回 fn1 还是 fn2 的结果。 ;) 在这种情况下,我认为您可以提供 train_phase 张量。让我知道这是否有帮助!
      【解决方案3】:

      我认为你可以通过if 做到这一点

      Train = False
      
      x = tf.constant(5.)
      y = x + 1
      if Train:
          y = y + 2
      y = y + 3
      
      with tf.Session() as sess:
          res = sess.run(y) # 11 if Train else 9
      

      【讨论】:

        猜你喜欢
        • 2017-10-08
        • 1970-01-01
        • 1970-01-01
        • 2019-08-22
        • 1970-01-01
        • 2017-07-27
        • 2021-07-13
        • 1970-01-01
        • 2021-03-31
        相关资源
        最近更新 更多