为什么我自己写表达式却得不到和tensorflow的方法一样的结果?

Why don't I get the same result as with tensorflow's method when I write my own expression?

我正在学习逻辑回归,我想计算通过梯度下降最小化交叉熵损失函数的值是多少,但是当我使用 tensorflow 的 sigmoid_cross_entropy_with_logits 函数时,我得到了不同的结果我通过自己的表达得到了什么。

这是一个例子:

import numpy as np
import tensorflow as tf

pred = np.array([[0.2],[0.3],[0.4]])
test_y = np.array([[0.5],[0.6],[0.7]])
print(tf.nn.sigmoid_cross_entropy_with_logits(logits = pred, labels = test_y))
print(-test_y * tf.math.log(pred) - (1-test_y) * tf.math.log(1-pred))

输出:

tf.Tensor(
[[0.69813887]
 [0.67435524]
 [0.63301525]], shape=(3, 1), dtype=float64)
tf.Tensor(
[[0.91629073]
 [0.86505366]
 [0.7946512 ]], shape=(3, 1), dtype=float64)

谁能给我解释一下这是怎么回事?我查看了tensorflow文档关于它们的功能,看起来它应该和我的表达式完全一样。

在计算交叉熵损失之前,您忘记了预测的 S 形 pred

-test_y * tf.math.log(tf.math.sigmoid(pred)) - (1-test_y) * tf.math.log(1-tf.math.sigmoid(pred))
tf.Tensor(
[[0.69813887]
 [0.67435524]
 [0.63301525]], shape=(3, 1), dtype=float64)