在 TensorFlow 图中使用 if 条件

Using if conditions inside a TensorFlow graph

在 tensorflow CIFAR-10 tutorial in cifar10_inputs.py 第 174 行中,据说您应该随机化操作的顺序 random_contrast 和 random_brightness 以获得更好的数据扩充。

为此,我首先想到的是从 0 和 1 之间的均匀分布中抽取一个随机变量:p_order。并做:

if p_order>0.5:
  distorted_image=tf.image.random_contrast(image)
  distorted_image=tf.image.random_brightness(distorted_image)
else:
  distorted_image=tf.image.random_brightness(image)
  distorted_image=tf.image.random_contrast(distorted_image)

然而,有两种可能的选择来获得 p_order:

1) 使用 numpy 让我不满意,因为我想要纯 TF,而 TF 不鼓励其用户混合使用 numpy 和 tensorflow

2) 使用 TF,但是因为 p_order 只能在 tf.Session() 中计算 我真的不知道我是否应该这样做:

with tf.Session() as sess2:
  p_order_tensor=tf.random_uniform([1,],0.,1.)
  p_order=float(p_order_tensor.eval())

所有这些操作都在函数体内,并且 运行 来自另一个具有不同 session/graph 的脚本。或者我可以将其他脚本中的图形作为参数传递给此函数,但我很困惑。 甚至像这样的 tensorflow 函数或推理这样的事实似乎以全局方式定义图形而没有明确地将其作为输出返回,这对我来说有点难以理解。

您可以使用 tf.cond(pred, fn1, fn2, name=None) (see doc)。 此函数允许您在 TensorFlow 图形中使用 pred 的布尔值(无需调用 self.eval()sess.run(),因此 不需要 Session).

这是一个如何使用它的例子:

def fn1():
    distorted_image=tf.image.random_contrast(image)
    distorted_image=tf.image.random_brightness(distorted_image)
    return distorted_image
def fn2():
    distorted_image=tf.image.random_brightness(image)
    distorted_image=tf.image.random_contrast(distorted_image)
    return distorted_image

# Uniform variable in [0,1)
p_order = tf.random_uniform(shape=[], minval=0., maxval=1., dtype=tf.float32)
pred = tf.less(p_order, 0.5)

distorted_image = tf.cond(pred, fn1, fn2)