如何对张量的单个元素执行减法

How to perform subtraction on a single element of a tensor

我有一个由 4 个浮点数组成的张量,称为 label

如何以 50% 的几率执行 x[0] = 1 - x[0]

现在我有:

label = tf.constant([0.35, 0.5, 0.17, 0.14]) # just an example
uniform_random = tf.random_uniform([], 0, 1.0)

# Create a tensor with [1.0, 0.0, 0.0, 0.0] if uniform_random > 50%
# else it's only zeroes
inv = tf.pack([tf.round(uniform_random), 0.0, 0.0, 0.0])

label = tf.sub(inv, label)
label = tf.abs(label) # need abs because it inverted the other elements
# output will be either [0.35, 0.5, 0.17, 0.14] or [0.65, 0.5, 0.17, 0.14]

有效,但看起来非常丑陋。没有 smarter/simpler 的方法吗?

相关问题:如何将特定操作(例如 sqrt)仅应用于两个元素?我猜我必须删除这两个元素,执行操作然后将它们连接回原始向量?

tf.select and tf.cond 在必须有条件地对张量元素执行计算的情况下派上用场。对于您的示例,以下内容将起作用:

label = tf.constant([0.35, 0.5, 0.17, 0.14])
inv = tf.pack([1.0, 0.0, 0.0, 0.0])
mask = tf.pack([1.0, -1.0, -1.0, -1.0])
output = tf.cond(tf.random_uniform([], 0, 1.0) > 0.5,
                 lambda: label,
                 lambda: (inv - label) * mask)
with tf.Session(''):
  print(output.eval())