在 tensorflow CIFAR-10 中 tutorial在 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 /图形的脚本中运行。或者我可以将另一个脚本中的图形作为参数传递给这个函数,但我很困惑。
即使 tensorflow 函数像这样或推理,例如似乎以全局方式定义图形而没有明确将其作为输出返回的事实对我来说也有点难以理解。
最佳答案
您可以使用 tf.cond(pred, fn1, fn2, name=None)
( see doc )。
此函数允许您使用 pred
的 bool 值。在 TensorFlow 图中(无需调用 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)
关于random - 在 TensorFlow 图中使用 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37299345/