python - 如何有条件地将值分配给张量[损失函数的掩蔽]?

标签 python tensorflow machine-learning loss loss-function

我想创建一个忽略标签值为 0 的值(=> 像素)的 L2 损失函数。张量 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)

我当前的代码产生 TypeError: 'Tensor' object does not support item assignment(在第二行)。执行此操作的 tensorflow 方式是什么?我还尝试使用 tf.reduce_sum(labels_mask) 将损失归一化,我希望它能像这样工作。

最佳答案

这是一个如何应用 bool 索引并有条件地为变量赋值的示例:

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))

输出:

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

关于python - 如何有条件地将值分配给张量[损失函数的掩蔽]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48510741/

相关文章:

tensorflow - 如何将 std::vector<float> 转换为张量而无需在 C++ 中的 tensorflow 中复制?

python - 如何在 Tensorflow 多 GPU 案例中使用 feed_dict

machine-learning - Keras、Lasagne、Block 和 Theano 之间的关系?

python - 为什么我的 python 多进程代码运行速度很慢?

python - if/else 语句与字典

python - 如何在导入 pytest conftest.py 之前设置配置?

machine-learning - 使用标记+预测数据重新训练生产模型?

Python 子进程 AttributeError

tensorflow - 在具有多个 Keras 模型的 TF2 自定义训练循环中应用梯度的正确方法

python - 如何解读 H2ORF 对回归任务的预测?