【发布时间】:2021-07-13 05:50:38
【问题描述】:
在 Tensorflow 2.4.1 中的自定义损失函数中。和 Python 3.7
y_pred 张量的形状为 (batch, 21,21,3) 其中 3 是模型中的类数
y_true 是一个整数,表示模型应该分类的正确类别。
为了进行计算,创建了一个形状为 y_pred 的 zeros 张量,名称为 y_true_array
应该有比以下解决方法更简单的方法:
y_true_array= tf.zeros_like(y_pred, dtype=tf.float32, name="loss_tru_array")
one_class_shape = y_pred.shape[:-1] + [1]
ones =tf.ones(one_class_shape, dtype=tf.float32, name="loss_ones")
zeros = tf.zeros(one_class_shape, dtype=tf.float32, name="loss_ones")
if (y_true == 0):
y_true_array = tf.concat([ones, zeros, zeros], axis=-1)
elif (y_true == 1):
y_true_array = tf.concat([zeros, ones, zeros], axis=-1)
elif (y_true == 2):
y_true_array = tf.concat([zeros, zeros, ones], axis=-1)
例如 对于大小为 (3, 2, 3) 的 y_pred 数组。第二维中的 2 是特征尺寸。如果 y_true = 1,y_true_array 应该是
[ [[0, 1, 0],[0,1,0]] ,
[[0, 1, 0],[0, 1, 0]] ,
[[0, 1, 0],[0,1,0]] ]
【问题讨论】:
标签: python tensorflow loss-function