如何从tensorflow中的ops列表中随机选择和应用op?

时间:2016-02-19 01:24:11

标签: tensorflow

出于数据增加的目的,我希望对数据进行n次不同的转换,并希望为批处理中的每个图像随机选择并应用其中一个。类似的东西:

image = tf.apply_random_op(image, [op1, op2, op3])
images, label_batch = tf.train.shuffle_batch([image, label])

这可能吗?

Obs:我希望在执行会话时随机选择op。

1 个答案:

答案 0 :(得分:2)

我想我想出了一个解决方案:

def apply_random_op(tensor, ops):
  n = len(ops)
  rand_idx = tf.floor(tf.random_uniform([], 0, n, dtype=tf.float32))
  op_idx = tf.constant(0.0, dtype=tf.float32)
  chain = tf.cond(tf.equal(op_idx, rand_idx), lambda: ops[0](tensor), lambda: ops[1](tensor))
  for i in xrange(2, n):
    op_idx = tf.constant(float(i), dtype=tf.float32)
    chain = tf.cond(tf.equal(op_idx, rand_idx), lambda: ops[i](tensor), lambda: chain)
  return chain