Tensorflow 自定义损耗函数和内置损耗函数之间的输出不匹配
我试图实现二进制交叉熵损失,而不是使用keras函数。这是我的密码:Tensorflow 自定义损耗函数和内置损耗函数之间的输出不匹配,tensorflow,keras,Tensorflow,Keras,我试图实现二进制交叉熵损失,而不是使用keras函数。这是我的密码: def softmax_fn(val): return tf.math.exp(val) / tf.math.reduce_sum(tf.math.exp(val)) def bce_fn(y_true, y_pred): y_pred_softmax = softmax_fn(y_pred) bce_loss = tf.cast(y_true, tf.float32) * tf.math.log(y_pred_
def softmax_fn(val):
return tf.math.exp(val) / tf.math.reduce_sum(tf.math.exp(val))
def bce_fn(y_true, y_pred):
y_pred_softmax = softmax_fn(y_pred)
bce_loss = tf.cast(y_true, tf.float32) * tf.math.log(y_pred_softmax) + (1.0 - tf.cast(y_true, tf.float32)) * tf.math.log(1.0 - y_pred_softmax)
return -tf.math.reduce_mean(bce_loss)
我的问题是我的损失和keras损失之间存在输出不匹配:
# keras loss
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
y_true = [1.0, 1.0, 0.0, 0.0]
y_pred = [1.0, 0.0, 1.0, 0.0]
print(cross_entropy(y_true,y_pred)) # 0.75320446
print(bce_fn(y_true,y_pred)) # 0.903049
谁能解释一下为什么会这样
编辑
我发现了一个错误:在内置损失函数中使用from_logits=True意味着我们计算概率的方式类似于sigmoid函数,而不是softmax函数
现在,内置函数和我的自定义函数具有相同的输出。感谢Alexandru Ropotica的更新。为了社区的利益,请在回答部分发布解决方案 #BinaryCrossentropy自定义内置函数: 输出:
tf.Tensor(0.75320446, shape=(), dtype=float32)
tf.Tensor(0.75320446, shape=(), dtype=float32)
我认为二进制entropy的最后一个维度应该等于2,这是什么意思?我只有1和0,所以维度已经是2了。
def bce_fn(y_true, y_pred):
y_pred_sigmoid = tf.math.sigmoid(y_pred)
bce_loss = tf.math.reduce_mean(tf.cast(y_true, tf.float32) * -tf.math.log(y_pred_sigmoid) + (1 - tf.cast(y_true, tf.float32) ) * -tf.math.log(1 - y_pred_sigmoid))
return bce_loss
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
y_true = [1.0, 1.0, 0.0, 0.0]
y_pred = [1.0, 0.0, 1.0, 0.0]
print(cross_entropy(y_true,y_pred))
print(bce_fn(y_true,y_pred))
tf.Tensor(0.75320446, shape=(), dtype=float32)
tf.Tensor(0.75320446, shape=(), dtype=float32)