You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

loss.py 9.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import functools
  10. import numpy as np
  11. from ..core.tensor.array_method import _reduce
  12. from ..tensor import Tensor
  13. from .elemwise import abs, log
  14. from .nn import indexing_one_hot, logsigmoid, logsumexp, relu
  15. from .tensor import where
  16. __all__ = [
  17. "l1_loss",
  18. "square_loss",
  19. "cross_entropy",
  20. "binary_cross_entropy",
  21. "hinge_loss",
  22. ]
  23. def _reduce_output(loss_fn):
  24. r"""Wrapper to apply canonical reductions to loss outputs."""
  25. @functools.wraps(loss_fn)
  26. def reduced_loss_fn(*args, reduction="mean", **kwargs):
  27. loss = loss_fn(*args, **kwargs)
  28. if reduction == "none":
  29. return loss
  30. elif reduction in ("mean", "sum"):
  31. return _reduce(reduction)(loss)
  32. else:
  33. raise ValueError("{} is not a valid value for reduction".format(reduction))
  34. return reduced_loss_fn
  35. @_reduce_output
  36. def l1_loss(pred: Tensor, label: Tensor, reduction: str = "mean") -> Tensor:
  37. r"""Calculates the mean absolute error (MAE) between
  38. each element in the pred :math:`x` and label :math:`y`.
  39. The mean absolute error can be described as:
  40. .. math::
  41. \ell(x,y) = mean\left(L \right)
  42. where
  43. .. math::
  44. L = \{l_1,\dots,l_N\}, \quad
  45. l_n = \left| x_n - y_n \right|,
  46. :math:`x` and :math:`y` are tensors of arbitrary shapes with a total
  47. of :math:`N` elements each. :math:`N` is the batch size.
  48. Args:
  49. pred: predicted result from model.
  50. label: ground truth to compare.
  51. reduction: the reduction to apply to the output: 'none' | 'mean' | 'sum'. Default: 'mean'
  52. Returns:
  53. loss value.
  54. Examples:
  55. .. testcode::
  56. import numpy as np
  57. import megengine as mge
  58. import megengine.functional as F
  59. ipt = mge.tensor(np.array([3, 3, 3, 3]).astype(np.float32))
  60. tgt = mge.tensor(np.array([2, 8, 6, 1]).astype(np.float32))
  61. loss = F.nn.l1_loss(ipt, tgt)
  62. print(loss.numpy())
  63. Outputs:
  64. .. testoutput::
  65. 2.75
  66. """
  67. diff = pred - label
  68. return abs(diff)
  69. @_reduce_output
  70. def square_loss(pred: Tensor, label: Tensor, reduction: str = "mean") -> Tensor:
  71. r"""Calculates the mean squared error (squared L2 norm) between
  72. each element in the pred :math:`x` and label :math:`y`.
  73. The mean squared error can be described as:
  74. .. math::
  75. \ell(x, y) = mean\left( L \right)
  76. where
  77. .. math::
  78. L = \{l_1,\dots,l_N\}, \quad
  79. l_n = \left( x_n - y_n \right)^2,
  80. :math:`x` and :math:`y` are tensors of arbitrary shapes with a total
  81. of :math:`N` elements each. :math:`N` is the batch size.
  82. Args:
  83. pred: predicted result from model.
  84. label: ground truth to compare.
  85. reduction: the reduction to apply to the output: 'none' | 'mean' | 'sum'. Default: 'mean'
  86. Returns:
  87. loss value.
  88. Shape:
  89. * pred: :math:`(N, *)` where :math:`*` means any number of additional
  90. dimensions.
  91. * label: :math:`(N, *)`. Same shape as ``pred``.
  92. Examples:
  93. .. testcode::
  94. import numpy as np
  95. import megengine as mge
  96. import megengine.functional as F
  97. ipt = mge.tensor(np.array([3, 3, 3, 3]).astype(np.float32))
  98. tgt = mge.tensor(np.array([2, 8, 6, 1]).astype(np.float32))
  99. loss = F.nn.square_loss(ipt, tgt)
  100. print(loss.numpy())
  101. Outputs:
  102. .. testoutput::
  103. 9.75
  104. """
  105. diff = pred - label
  106. return diff ** 2
  107. @_reduce_output
  108. def cross_entropy(
  109. pred: Tensor,
  110. label: Tensor,
  111. axis: int = 1,
  112. with_logits: bool = True,
  113. label_smooth: float = 0,
  114. reduction: str = "mean",
  115. ) -> Tensor:
  116. r"""Computes the multi-class cross entropy loss (using logits by default).
  117. By default(``with_logitis`` is True), ``pred`` is assumed to be logits,
  118. class probabilities are given by softmax.
  119. It has better numerical stability compared with sequential calls to :func:`~.softmax` and :func:`~.cross_entropy`.
  120. When using label smoothing, the label distribution is as follows:
  121. .. math:: y^{LS}_{k}=y_{k}\left(1-\alpha\right)+\alpha/K
  122. where :math:`y^{LS}` and :math:`y` are new label distribution and origin label distribution respectively.
  123. k is the index of label distribution. :math:`\alpha` is ``label_smooth`` and :math:`K` is the number of classes.
  124. Args:
  125. pred: input tensor representing the predicted probability.
  126. label: input tensor representing the classification label.
  127. axis: an axis along which softmax will be applied. Default: 1
  128. with_logits: whether to apply softmax first. Default: True
  129. label_smooth: a label smoothing of parameter that can re-distribute target distribution. Default: 0
  130. reduction: the reduction to apply to the output: 'none' | 'mean' | 'sum'. Default: 'mean'
  131. Returns:
  132. loss value.
  133. Examples:
  134. .. testcode::
  135. import numpy as np
  136. from megengine import tensor
  137. import megengine.functional as F
  138. data_shape = (1, 2)
  139. label_shape = (1, )
  140. pred = tensor(np.array([0, 0], dtype=np.float32).reshape(data_shape))
  141. label = tensor(np.ones(label_shape, dtype=np.int32))
  142. loss = F.nn.cross_entropy(pred, label)
  143. print(loss.numpy().round(decimals=4))
  144. Outputs:
  145. .. testoutput::
  146. 0.6931
  147. """
  148. n0 = pred.ndim
  149. n1 = label.ndim
  150. assert n0 == n1 + 1, (
  151. "target ndim must be one less than input ndim; input_ndim={} "
  152. "target_ndim={}".format(n0, n1)
  153. )
  154. ls = label_smooth
  155. if with_logits:
  156. logZ = logsumexp(pred, axis)
  157. primary_term = indexing_one_hot(pred, label, axis)
  158. else:
  159. logZ = 0
  160. primary_term = log(indexing_one_hot(pred, label, axis))
  161. if ls is None or type(ls) in (int, float) and ls == 0:
  162. return logZ - primary_term
  163. if not with_logits:
  164. pred = log(pred)
  165. return logZ - ls * pred.mean(axis) - (1 - ls) * primary_term
  166. @_reduce_output
  167. def binary_cross_entropy(
  168. pred: Tensor, label: Tensor, with_logits: bool = True, reduction: str = "mean",
  169. ) -> Tensor:
  170. r"""Computes the binary cross entropy loss (using logits by default).
  171. By default(``with_logitis`` is True), ``pred`` is assumed to be logits,
  172. class probabilities are given by sigmoid.
  173. Args:
  174. pred: `(N, *)`, where `*` means any number of additional dimensions.
  175. label: `(N, *)`, same shape as the input.
  176. with_logits: bool, whether to apply sigmoid first. Default: True
  177. reduction: the reduction to apply to the output: 'none' | 'mean' | 'sum'. Default: 'mean'
  178. Returns:
  179. loss value.
  180. Examples:
  181. .. testcode::
  182. import numpy as np
  183. from megengine import tensor
  184. import megengine.functional as F
  185. pred = tensor(np.array([0, 0], dtype=np.float32).reshape(1, 2))
  186. label = tensor(np.ones((1, 2), dtype=np.float32))
  187. loss = F.nn.binary_cross_entropy(pred, label)
  188. print(loss.numpy().round(decimals=4))
  189. Outputs:
  190. .. testoutput::
  191. 0.6931
  192. """
  193. if not with_logits:
  194. return -(label * log(pred) + (1 - label) * log(1 - pred))
  195. # logsigmoid(pred) and logsigmoid(-pred) has common sub-expression
  196. # hopefully the backend would optimize this
  197. return -(label * logsigmoid(pred) + (1 - label) * logsigmoid(-pred))
  198. @_reduce_output
  199. def hinge_loss(
  200. pred: Tensor, label: Tensor, norm: str = "L1", reduction: str = "mean"
  201. ) -> Tensor:
  202. r"""Caculates the hinge loss which is often used in SVM.
  203. The hinge loss can be described as:
  204. .. math:: loss(x, y) = \frac{1}{N}\sum_i\sum_j(max(0, 1 - x_{ij}*y_{ij}))
  205. Args:
  206. pred: input tensor representing the predicted probability, shape is `(N, C)`.
  207. label: input tensor representing the binary classification label, shape is `(N, C)`.
  208. norm: specify the norm to caculate the loss, should be "L1" or "L2".
  209. reduction: the reduction to apply to the output: 'none' | 'mean' | 'sum'. Default: 'mean'
  210. Returns:
  211. loss value.
  212. Examples:
  213. .. testcode::
  214. from megengine import tensor
  215. import megengine.functional as F
  216. pred = tensor([[0.5, -0.5, 0.1], [-0.6, 0.7, 0.8]], dtype="float32")
  217. label = tensor([[1, -1, -1], [-1, 1, 1]], dtype="float32")
  218. loss = F.nn.hinge_loss(pred, label)
  219. print(loss.numpy())
  220. Outputs:
  221. .. testoutput::
  222. 1.5
  223. """
  224. norm = norm.upper()
  225. assert norm in ["L1", "L2"], "norm must be L1 or L2"
  226. # Converts binary labels to -1/1 labels.
  227. loss = relu(1.0 - pred * label)
  228. if norm == "L1":
  229. return loss.sum(axis=1)
  230. else:
  231. return (loss ** 2).sum(axis=1)

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台