random - 在 TensorFlow 图中使用 if 条件

标签 random tensorflow deep-learning

在 tensorflow CIFAR-10 中 tutorialcifar10_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/

相关文章:

python - Keras top_k_categorical_accuracy 指标与准确率相比极低

python - tensorflow API 检测盒及评测

python - 在 session 期间获取 tensorflow 占位符的值

neural-network - 如何计算 CNN 网络的 FLOPs

java - 我正在尝试生成一个随机的不同 3 或 4 位数字

python - 如何在 Tensorflow 中重用模型

perl - 有没有更有效的方法在 Perl 中生成随机文件?

python - Eager Execution 函数的输入不能是 Keras 符号张量

c# - 如何在C#类的构造函数中生成一个随机数

python - Pandas 、 python 。替换列中值的随机子集