【问题标题】:How to perform subtraction on a single element of a tensor如何对张量的单个元素执行减法
【发布时间】:2016-02-24 10:14:12
【问题描述】:

我有一个由 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]

这可行,但看起来非常难看。没有更智能/更简单的方法吗?

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

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    tf.selecttf.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())
    

    【讨论】:

    • 您好,感谢您的快速回复!我的印象是建议尽可能避免接触控制流,是这样还是不是真的那么重要?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    相关资源
    最近更新 更多