python - 如何在 Tensorflow 中用掩码减去两个张量?

标签 python tensorflow

我正在实现具有自定义损失的 YOLO 网络。

假设有两个张量,GT 和 PD(ground truth 和 predicts)。它们都是 4x4 的 2 dims 矩阵。

假设 GT 是:

0,0,0,0
0,1,0,0
0,0,1,0
0,0,0,0

PD 具有与一些随机数相同的大小。

这里我需要单独计算均方误差。
在 GT 中用 1 计算 MSE,在 GT 中分别用 0 计算 MSE。
我更喜欢使用掩码来覆盖不相关的元素,因此只计算相关元素的计算。我已经在 numpy 中实现了这一点,但不知道如何使用 tf(v1.14) 实现这一点

import numpy as np
import numpy.ma as ma
conf = y_true[...,0]
conf = np.expand_dims(conf,-1)

conf_pred = y_pred[...,0]
conf_pred = np.expand_dims(conf_pred,-1)

noobj_conf = ma.masked_equal(conf,1)   #cover grid with objects
obj_conf = ma.masked_equal(conf,0)     #cover grid without objects

loss_obj = np.sum(np.square(obj_conf - conf_pred))
loss_noobj = np.sum(np.square(noobj_conf - conf_pred))

关于如何在 tensorflow 中实现它有什么建议吗?

最佳答案

如果我没理解错的话,您想分别计算 0 和 1 的均方误差。

您可以执行以下操作:

y_true = tf.constant([[0,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0]], dtype=tf.float32)
y_pred = tf.random.uniform([4, 4], minval=0, maxval=1)

# find indices where 0 is present in y_true
indices0 = tf.where(tf.equal(y_true, tf.zeros([1.]))) 
# find indices where 1 is present in y_true
indices1 = tf.where(tf.equal(y_true, tf.ones([1.]))) 

# find all values in y_pred which are present at indices0
y_pred_indices0 = tf.gather_nd(y_pred, indices0)
# find all values in y_pred which are present at indices1
y_pred_indices1 = tf.gather_nd(y_pred, indices1)

# mse loss calculations 
mse0 = tf.losses.mean_squared_error(labels=tf.gather_nd(y_true, indices0), predictions=y_pred_indices0)
mse1 = tf.losses.mean_squared_error(labels=tf.gather_nd(y_true, indices1), predictions=y_pred_indices1)

# mse0 = tf.reduce_sum(tf.squared_difference(tf.gather_nd(y_true, indices0), y_pred_indices0))
# mse1 = tf.reduce_sum(tf.squared_difference(tf.gather_nd(y_true, indices1), y_pred_indices1))

with tf.Session() as sess:
    y_, loss0, loss1 = sess.run([y_pred, mse0, mse1])
    print(y_)
    print(loss0, loss1)

输出:

[[0.12770343 0.43467927 0.9362457  0.09105921]
 [0.46243036 0.8838414  0.92655015 0.9347118 ]
 [0.14018488 0.14527774 0.8395766  0.14391887]
 [0.1209656  0.7793218  0.70543754 0.749542  ]]
0.341359 0.019614244

关于python - 如何在 Tensorflow 中用掩码减去两个张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57240208/

相关文章:

python - 将透明视频叠加到摄像机供稿OpenCV

python - FASTAPI测试数据库不创建数据库

Python 替代 fscanf C 代码

python - Django : how to define a unique slug for an abstract model and its children?

c++ - C++ 中的仅限 gRPC 的 Tensorflow 服务客户端

python - TensorFlow 从源错误 ValueError : invalid literal for int() with base 10: '' during cuda path configuration? 构建

python - 列表、For 循环、范围、索引

TensorFlow - "TypeError: Fetch Argument None"

python - mxnet 和 tensorflow 中错误的 gpu 顺序

python - Tensorflow 将训练数据分成批处理