PyTorch 示例的 BCEWithLogitsLoss 数值计算的输出

hel*_*123 1 python pytorch

当我在 PyTorch Docs 中查看 BCEWithLogitsLoss 的示例代码时。我对损失函数和公式的输出结果感到困惑。

PyTorch 示例

>>> loss = nn.BCEWithLogitsLoss()
>>> input = torch.randn(3, requires_grad=True)
>>> target = torch.empty(3).random_(2)
>>> output = loss(input, target)
>>> output.backward()

input : tensor([0.4764, -2.4063,  0.1563], requires_grad=True)
target: tensor([0., 1., 1.])
output: tensor(1.3567, grad_fn=<BinaryCrossEntropyWithLogitsBackward>)
Run Code Online (Sandbox Code Playgroud)

但根据公式可知:

在此输入图像描述

损失函数的输出应该具有形状 (3,) 而不是单个值,因为输入和输出的形状都是 (3,) 。我想输出可能是 Ln 的总和或者其他,但仍然不知道。有人可以帮我解释一下吗?

正如 @Dishin H Goyani 提醒的那样,默认减少是“平均”。我做了一个简单的测试。

>>> target_n = target.numpy()
>>> input_n  = input.detach().numpy()
>>> def sigmoid(array):return 1/(1+np.exp(-array))
>>> output_n = -1*(target_n*np.log(sigmoid(input_n))+(1-target_n)*np.log(1-sigmoid(input_n)))
output_n : array([0.95947516, 2.4926252 , 0.61806685], dtype=float32)
>>> np.mean(output_n)
1.3567224
Run Code Online (Sandbox Code Playgroud)

结果是匹配的。

如您所见,默认 Wn 为 1。

Dis*_*ani 5

由于归约参数默认值为 BCEWithLogitsLoss 中的“ mean ”。

\n\n

输出是平均值 - 输出的总和将除以输出中的元素数量。

\n\n

阅读此处的文档以获取更多详细信息:
\n参数
\n...
\n缩减 (字符串,可选) \xe2\x80\x93 指定要应用于输出的缩减:\'none\'| \'mean\'| \'sum\'

\n\n
\n

\'none\':不会应用归约,
\n \'mean\':输出的总和将除以输出中的元素数量,
\n \'sum\':输出将被求和。

\n
\n\n

注意:size_average和reduce正在被弃用,同时,指定这两个参数中的任何一个都会覆盖reduction。默认值:\'mean\'
\n...

\n