MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / binary_cross_entropy

Function binary_cross_entropy

imperative/python/megengine/functional/loss.py:214–256  ·  view source on GitHub ↗

r"""Computes the binary cross entropy loss (using logits by default). Args: pred: `(N, *)`, where `*` means any number of additional dimensions. label: `(N, *)`, same shape as the input. with_logits: bool, whether to apply sigmoid first. Default: True reduction:

(
    pred: Tensor, label: Tensor, with_logits: bool = True, reduction: str = "mean",
)

Source from the content-addressed store, hash-verified

212
213@_reduce_output
214def binary_cross_entropy(
215 pred: Tensor, label: Tensor, with_logits: bool = True, reduction: str = "mean",
216) -> Tensor:
217 r"""Computes the binary cross entropy loss (using logits by default).
218
219 Args:
220 pred: `(N, *)`, where `*` means any number of additional dimensions.
221 label: `(N, *)`, same shape as the input.
222 with_logits: bool, whether to apply sigmoid first. Default: True
223 reduction: the reduction to apply to the output: 'none' | 'mean' | 'sum'.
224
225 Returns:
226 loss value.
227
228 Examples:
229
230 By default(``with_logitis`` is True), ``pred`` is assumed to be logits,
231 class probabilities are given by softmax.
232 It has better numerical stability compared with sequential calls to
233 :func:`~.sigmoid` and :func:`~.binary_cross_entropy`.
234
235 >>> pred = Tensor([0.9, 0.7, 0.3])
236 >>> label = Tensor([1., 1., 1.])
237 >>> F.nn.binary_cross_entropy(pred, label)
238 Tensor(0.4328984, device=xpux:0)
239 >>> F.nn.binary_cross_entropy(pred, label, reduction="none")
240 Tensor([0.3412 0.4032 0.5544], device=xpux:0)
241
242 If the ``pred`` value has been probabilities, set ``with_logits`` to False:
243
244 >>> pred = Tensor([0.9, 0.7, 0.3])
245 >>> label = Tensor([1., 1., 1.])
246 >>> F.nn.binary_cross_entropy(pred, label, with_logits=False)
247 Tensor(0.5553361, device=xpux:0)
248 >>> F.nn.binary_cross_entropy(pred, label, with_logits=False, reduction="none")
249 Tensor([0.1054 0.3567 1.204 ], device=xpux:0)
250
251 """
252 if not with_logits:
253 return -(label * log(pred) + (1 - label) * log(1 - pred))
254 # logsigmoid(pred) and logsigmoid(-pred) has common sub-expression
255 # hopefully the backend would optimize this
256 return -(label * logsigmoid(pred) + (1 - label) * logsigmoid(-pred))
257
258
259@_reduce_output

Callers

nothing calls this directly

Calls 2

logFunction · 0.70
logsigmoidFunction · 0.70

Tested by

no test coverage detected