Sci*_*tas 5 python machine-learning loss tensorflow loss-function
我想创建一个 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)
Run Code Online (Sandbox Code Playgroud)
我当前的代码屈服于TypeError: 'Tensor' object does not support item assignment
(在第二行)。什么是张量流方式来做到这一点?我还尝试将损失归一化为tf.reduce_sum(labels_mask)
,我希望它像这样工作。
以下是如何应用布尔索引并有条件地将值赋给变量的示例:
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))
Run Code Online (Sandbox Code Playgroud)
输出:
[ 0, 0, 1500, 1500, 1, 1500, 1500, 0]
Run Code Online (Sandbox Code Playgroud)
如果你想这样写,就必须使用Tensorflow的scatter
方法进行赋值。不幸的是,tensorflow 也不真正支持布尔索引(新的boolean_select
使之成为可能,但很烦人)。写起来会很棘手,读起来也很困难。
您有两个不那么烦人的选择:
labels_mask > 0
布尔掩码并使用 Tensorflow 最近的boolean_mask函数。也许这是更张量流的方式,因为它调用任意特定的函数。labels_mask > 0
到浮动:tf.cast(labels_mask > 0, tf.float32)
. 然后,您可以在代码的最后一行中按照您想要的方式使用它。 归档时间: |
|
查看次数: |
3611 次 |
最近记录: |