[英]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: 您有两个不太烦人的选择:
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. 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.