【问题标题】:Using if conditions inside a TensorFlow graph在 TensorFlow 图中使用 if 条件
【发布时间】:2016-05-18 12:15:45
【问题描述】:

在 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())

所有这些操作都在函数体内,并从具有不同会话/图形的另一个脚本运行。或者我可以将另一个脚本中的图表作为参数传递给这个函数,但我很困惑。 即使像这样的 tensorflow 函数或推理之类的函数似乎以全局方式定义图形而没有明确将其作为输出返回,这对我来说有点难以理解。

【问题讨论】:

    标签: random tensorflow deep-learning


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

      猜你喜欢
      • 2016-06-20
      • 2016-03-08
      • 2020-11-02
      • 1970-01-01
      • 2014-02-10
      • 2011-10-15
      • 2011-07-03
      • 2020-11-20
      • 2019-04-25
      相关资源
      最近更新 更多