简体   繁体   English

如何有条件地将值分配给张量[蒙版损失函数]?

[英]How to conditionally assign values to tensor [masking for loss function]?

I want to create a L2 loss function that ignores values (=> pixels) where the label has the value 0. The tensor batch[1] contains the labels while output is a tensor for the net output, both have a shape of (None,300,300,1) . 我想创建一个L2损失函数,忽略标签值为0的值(=>像素)。张量batch[1]包含标签,而output是净输出的张量,两者的形状均为(None,300,300,1)

labels_mask = tf.identity(batch[1])
labels_mask[labels_mask > 0] = 1
loss = tf.reduce_sum(tf.square((output-batch[1])*labels_mask))/tf.reduce_sum(labels_mask)

My current code yields to TypeError: 'Tensor' object does not support item assignment (on the second line). 我当前的代码TypeError: 'Tensor' object does not support item assignment (在第二行)。 What's the tensorflow-way to do this? 这样做的张量流是什么? I also tried to normalize the loss with tf.reduce_sum(labels_mask) , which I hope works like this. 我还尝试使用tf.reduce_sum(labels_mask)规范化损失,我希望这样工作。

If you wanted to write it that way, you would have to use Tensorflow's scatter method for assignment. 如果您想以这种方式编写代码,则必须使用Tensorflow的scatter方法进行分配。 Unfortunately, tensorflow doesn't really support boolean indexing either (the new boolean_select makes it possible, but annoying). 不幸的是,tensorflow也不真正支持布尔索引(新的boolean_select使之成为可能,但很烦人)。 It would be tricky to write and difficult to read. 编写起来很棘手,很难阅读。

You have two options that are less annoying: 您有两个不太烦人的选择:

  1. Use labels_mask > 0 as a boolean mask and use Tensorflow's recent boolean_mask function. 使用labels_mask > 0作为布尔掩码,并使用Tensorflow的最新boolean_mask函数。 Maybe this is the more tensorflow way, because it invokes arbitrarily specific functions. 也许这是更张量流的方式,因为它调用任意特定的函数。
  2. Cast labels_mask > 0 to float: tf.cast(labels_mask > 0, tf.float32) . labels_mask > 0强制labels_mask > 0为float: tf.cast(labels_mask > 0, tf.float32) Then, you can use it the way you wanted to in the final line of your code. 然后,您可以在代码的最后一行中以所需的方式使用它。

Here is an example how to apply boolean indexing and conditionally assign values to Variable: 这是一个示例,该示例如何应用布尔索引并有条件地将值分配给Variable:

a = tf.Variable(initial_value=[0, 0, 4, 6, 1, 2, 4, 0])
mask = tf.greater_equal(a, 2)  # [False False  True  True False  True  True False]
indexes = tf.where(mask)  # [[2] [3] [5] [6]], shape=(4, 1)
b = tf.scatter_update(a, mask, tf.constant(1500))

output: 输出:

[   0,    0, 1500, 1500,    1, 1500, 1500,    0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM