loss.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  1. import warnings
  2. from .distance import PairwiseDistance
  3. from .module import Module
  4. from .. import functional as F
  5. from .. import _reduction as _Reduction
  6. from torch import Tensor
  7. from typing import Callable, Optional
  8. class _Loss(Module):
  9. reduction: str
  10. def __init__(self, size_average=None, reduce=None, reduction: str = 'mean') -> None:
  11. super(_Loss, self).__init__()
  12. if size_average is not None or reduce is not None:
  13. self.reduction: str = _Reduction.legacy_get_string(size_average, reduce)
  14. else:
  15. self.reduction = reduction
  16. class _WeightedLoss(_Loss):
  17. def __init__(self, weight: Optional[Tensor] = None, size_average=None, reduce=None, reduction: str = 'mean') -> None:
  18. super(_WeightedLoss, self).__init__(size_average, reduce, reduction)
  19. self.register_buffer('weight', weight)
  20. self.weight: Optional[Tensor]
  21. class L1Loss(_Loss):
  22. r"""Creates a criterion that measures the mean absolute error (MAE) between each element in
  23. the input :math:`x` and target :math:`y`.
  24. The unreduced (i.e. with :attr:`reduction` set to ``'none'``) loss can be described as:
  25. .. math::
  26. \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
  27. l_n = \left| x_n - y_n \right|,
  28. where :math:`N` is the batch size. If :attr:`reduction` is not ``'none'``
  29. (default ``'mean'``), then:
  30. .. math::
  31. \ell(x, y) =
  32. \begin{cases}
  33. \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\
  34. \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.}
  35. \end{cases}
  36. :math:`x` and :math:`y` are tensors of arbitrary shapes with a total
  37. of :math:`n` elements each.
  38. The sum operation still operates over all the elements, and divides by :math:`n`.
  39. The division by :math:`n` can be avoided if one sets ``reduction = 'sum'``.
  40. Supports real-valued and complex-valued inputs.
  41. Args:
  42. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  43. the losses are averaged over each loss element in the batch. Note that for
  44. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  45. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  46. when :attr:`reduce` is ``False``. Default: ``True``
  47. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  48. losses are averaged or summed over observations for each minibatch depending
  49. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  50. batch element instead and ignores :attr:`size_average`. Default: ``True``
  51. reduction (string, optional): Specifies the reduction to apply to the output:
  52. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  53. ``'mean'``: the sum of the output will be divided by the number of
  54. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  55. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  56. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  57. Shape:
  58. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  59. - Target: :math:`(*)`, same shape as the input.
  60. - Output: scalar. If :attr:`reduction` is ``'none'``, then
  61. :math:`(*)`, same shape as the input.
  62. Examples::
  63. >>> loss = nn.L1Loss()
  64. >>> input = torch.randn(3, 5, requires_grad=True)
  65. >>> target = torch.randn(3, 5)
  66. >>> output = loss(input, target)
  67. >>> output.backward()
  68. """
  69. __constants__ = ['reduction']
  70. def __init__(self, size_average=None, reduce=None, reduction: str = 'mean') -> None:
  71. super(L1Loss, self).__init__(size_average, reduce, reduction)
  72. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  73. return F.l1_loss(input, target, reduction=self.reduction)
  74. class NLLLoss(_WeightedLoss):
  75. r"""The negative log likelihood loss. It is useful to train a classification
  76. problem with `C` classes.
  77. If provided, the optional argument :attr:`weight` should be a 1D Tensor assigning
  78. weight to each of the classes. This is particularly useful when you have an
  79. unbalanced training set.
  80. The `input` given through a forward call is expected to contain
  81. log-probabilities of each class. `input` has to be a Tensor of size either
  82. :math:`(minibatch, C)` or :math:`(minibatch, C, d_1, d_2, ..., d_K)`
  83. with :math:`K \geq 1` for the `K`-dimensional case. The latter is useful for
  84. higher dimension inputs, such as computing NLL loss per-pixel for 2D images.
  85. Obtaining log-probabilities in a neural network is easily achieved by
  86. adding a `LogSoftmax` layer in the last layer of your network.
  87. You may use `CrossEntropyLoss` instead, if you prefer not to add an extra
  88. layer.
  89. The `target` that this loss expects should be a class index in the range :math:`[0, C-1]`
  90. where `C = number of classes`; if `ignore_index` is specified, this loss also accepts
  91. this class index (this index may not necessarily be in the class range).
  92. The unreduced (i.e. with :attr:`reduction` set to ``'none'``) loss can be described as:
  93. .. math::
  94. \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
  95. l_n = - w_{y_n} x_{n,y_n}, \quad
  96. w_{c} = \text{weight}[c] \cdot \mathbb{1}\{c \not= \text{ignore\_index}\},
  97. where :math:`x` is the input, :math:`y` is the target, :math:`w` is the weight, and
  98. :math:`N` is the batch size. If :attr:`reduction` is not ``'none'``
  99. (default ``'mean'``), then
  100. .. math::
  101. \ell(x, y) = \begin{cases}
  102. \sum_{n=1}^N \frac{1}{\sum_{n=1}^N w_{y_n}} l_n, &
  103. \text{if reduction} = \text{`mean';}\\
  104. \sum_{n=1}^N l_n, &
  105. \text{if reduction} = \text{`sum'.}
  106. \end{cases}
  107. Args:
  108. weight (Tensor, optional): a manual rescaling weight given to each
  109. class. If given, it has to be a Tensor of size `C`. Otherwise, it is
  110. treated as if having all ones.
  111. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  112. the losses are averaged over each loss element in the batch. Note that for
  113. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  114. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  115. when :attr:`reduce` is ``False``. Default: ``None``
  116. ignore_index (int, optional): Specifies a target value that is ignored
  117. and does not contribute to the input gradient. When
  118. :attr:`size_average` is ``True``, the loss is averaged over
  119. non-ignored targets.
  120. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  121. losses are averaged or summed over observations for each minibatch depending
  122. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  123. batch element instead and ignores :attr:`size_average`. Default: ``None``
  124. reduction (string, optional): Specifies the reduction to apply to the output:
  125. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will
  126. be applied, ``'mean'``: the weighted mean of the output is taken,
  127. ``'sum'``: the output will be summed. Note: :attr:`size_average`
  128. and :attr:`reduce` are in the process of being deprecated, and in
  129. the meantime, specifying either of those two args will override
  130. :attr:`reduction`. Default: ``'mean'``
  131. Shape:
  132. - Input: :math:`(N, C)` or :math:`(C)`, where `C = number of classes`, or
  133. :math:`(N, C, d_1, d_2, ..., d_K)` with :math:`K \geq 1`
  134. in the case of `K`-dimensional loss.
  135. - Target: :math:`(N)` or :math:`()`, where each value is
  136. :math:`0 \leq \text{targets}[i] \leq C-1`, or
  137. :math:`(N, d_1, d_2, ..., d_K)` with :math:`K \geq 1` in the case of
  138. K-dimensional loss.
  139. - Output: If :attr:`reduction` is ``'none'``, shape :math:`(N)` or
  140. :math:`(N, d_1, d_2, ..., d_K)` with :math:`K \geq 1` in the case of K-dimensional loss.
  141. Otherwise, scalar.
  142. Examples::
  143. >>> m = nn.LogSoftmax(dim=1)
  144. >>> loss = nn.NLLLoss()
  145. >>> # input is of size N x C = 3 x 5
  146. >>> input = torch.randn(3, 5, requires_grad=True)
  147. >>> # each element in target has to have 0 <= value < C
  148. >>> target = torch.tensor([1, 0, 4])
  149. >>> output = loss(m(input), target)
  150. >>> output.backward()
  151. >>>
  152. >>>
  153. >>> # 2D loss example (used, for example, with image inputs)
  154. >>> N, C = 5, 4
  155. >>> loss = nn.NLLLoss()
  156. >>> # input is of size N x C x height x width
  157. >>> data = torch.randn(N, 16, 10, 10)
  158. >>> conv = nn.Conv2d(16, C, (3, 3))
  159. >>> m = nn.LogSoftmax(dim=1)
  160. >>> # each element in target has to have 0 <= value < C
  161. >>> target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
  162. >>> output = loss(m(conv(data)), target)
  163. >>> output.backward()
  164. """
  165. __constants__ = ['ignore_index', 'reduction']
  166. ignore_index: int
  167. def __init__(self, weight: Optional[Tensor] = None, size_average=None, ignore_index: int = -100,
  168. reduce=None, reduction: str = 'mean') -> None:
  169. super(NLLLoss, self).__init__(weight, size_average, reduce, reduction)
  170. self.ignore_index = ignore_index
  171. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  172. return F.nll_loss(input, target, weight=self.weight, ignore_index=self.ignore_index, reduction=self.reduction)
  173. class NLLLoss2d(NLLLoss):
  174. def __init__(self, weight: Optional[Tensor] = None, size_average=None, ignore_index: int = -100,
  175. reduce=None, reduction: str = 'mean') -> None:
  176. warnings.warn("NLLLoss2d has been deprecated. "
  177. "Please use NLLLoss instead as a drop-in replacement and see "
  178. "https://pytorch.org/docs/master/nn.html#torch.nn.NLLLoss for more details.")
  179. super(NLLLoss2d, self).__init__(weight, size_average, ignore_index, reduce, reduction)
  180. class PoissonNLLLoss(_Loss):
  181. r"""Negative log likelihood loss with Poisson distribution of target.
  182. The loss can be described as:
  183. .. math::
  184. \text{target} \sim \mathrm{Poisson}(\text{input})
  185. \text{loss}(\text{input}, \text{target}) = \text{input} - \text{target} * \log(\text{input})
  186. + \log(\text{target!})
  187. The last term can be omitted or approximated with Stirling formula. The
  188. approximation is used for target values more than 1. For targets less or
  189. equal to 1 zeros are added to the loss.
  190. Args:
  191. log_input (bool, optional): if ``True`` the loss is computed as
  192. :math:`\exp(\text{input}) - \text{target}*\text{input}`, if ``False`` the loss is
  193. :math:`\text{input} - \text{target}*\log(\text{input}+\text{eps})`.
  194. full (bool, optional): whether to compute full loss, i. e. to add the
  195. Stirling approximation term
  196. .. math::
  197. \text{target}*\log(\text{target}) - \text{target} + 0.5 * \log(2\pi\text{target}).
  198. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  199. the losses are averaged over each loss element in the batch. Note that for
  200. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  201. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  202. when :attr:`reduce` is ``False``. Default: ``True``
  203. eps (float, optional): Small value to avoid evaluation of :math:`\log(0)` when
  204. :attr:`log_input = False`. Default: 1e-8
  205. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  206. losses are averaged or summed over observations for each minibatch depending
  207. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  208. batch element instead and ignores :attr:`size_average`. Default: ``True``
  209. reduction (string, optional): Specifies the reduction to apply to the output:
  210. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  211. ``'mean'``: the sum of the output will be divided by the number of
  212. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  213. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  214. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  215. Examples::
  216. >>> loss = nn.PoissonNLLLoss()
  217. >>> log_input = torch.randn(5, 2, requires_grad=True)
  218. >>> target = torch.randn(5, 2)
  219. >>> output = loss(log_input, target)
  220. >>> output.backward()
  221. Shape:
  222. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  223. - Target: :math:`(*)`, same shape as the input.
  224. - Output: scalar by default. If :attr:`reduction` is ``'none'``, then :math:`(*)`,
  225. the same shape as the input.
  226. """
  227. __constants__ = ['log_input', 'full', 'eps', 'reduction']
  228. log_input: bool
  229. full: bool
  230. eps: float
  231. def __init__(self, log_input: bool = True, full: bool = False, size_average=None,
  232. eps: float = 1e-8, reduce=None, reduction: str = 'mean') -> None:
  233. super(PoissonNLLLoss, self).__init__(size_average, reduce, reduction)
  234. self.log_input = log_input
  235. self.full = full
  236. self.eps = eps
  237. def forward(self, log_input: Tensor, target: Tensor) -> Tensor:
  238. return F.poisson_nll_loss(log_input, target, log_input=self.log_input, full=self.full,
  239. eps=self.eps, reduction=self.reduction)
  240. class GaussianNLLLoss(_Loss):
  241. r"""Gaussian negative log likelihood loss.
  242. The targets are treated as samples from Gaussian distributions with
  243. expectations and variances predicted by the neural network. For a
  244. ``target`` tensor modelled as having Gaussian distribution with a tensor
  245. of expectations ``input`` and a tensor of positive variances ``var`` the loss is:
  246. .. math::
  247. \text{loss} = \frac{1}{2}\left(\log\left(\text{max}\left(\text{var},
  248. \ \text{eps}\right)\right) + \frac{\left(\text{input} - \text{target}\right)^2}
  249. {\text{max}\left(\text{var}, \ \text{eps}\right)}\right) + \text{const.}
  250. where :attr:`eps` is used for stability. By default, the constant term of
  251. the loss function is omitted unless :attr:`full` is ``True``. If ``var`` is not the same
  252. size as ``input`` (due to a homoscedastic assumption), it must either have a final dimension
  253. of 1 or have one fewer dimension (with all other sizes being the same) for correct broadcasting.
  254. Args:
  255. full (bool, optional): include the constant term in the loss
  256. calculation. Default: ``False``.
  257. eps (float, optional): value used to clamp ``var`` (see note below), for
  258. stability. Default: 1e-6.
  259. reduction (string, optional): specifies the reduction to apply to the
  260. output:``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
  261. will be applied, ``'mean'``: the output is the average of all batch
  262. member losses, ``'sum'``: the output is the sum of all batch member
  263. losses. Default: ``'mean'``.
  264. Shape:
  265. - Input: :math:`(N, *)` or :math:`(*)` where :math:`*` means any number of additional
  266. dimensions
  267. - Target: :math:`(N, *)` or :math:`(*)`, same shape as the input, or same shape as the input
  268. but with one dimension equal to 1 (to allow for broadcasting)
  269. - Var: :math:`(N, *)` or :math:`(*)`, same shape as the input, or same shape as the input but
  270. with one dimension equal to 1, or same shape as the input but with one fewer
  271. dimension (to allow for broadcasting)
  272. - Output: scalar if :attr:`reduction` is ``'mean'`` (default) or
  273. ``'sum'``. If :attr:`reduction` is ``'none'``, then :math:`(N, *)`, same
  274. shape as the input
  275. Examples::
  276. >>> loss = nn.GaussianNLLLoss()
  277. >>> input = torch.randn(5, 2, requires_grad=True)
  278. >>> target = torch.randn(5, 2)
  279. >>> var = torch.ones(5, 2, requires_grad=True) #heteroscedastic
  280. >>> output = loss(input, target, var)
  281. >>> output.backward()
  282. >>> loss = nn.GaussianNLLLoss()
  283. >>> input = torch.randn(5, 2, requires_grad=True)
  284. >>> target = torch.randn(5, 2)
  285. >>> var = torch.ones(5, 1, requires_grad=True) #homoscedastic
  286. >>> output = loss(input, target, var)
  287. >>> output.backward()
  288. Note:
  289. The clamping of ``var`` is ignored with respect to autograd, and so the
  290. gradients are unaffected by it.
  291. Reference:
  292. Nix, D. A. and Weigend, A. S., "Estimating the mean and variance of the
  293. target probability distribution", Proceedings of 1994 IEEE International
  294. Conference on Neural Networks (ICNN'94), Orlando, FL, USA, 1994, pp. 55-60
  295. vol.1, doi: 10.1109/ICNN.1994.374138.
  296. """
  297. __constants__ = ['full', 'eps', 'reduction']
  298. full: bool
  299. eps: float
  300. def __init__(self, *, full: bool = False, eps: float = 1e-6, reduction: str = 'mean') -> None:
  301. super(GaussianNLLLoss, self).__init__(None, None, reduction)
  302. self.full = full
  303. self.eps = eps
  304. def forward(self, input: Tensor, target: Tensor, var: Tensor) -> Tensor:
  305. return F.gaussian_nll_loss(input, target, var, full=self.full, eps=self.eps, reduction=self.reduction)
  306. class KLDivLoss(_Loss):
  307. r"""The Kullback-Leibler divergence loss.
  308. For tensors of the same shape :math:`y_{\text{pred}},\ y_{\text{true}}`,
  309. where :math:`y_{\text{pred}}` is the :attr:`input` and :math:`y_{\text{true}}` is the
  310. :attr:`target`, we define the **pointwise KL-divergence** as
  311. .. math::
  312. L(y_{\text{pred}},\ y_{\text{true}})
  313. = y_{\text{true}} \cdot \log \frac{y_{\text{true}}}{y_{\text{pred}}}
  314. = y_{\text{true}} \cdot (\log y_{\text{true}} - \log y_{\text{pred}})
  315. To avoid underflow issues when computing this quantity, this loss expects the argument
  316. :attr:`input` in the log-space. The argument :attr:`target` may also be provided in the
  317. log-space if :attr:`log_target`\ `= True`.
  318. To summarise, this function is roughly equivalent to computing
  319. .. code-block:: python
  320. if not log_target: # default
  321. loss_pointwise = target * (target.log() - input)
  322. else:
  323. loss_pointwise = target.exp() * (target - input)
  324. and then reducing this result depending on the argument :attr:`reduction` as
  325. .. code-block:: python
  326. if reduction == "mean": # default
  327. loss = loss_pointwise.mean()
  328. elif reduction == "batchmean": # mathematically correct
  329. loss = loss_pointwise.sum() / input.size(0)
  330. elif reduction == "sum":
  331. loss = loss_pointwise.sum()
  332. else: # reduction == "none"
  333. loss = loss_pointwise
  334. .. note::
  335. As all the other losses in PyTorch, this function expects the first argument,
  336. :attr:`input`, to be the output of the model (e.g. the neural network)
  337. and the second, :attr:`target`, to be the observations in the dataset.
  338. This differs from the standard mathematical notation :math:`KL(P\ ||\ Q)` where
  339. :math:`P` denotes the distribution of the observations and :math:`Q` denotes the model.
  340. .. warning::
  341. :attr:`reduction`\ `= "mean"` doesn't return the true KL divergence value, please use
  342. :attr:`reduction`\ `= "batchmean"` which aligns with the mathematical definition.
  343. In a future release, `"mean"` will be changed to be the same as `"batchmean"`.
  344. Args:
  345. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  346. the losses are averaged over each loss element in the batch. Note that for
  347. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  348. is set to `False`, the losses are instead summed for each minibatch. Ignored
  349. when :attr:`reduce` is `False`. Default: `True`
  350. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  351. losses are averaged or summed over observations for each minibatch depending
  352. on :attr:`size_average`. When :attr:`reduce` is `False`, returns a loss per
  353. batch element instead and ignores :attr:`size_average`. Default: `True`
  354. reduction (string, optional): Specifies the reduction to apply to the output. Default: `"mean"`
  355. log_target (bool, optional): Specifies whether `target` is the log space. Default: `False`
  356. Shape:
  357. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  358. - Target: :math:`(*)`, same shape as the input.
  359. - Output: scalar by default. If :attr:`reduction` is `'none'`, then :math:`(*)`,
  360. same shape as the input.
  361. Examples::
  362. >>> kl_loss = nn.KLDivLoss(reduction="batchmean")
  363. >>> # input should be a distribution in the log space
  364. >>> input = F.log_softmax(torch.randn(3, 5, requires_grad=True))
  365. >>> # Sample a batch of distributions. Usually this would come from the dataset
  366. >>> target = F.softmax(torch.rand(3, 5))
  367. >>> output = kl_loss(input, target)
  368. >>> kl_loss = nn.KLDivLoss(reduction="batchmean", log_target=True)
  369. >>> log_target = F.log_softmax(torch.rand(3, 5))
  370. >>> output = kl_loss(input, log_target)
  371. """
  372. __constants__ = ['reduction']
  373. def __init__(self, size_average=None, reduce=None, reduction: str = 'mean', log_target: bool = False) -> None:
  374. super(KLDivLoss, self).__init__(size_average, reduce, reduction)
  375. self.log_target = log_target
  376. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  377. return F.kl_div(input, target, reduction=self.reduction, log_target=self.log_target)
  378. class MSELoss(_Loss):
  379. r"""Creates a criterion that measures the mean squared error (squared L2 norm) between
  380. each element in the input :math:`x` and target :math:`y`.
  381. The unreduced (i.e. with :attr:`reduction` set to ``'none'``) loss can be described as:
  382. .. math::
  383. \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
  384. l_n = \left( x_n - y_n \right)^2,
  385. where :math:`N` is the batch size. If :attr:`reduction` is not ``'none'``
  386. (default ``'mean'``), then:
  387. .. math::
  388. \ell(x, y) =
  389. \begin{cases}
  390. \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\
  391. \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.}
  392. \end{cases}
  393. :math:`x` and :math:`y` are tensors of arbitrary shapes with a total
  394. of :math:`n` elements each.
  395. The mean operation still operates over all the elements, and divides by :math:`n`.
  396. The division by :math:`n` can be avoided if one sets ``reduction = 'sum'``.
  397. Args:
  398. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  399. the losses are averaged over each loss element in the batch. Note that for
  400. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  401. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  402. when :attr:`reduce` is ``False``. Default: ``True``
  403. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  404. losses are averaged or summed over observations for each minibatch depending
  405. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  406. batch element instead and ignores :attr:`size_average`. Default: ``True``
  407. reduction (string, optional): Specifies the reduction to apply to the output:
  408. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  409. ``'mean'``: the sum of the output will be divided by the number of
  410. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  411. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  412. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  413. Shape:
  414. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  415. - Target: :math:`(*)`, same shape as the input.
  416. Examples::
  417. >>> loss = nn.MSELoss()
  418. >>> input = torch.randn(3, 5, requires_grad=True)
  419. >>> target = torch.randn(3, 5)
  420. >>> output = loss(input, target)
  421. >>> output.backward()
  422. """
  423. __constants__ = ['reduction']
  424. def __init__(self, size_average=None, reduce=None, reduction: str = 'mean') -> None:
  425. super(MSELoss, self).__init__(size_average, reduce, reduction)
  426. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  427. return F.mse_loss(input, target, reduction=self.reduction)
  428. class BCELoss(_WeightedLoss):
  429. r"""Creates a criterion that measures the Binary Cross Entropy between the target and
  430. the input probabilities:
  431. The unreduced (i.e. with :attr:`reduction` set to ``'none'``) loss can be described as:
  432. .. math::
  433. \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
  434. l_n = - w_n \left[ y_n \cdot \log x_n + (1 - y_n) \cdot \log (1 - x_n) \right],
  435. where :math:`N` is the batch size. If :attr:`reduction` is not ``'none'``
  436. (default ``'mean'``), then
  437. .. math::
  438. \ell(x, y) = \begin{cases}
  439. \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\
  440. \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.}
  441. \end{cases}
  442. This is used for measuring the error of a reconstruction in for example
  443. an auto-encoder. Note that the targets :math:`y` should be numbers
  444. between 0 and 1.
  445. Notice that if :math:`x_n` is either 0 or 1, one of the log terms would be
  446. mathematically undefined in the above loss equation. PyTorch chooses to set
  447. :math:`\log (0) = -\infty`, since :math:`\lim_{x\to 0} \log (x) = -\infty`.
  448. However, an infinite term in the loss equation is not desirable for several reasons.
  449. For one, if either :math:`y_n = 0` or :math:`(1 - y_n) = 0`, then we would be
  450. multiplying 0 with infinity. Secondly, if we have an infinite loss value, then
  451. we would also have an infinite term in our gradient, since
  452. :math:`\lim_{x\to 0} \frac{d}{dx} \log (x) = \infty`.
  453. This would make BCELoss's backward method nonlinear with respect to :math:`x_n`,
  454. and using it for things like linear regression would not be straight-forward.
  455. Our solution is that BCELoss clamps its log function outputs to be greater than
  456. or equal to -100. This way, we can always have a finite loss value and a linear
  457. backward method.
  458. Args:
  459. weight (Tensor, optional): a manual rescaling weight given to the loss
  460. of each batch element. If given, has to be a Tensor of size `nbatch`.
  461. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  462. the losses are averaged over each loss element in the batch. Note that for
  463. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  464. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  465. when :attr:`reduce` is ``False``. Default: ``True``
  466. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  467. losses are averaged or summed over observations for each minibatch depending
  468. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  469. batch element instead and ignores :attr:`size_average`. Default: ``True``
  470. reduction (string, optional): Specifies the reduction to apply to the output:
  471. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  472. ``'mean'``: the sum of the output will be divided by the number of
  473. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  474. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  475. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  476. Shape:
  477. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  478. - Target: :math:`(*)`, same shape as the input.
  479. - Output: scalar. If :attr:`reduction` is ``'none'``, then :math:`(*)`, same
  480. shape as input.
  481. Examples::
  482. >>> m = nn.Sigmoid()
  483. >>> loss = nn.BCELoss()
  484. >>> input = torch.randn(3, requires_grad=True)
  485. >>> target = torch.empty(3).random_(2)
  486. >>> output = loss(m(input), target)
  487. >>> output.backward()
  488. """
  489. __constants__ = ['reduction']
  490. def __init__(self, weight: Optional[Tensor] = None, size_average=None, reduce=None, reduction: str = 'mean') -> None:
  491. super(BCELoss, self).__init__(weight, size_average, reduce, reduction)
  492. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  493. return F.binary_cross_entropy(input, target, weight=self.weight, reduction=self.reduction)
  494. class BCEWithLogitsLoss(_Loss):
  495. r"""This loss combines a `Sigmoid` layer and the `BCELoss` in one single
  496. class. This version is more numerically stable than using a plain `Sigmoid`
  497. followed by a `BCELoss` as, by combining the operations into one layer,
  498. we take advantage of the log-sum-exp trick for numerical stability.
  499. The unreduced (i.e. with :attr:`reduction` set to ``'none'``) loss can be described as:
  500. .. math::
  501. \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
  502. l_n = - w_n \left[ y_n \cdot \log \sigma(x_n)
  503. + (1 - y_n) \cdot \log (1 - \sigma(x_n)) \right],
  504. where :math:`N` is the batch size. If :attr:`reduction` is not ``'none'``
  505. (default ``'mean'``), then
  506. .. math::
  507. \ell(x, y) = \begin{cases}
  508. \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\
  509. \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.}
  510. \end{cases}
  511. This is used for measuring the error of a reconstruction in for example
  512. an auto-encoder. Note that the targets `t[i]` should be numbers
  513. between 0 and 1.
  514. It's possible to trade off recall and precision by adding weights to positive examples.
  515. In the case of multi-label classification the loss can be described as:
  516. .. math::
  517. \ell_c(x, y) = L_c = \{l_{1,c},\dots,l_{N,c}\}^\top, \quad
  518. l_{n,c} = - w_{n,c} \left[ p_c y_{n,c} \cdot \log \sigma(x_{n,c})
  519. + (1 - y_{n,c}) \cdot \log (1 - \sigma(x_{n,c})) \right],
  520. where :math:`c` is the class number (:math:`c > 1` for multi-label binary classification,
  521. :math:`c = 1` for single-label binary classification),
  522. :math:`n` is the number of the sample in the batch and
  523. :math:`p_c` is the weight of the positive answer for the class :math:`c`.
  524. :math:`p_c > 1` increases the recall, :math:`p_c < 1` increases the precision.
  525. For example, if a dataset contains 100 positive and 300 negative examples of a single class,
  526. then `pos_weight` for the class should be equal to :math:`\frac{300}{100}=3`.
  527. The loss would act as if the dataset contains :math:`3\times 100=300` positive examples.
  528. Examples::
  529. >>> target = torch.ones([10, 64], dtype=torch.float32) # 64 classes, batch size = 10
  530. >>> output = torch.full([10, 64], 1.5) # A prediction (logit)
  531. >>> pos_weight = torch.ones([64]) # All weights are equal to 1
  532. >>> criterion = torch.nn.BCEWithLogitsLoss(pos_weight=pos_weight)
  533. >>> criterion(output, target) # -log(sigmoid(1.5))
  534. tensor(0.2014)
  535. Args:
  536. weight (Tensor, optional): a manual rescaling weight given to the loss
  537. of each batch element. If given, has to be a Tensor of size `nbatch`.
  538. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  539. the losses are averaged over each loss element in the batch. Note that for
  540. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  541. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  542. when :attr:`reduce` is ``False``. Default: ``True``
  543. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  544. losses are averaged or summed over observations for each minibatch depending
  545. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  546. batch element instead and ignores :attr:`size_average`. Default: ``True``
  547. reduction (string, optional): Specifies the reduction to apply to the output:
  548. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  549. ``'mean'``: the sum of the output will be divided by the number of
  550. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  551. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  552. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  553. pos_weight (Tensor, optional): a weight of positive examples.
  554. Must be a vector with length equal to the number of classes.
  555. Shape:
  556. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  557. - Target: :math:`(*)`, same shape as the input.
  558. - Output: scalar. If :attr:`reduction` is ``'none'``, then :math:`(*)`, same
  559. shape as input.
  560. Examples::
  561. >>> loss = nn.BCEWithLogitsLoss()
  562. >>> input = torch.randn(3, requires_grad=True)
  563. >>> target = torch.empty(3).random_(2)
  564. >>> output = loss(input, target)
  565. >>> output.backward()
  566. """
  567. def __init__(self, weight: Optional[Tensor] = None, size_average=None, reduce=None, reduction: str = 'mean',
  568. pos_weight: Optional[Tensor] = None) -> None:
  569. super(BCEWithLogitsLoss, self).__init__(size_average, reduce, reduction)
  570. self.register_buffer('weight', weight)
  571. self.register_buffer('pos_weight', pos_weight)
  572. self.weight: Optional[Tensor]
  573. self.pos_weight: Optional[Tensor]
  574. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  575. return F.binary_cross_entropy_with_logits(input, target,
  576. self.weight,
  577. pos_weight=self.pos_weight,
  578. reduction=self.reduction)
  579. class HingeEmbeddingLoss(_Loss):
  580. r"""Measures the loss given an input tensor :math:`x` and a labels tensor :math:`y`
  581. (containing 1 or -1).
  582. This is usually used for measuring whether two inputs are similar or
  583. dissimilar, e.g. using the L1 pairwise distance as :math:`x`, and is typically
  584. used for learning nonlinear embeddings or semi-supervised learning.
  585. The loss function for :math:`n`-th sample in the mini-batch is
  586. .. math::
  587. l_n = \begin{cases}
  588. x_n, & \text{if}\; y_n = 1,\\
  589. \max \{0, \Delta - x_n\}, & \text{if}\; y_n = -1,
  590. \end{cases}
  591. and the total loss functions is
  592. .. math::
  593. \ell(x, y) = \begin{cases}
  594. \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\
  595. \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.}
  596. \end{cases}
  597. where :math:`L = \{l_1,\dots,l_N\}^\top`.
  598. Args:
  599. margin (float, optional): Has a default value of `1`.
  600. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  601. the losses are averaged over each loss element in the batch. Note that for
  602. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  603. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  604. when :attr:`reduce` is ``False``. Default: ``True``
  605. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  606. losses are averaged or summed over observations for each minibatch depending
  607. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  608. batch element instead and ignores :attr:`size_average`. Default: ``True``
  609. reduction (string, optional): Specifies the reduction to apply to the output:
  610. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  611. ``'mean'``: the sum of the output will be divided by the number of
  612. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  613. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  614. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  615. Shape:
  616. - Input: :math:`(*)` where :math:`*` means, any number of dimensions. The sum operation
  617. operates over all the elements.
  618. - Target: :math:`(*)`, same shape as the input
  619. - Output: scalar. If :attr:`reduction` is ``'none'``, then same shape as the input
  620. """
  621. __constants__ = ['margin', 'reduction']
  622. margin: float
  623. def __init__(self, margin: float = 1.0, size_average=None, reduce=None, reduction: str = 'mean') -> None:
  624. super(HingeEmbeddingLoss, self).__init__(size_average, reduce, reduction)
  625. self.margin = margin
  626. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  627. return F.hinge_embedding_loss(input, target, margin=self.margin, reduction=self.reduction)
  628. class MultiLabelMarginLoss(_Loss):
  629. r"""Creates a criterion that optimizes a multi-class multi-classification
  630. hinge loss (margin-based loss) between input :math:`x` (a 2D mini-batch `Tensor`)
  631. and output :math:`y` (which is a 2D `Tensor` of target class indices).
  632. For each sample in the mini-batch:
  633. .. math::
  634. \text{loss}(x, y) = \sum_{ij}\frac{\max(0, 1 - (x[y[j]] - x[i]))}{\text{x.size}(0)}
  635. where :math:`x \in \left\{0, \; \cdots , \; \text{x.size}(0) - 1\right\}`, \
  636. :math:`y \in \left\{0, \; \cdots , \; \text{y.size}(0) - 1\right\}`, \
  637. :math:`0 \leq y[j] \leq \text{x.size}(0)-1`, \
  638. and :math:`i \neq y[j]` for all :math:`i` and :math:`j`.
  639. :math:`y` and :math:`x` must have the same size.
  640. The criterion only considers a contiguous block of non-negative targets that
  641. starts at the front.
  642. This allows for different samples to have variable amounts of target classes.
  643. Args:
  644. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  645. the losses are averaged over each loss element in the batch. Note that for
  646. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  647. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  648. when :attr:`reduce` is ``False``. Default: ``True``
  649. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  650. losses are averaged or summed over observations for each minibatch depending
  651. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  652. batch element instead and ignores :attr:`size_average`. Default: ``True``
  653. reduction (string, optional): Specifies the reduction to apply to the output:
  654. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  655. ``'mean'``: the sum of the output will be divided by the number of
  656. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  657. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  658. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  659. Shape:
  660. - Input: :math:`(C)` or :math:`(N, C)` where `N` is the batch size and `C`
  661. is the number of classes.
  662. - Target: :math:`(C)` or :math:`(N, C)`, label targets padded by -1 ensuring same shape as the input.
  663. - Output: scalar. If :attr:`reduction` is ``'none'``, then :math:`(N)`.
  664. Examples::
  665. >>> loss = nn.MultiLabelMarginLoss()
  666. >>> x = torch.FloatTensor([[0.1, 0.2, 0.4, 0.8]])
  667. >>> # for target y, only consider labels 3 and 0, not after label -1
  668. >>> y = torch.LongTensor([[3, 0, -1, 1]])
  669. >>> loss(x, y)
  670. >>> # 0.25 * ((1-(0.1-0.2)) + (1-(0.1-0.4)) + (1-(0.8-0.2)) + (1-(0.8-0.4)))
  671. tensor(0.8500)
  672. """
  673. __constants__ = ['reduction']
  674. def __init__(self, size_average=None, reduce=None, reduction: str = 'mean') -> None:
  675. super(MultiLabelMarginLoss, self).__init__(size_average, reduce, reduction)
  676. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  677. return F.multilabel_margin_loss(input, target, reduction=self.reduction)
  678. class SmoothL1Loss(_Loss):
  679. r"""Creates a criterion that uses a squared term if the absolute
  680. element-wise error falls below beta and an L1 term otherwise.
  681. It is less sensitive to outliers than :class:`torch.nn.MSELoss` and in some cases
  682. prevents exploding gradients (e.g. see the paper `Fast R-CNN`_ by Ross Girshick).
  683. For a batch of size :math:`N`, the unreduced loss can be described as:
  684. .. math::
  685. \ell(x, y) = L = \{l_1, ..., l_N\}^T
  686. with
  687. .. math::
  688. l_n = \begin{cases}
  689. 0.5 (x_n - y_n)^2 / beta, & \text{if } |x_n - y_n| < beta \\
  690. |x_n - y_n| - 0.5 * beta, & \text{otherwise }
  691. \end{cases}
  692. If `reduction` is not `none`, then:
  693. .. math::
  694. \ell(x, y) =
  695. \begin{cases}
  696. \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\
  697. \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.}
  698. \end{cases}
  699. .. note::
  700. Smooth L1 loss can be seen as exactly :class:`L1Loss`, but with the :math:`|x - y| < beta`
  701. portion replaced with a quadratic function such that its slope is 1 at :math:`|x - y| = beta`.
  702. The quadratic segment smooths the L1 loss near :math:`|x - y| = 0`.
  703. .. note::
  704. Smooth L1 loss is closely related to :class:`HuberLoss`, being
  705. equivalent to :math:`huber(x, y) / beta` (note that Smooth L1's beta hyper-parameter is
  706. also known as delta for Huber). This leads to the following differences:
  707. * As beta -> 0, Smooth L1 loss converges to :class:`L1Loss`, while :class:`HuberLoss`
  708. converges to a constant 0 loss. When beta is 0, Smooth L1 loss is equivalent to L1 loss.
  709. * As beta -> :math:`+\infty`, Smooth L1 loss converges to a constant 0 loss, while
  710. :class:`HuberLoss` converges to :class:`MSELoss`.
  711. * For Smooth L1 loss, as beta varies, the L1 segment of the loss has a constant slope of 1.
  712. For :class:`HuberLoss`, the slope of the L1 segment is beta.
  713. .. _`Fast R-CNN`: https://arxiv.org/abs/1504.08083
  714. Args:
  715. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  716. the losses are averaged over each loss element in the batch. Note that for
  717. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  718. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  719. when :attr:`reduce` is ``False``. Default: ``True``
  720. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  721. losses are averaged or summed over observations for each minibatch depending
  722. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  723. batch element instead and ignores :attr:`size_average`. Default: ``True``
  724. reduction (string, optional): Specifies the reduction to apply to the output:
  725. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  726. ``'mean'``: the sum of the output will be divided by the number of
  727. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  728. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  729. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  730. beta (float, optional): Specifies the threshold at which to change between L1 and L2 loss.
  731. The value must be non-negative. Default: 1.0
  732. Shape:
  733. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  734. - Target: :math:`(*)`, same shape as the input.
  735. - Output: scalar. If :attr:`reduction` is ``'none'``, then :math:`(*)`, same shape as the input.
  736. """
  737. __constants__ = ['reduction']
  738. def __init__(self, size_average=None, reduce=None, reduction: str = 'mean', beta: float = 1.0) -> None:
  739. super(SmoothL1Loss, self).__init__(size_average, reduce, reduction)
  740. self.beta = beta
  741. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  742. return F.smooth_l1_loss(input, target, reduction=self.reduction, beta=self.beta)
  743. class HuberLoss(_Loss):
  744. r"""Creates a criterion that uses a squared term if the absolute
  745. element-wise error falls below delta and a delta-scaled L1 term otherwise.
  746. This loss combines advantages of both :class:`L1Loss` and :class:`MSELoss`; the
  747. delta-scaled L1 region makes the loss less sensitive to outliers than :class:`MSELoss`,
  748. while the L2 region provides smoothness over :class:`L1Loss` near 0. See
  749. `Huber loss <https://en.wikipedia.org/wiki/Huber_loss>`_ for more information.
  750. For a batch of size :math:`N`, the unreduced loss can be described as:
  751. .. math::
  752. \ell(x, y) = L = \{l_1, ..., l_N\}^T
  753. with
  754. .. math::
  755. l_n = \begin{cases}
  756. 0.5 (x_n - y_n)^2, & \text{if } |x_n - y_n| < delta \\
  757. delta * (|x_n - y_n| - 0.5 * delta), & \text{otherwise }
  758. \end{cases}
  759. If `reduction` is not `none`, then:
  760. .. math::
  761. \ell(x, y) =
  762. \begin{cases}
  763. \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\
  764. \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.}
  765. \end{cases}
  766. .. note::
  767. When delta is set to 1, this loss is equivalent to :class:`SmoothL1Loss`.
  768. In general, this loss differs from :class:`SmoothL1Loss` by a factor of delta (AKA beta
  769. in Smooth L1).
  770. See :class:`SmoothL1Loss` for additional discussion on the differences in behavior
  771. between the two losses.
  772. Args:
  773. reduction (string, optional): Specifies the reduction to apply to the output:
  774. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  775. ``'mean'``: the sum of the output will be divided by the number of
  776. elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``
  777. delta (float, optional): Specifies the threshold at which to change between delta-scaled L1 and L2 loss.
  778. The value must be positive. Default: 1.0
  779. Shape:
  780. - Input: :math:`(*)` where :math:`*` means any number of dimensions.
  781. - Target: :math:`(*)`, same shape as the input.
  782. - Output: scalar. If :attr:`reduction` is ``'none'``, then :math:`(*)`, same shape as the input.
  783. """
  784. __constants__ = ['reduction', 'delta']
  785. def __init__(self, reduction: str = 'mean', delta: float = 1.0) -> None:
  786. super().__init__(reduction=reduction)
  787. self.delta = delta
  788. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  789. return F.huber_loss(input, target, reduction=self.reduction, delta=self.delta)
  790. class SoftMarginLoss(_Loss):
  791. r"""Creates a criterion that optimizes a two-class classification
  792. logistic loss between input tensor :math:`x` and target tensor :math:`y`
  793. (containing 1 or -1).
  794. .. math::
  795. \text{loss}(x, y) = \sum_i \frac{\log(1 + \exp(-y[i]*x[i]))}{\text{x.nelement}()}
  796. Args:
  797. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  798. the losses are averaged over each loss element in the batch. Note that for
  799. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  800. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  801. when :attr:`reduce` is ``False``. Default: ``True``
  802. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  803. losses are averaged or summed over observations for each minibatch depending
  804. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  805. batch element instead and ignores :attr:`size_average`. Default: ``True``
  806. reduction (string, optional): Specifies the reduction to apply to the output:
  807. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  808. ``'mean'``: the sum of the output will be divided by the number of
  809. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  810. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  811. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  812. Shape:
  813. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  814. - Target: :math:`(*)`, same shape as the input.
  815. - Output: scalar. If :attr:`reduction` is ``'none'``, then :math:`(*)`, same
  816. shape as input.
  817. """
  818. __constants__ = ['reduction']
  819. def __init__(self, size_average=None, reduce=None, reduction: str = 'mean') -> None:
  820. super(SoftMarginLoss, self).__init__(size_average, reduce, reduction)
  821. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  822. return F.soft_margin_loss(input, target, reduction=self.reduction)
  823. class CrossEntropyLoss(_WeightedLoss):
  824. r"""This criterion computes the cross entropy loss between input and target.
  825. It is useful when training a classification problem with `C` classes.
  826. If provided, the optional argument :attr:`weight` should be a 1D `Tensor`
  827. assigning weight to each of the classes.
  828. This is particularly useful when you have an unbalanced training set.
  829. The `input` is expected to contain raw, unnormalized scores for each class.
  830. `input` has to be a Tensor of size :math:`(C)` for unbatched input,
  831. :math:`(minibatch, C)` or :math:`(minibatch, C, d_1, d_2, ..., d_K)` with :math:`K \geq 1` for the
  832. `K`-dimensional case. The last being useful for higher dimension inputs, such
  833. as computing cross entropy loss per-pixel for 2D images.
  834. The `target` that this criterion expects should contain either:
  835. - Class indices in the range :math:`[0, C)` where :math:`C` is the number of classes; if
  836. `ignore_index` is specified, this loss also accepts this class index (this index
  837. may not necessarily be in the class range). The unreduced (i.e. with :attr:`reduction`
  838. set to ``'none'``) loss for this case can be described as:
  839. .. math::
  840. \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
  841. l_n = - w_{y_n} \log \frac{\exp(x_{n,y_n})}{\sum_{c=1}^C \exp(x_{n,c})}
  842. \cdot \mathbb{1}\{y_n \not= \text{ignore\_index}\}
  843. where :math:`x` is the input, :math:`y` is the target, :math:`w` is the weight,
  844. :math:`C` is the number of classes, and :math:`N` spans the minibatch dimension as well as
  845. :math:`d_1, ..., d_k` for the `K`-dimensional case. If
  846. :attr:`reduction` is not ``'none'`` (default ``'mean'``), then
  847. .. math::
  848. \ell(x, y) = \begin{cases}
  849. \sum_{n=1}^N \frac{1}{\sum_{n=1}^N w_{y_n} \cdot \mathbb{1}\{y_n \not= \text{ignore\_index}\}} l_n, &
  850. \text{if reduction} = \text{`mean';}\\
  851. \sum_{n=1}^N l_n, &
  852. \text{if reduction} = \text{`sum'.}
  853. \end{cases}
  854. Note that this case is equivalent to the combination of :class:`~torch.nn.LogSoftmax` and
  855. :class:`~torch.nn.NLLLoss`.
  856. - Probabilities for each class; useful when labels beyond a single class per minibatch item
  857. are required, such as for blended labels, label smoothing, etc. The unreduced (i.e. with
  858. :attr:`reduction` set to ``'none'``) loss for this case can be described as:
  859. .. math::
  860. \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
  861. l_n = - \sum_{c=1}^C w_c \log \frac{\exp(x_{n,c})}{\sum_{i=1}^C \exp(x_{n,i})} y_{n,c}
  862. where :math:`x` is the input, :math:`y` is the target, :math:`w` is the weight,
  863. :math:`C` is the number of classes, and :math:`N` spans the minibatch dimension as well as
  864. :math:`d_1, ..., d_k` for the `K`-dimensional case. If
  865. :attr:`reduction` is not ``'none'`` (default ``'mean'``), then
  866. .. math::
  867. \ell(x, y) = \begin{cases}
  868. \frac{\sum_{n=1}^N l_n}{N}, &
  869. \text{if reduction} = \text{`mean';}\\
  870. \sum_{n=1}^N l_n, &
  871. \text{if reduction} = \text{`sum'.}
  872. \end{cases}
  873. .. note::
  874. The performance of this criterion is generally better when `target` contains class
  875. indices, as this allows for optimized computation. Consider providing `target` as
  876. class probabilities only when a single class label per minibatch item is too restrictive.
  877. Args:
  878. weight (Tensor, optional): a manual rescaling weight given to each class.
  879. If given, has to be a Tensor of size `C`
  880. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  881. the losses are averaged over each loss element in the batch. Note that for
  882. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  883. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  884. when :attr:`reduce` is ``False``. Default: ``True``
  885. ignore_index (int, optional): Specifies a target value that is ignored
  886. and does not contribute to the input gradient. When :attr:`size_average` is
  887. ``True``, the loss is averaged over non-ignored targets. Note that
  888. :attr:`ignore_index` is only applicable when the target contains class indices.
  889. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  890. losses are averaged or summed over observations for each minibatch depending
  891. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  892. batch element instead and ignores :attr:`size_average`. Default: ``True``
  893. reduction (string, optional): Specifies the reduction to apply to the output:
  894. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will
  895. be applied, ``'mean'``: the weighted mean of the output is taken,
  896. ``'sum'``: the output will be summed. Note: :attr:`size_average`
  897. and :attr:`reduce` are in the process of being deprecated, and in
  898. the meantime, specifying either of those two args will override
  899. :attr:`reduction`. Default: ``'mean'``
  900. label_smoothing (float, optional): A float in [0.0, 1.0]. Specifies the amount
  901. of smoothing when computing the loss, where 0.0 means no smoothing. The targets
  902. become a mixture of the original ground truth and a uniform distribution as described in
  903. `Rethinking the Inception Architecture for Computer Vision <https://arxiv.org/abs/1512.00567>`__. Default: :math:`0.0`.
  904. Shape:
  905. - Input: Shape :math:`(C)`, :math:`(N, C)` or :math:`(N, C, d_1, d_2, ..., d_K)` with :math:`K \geq 1`
  906. in the case of `K`-dimensional loss.
  907. - Target: If containing class indices, shape :math:`()`, :math:`(N)` or :math:`(N, d_1, d_2, ..., d_K)` with
  908. :math:`K \geq 1` in the case of K-dimensional loss where each value should be between :math:`[0, C)`.
  909. If containing class probabilities, same shape as the input and each value should be between :math:`[0, 1]`.
  910. - Output: If reduction is 'none', same shape as the target. Otherwise, scalar.
  911. where:
  912. .. math::
  913. \begin{aligned}
  914. C ={} & \text{number of classes} \\
  915. N ={} & \text{batch size} \\
  916. \end{aligned}
  917. Examples::
  918. >>> # Example of target with class indices
  919. >>> loss = nn.CrossEntropyLoss()
  920. >>> input = torch.randn(3, 5, requires_grad=True)
  921. >>> target = torch.empty(3, dtype=torch.long).random_(5)
  922. >>> output = loss(input, target)
  923. >>> output.backward()
  924. >>>
  925. >>> # Example of target with class probabilities
  926. >>> input = torch.randn(3, 5, requires_grad=True)
  927. >>> target = torch.randn(3, 5).softmax(dim=1)
  928. >>> output = loss(input, target)
  929. >>> output.backward()
  930. """
  931. __constants__ = ['ignore_index', 'reduction', 'label_smoothing']
  932. ignore_index: int
  933. label_smoothing: float
  934. def __init__(self, weight: Optional[Tensor] = None, size_average=None, ignore_index: int = -100,
  935. reduce=None, reduction: str = 'mean', label_smoothing: float = 0.0) -> None:
  936. super(CrossEntropyLoss, self).__init__(weight, size_average, reduce, reduction)
  937. self.ignore_index = ignore_index
  938. self.label_smoothing = label_smoothing
  939. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  940. return F.cross_entropy(input, target, weight=self.weight,
  941. ignore_index=self.ignore_index, reduction=self.reduction,
  942. label_smoothing=self.label_smoothing)
  943. class MultiLabelSoftMarginLoss(_WeightedLoss):
  944. r"""Creates a criterion that optimizes a multi-label one-versus-all
  945. loss based on max-entropy, between input :math:`x` and target :math:`y` of size
  946. :math:`(N, C)`.
  947. For each sample in the minibatch:
  948. .. math::
  949. loss(x, y) = - \frac{1}{C} * \sum_i y[i] * \log((1 + \exp(-x[i]))^{-1})
  950. + (1-y[i]) * \log\left(\frac{\exp(-x[i])}{(1 + \exp(-x[i]))}\right)
  951. where :math:`i \in \left\{0, \; \cdots , \; \text{x.nElement}() - 1\right\}`,
  952. :math:`y[i] \in \left\{0, \; 1\right\}`.
  953. Args:
  954. weight (Tensor, optional): a manual rescaling weight given to each
  955. class. If given, it has to be a Tensor of size `C`. Otherwise, it is
  956. treated as if having all ones.
  957. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  958. the losses are averaged over each loss element in the batch. Note that for
  959. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  960. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  961. when :attr:`reduce` is ``False``. Default: ``True``
  962. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  963. losses are averaged or summed over observations for each minibatch depending
  964. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  965. batch element instead and ignores :attr:`size_average`. Default: ``True``
  966. reduction (string, optional): Specifies the reduction to apply to the output:
  967. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  968. ``'mean'``: the sum of the output will be divided by the number of
  969. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  970. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  971. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  972. Shape:
  973. - Input: :math:`(N, C)` where `N` is the batch size and `C` is the number of classes.
  974. - Target: :math:`(N, C)`, label targets padded by -1 ensuring same shape as the input.
  975. - Output: scalar. If :attr:`reduction` is ``'none'``, then :math:`(N)`.
  976. """
  977. __constants__ = ['reduction']
  978. def __init__(self, weight: Optional[Tensor] = None, size_average=None, reduce=None, reduction: str = 'mean') -> None:
  979. super(MultiLabelSoftMarginLoss, self).__init__(weight, size_average, reduce, reduction)
  980. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  981. return F.multilabel_soft_margin_loss(input, target, weight=self.weight, reduction=self.reduction)
  982. class CosineEmbeddingLoss(_Loss):
  983. r"""Creates a criterion that measures the loss given input tensors
  984. :math:`x_1`, :math:`x_2` and a `Tensor` label :math:`y` with values 1 or -1.
  985. This is used for measuring whether two inputs are similar or dissimilar,
  986. using the cosine similarity, and is typically used for learning nonlinear
  987. embeddings or semi-supervised learning.
  988. The loss function for each sample is:
  989. .. math::
  990. \text{loss}(x, y) =
  991. \begin{cases}
  992. 1 - \cos(x_1, x_2), & \text{if } y = 1 \\
  993. \max(0, \cos(x_1, x_2) - \text{margin}), & \text{if } y = -1
  994. \end{cases}
  995. Args:
  996. margin (float, optional): Should be a number from :math:`-1` to :math:`1`,
  997. :math:`0` to :math:`0.5` is suggested. If :attr:`margin` is missing, the
  998. default value is :math:`0`.
  999. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  1000. the losses are averaged over each loss element in the batch. Note that for
  1001. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  1002. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  1003. when :attr:`reduce` is ``False``. Default: ``True``
  1004. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  1005. losses are averaged or summed over observations for each minibatch depending
  1006. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  1007. batch element instead and ignores :attr:`size_average`. Default: ``True``
  1008. reduction (string, optional): Specifies the reduction to apply to the output:
  1009. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  1010. ``'mean'``: the sum of the output will be divided by the number of
  1011. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  1012. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  1013. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  1014. Shape:
  1015. - Input1: :math:`(N, D)` or :math:`(D)`, where `N` is the batch size and `D` is the embedding dimension.
  1016. - Input2: :math:`(N, D)` or :math:`(D)`, same shape as Input1.
  1017. - Target: :math:`(N)` or :math:`()`.
  1018. - Output: If :attr:`reduction` is ``'none'``, then :math:`(N)`, otherwise scalar.
  1019. """
  1020. __constants__ = ['margin', 'reduction']
  1021. margin: float
  1022. def __init__(self, margin: float = 0., size_average=None, reduce=None, reduction: str = 'mean') -> None:
  1023. super(CosineEmbeddingLoss, self).__init__(size_average, reduce, reduction)
  1024. self.margin = margin
  1025. def forward(self, input1: Tensor, input2: Tensor, target: Tensor) -> Tensor:
  1026. return F.cosine_embedding_loss(input1, input2, target, margin=self.margin, reduction=self.reduction)
  1027. class MarginRankingLoss(_Loss):
  1028. r"""Creates a criterion that measures the loss given
  1029. inputs :math:`x1`, :math:`x2`, two 1D mini-batch or 0D `Tensors`,
  1030. and a label 1D mini-batch or 0D `Tensor` :math:`y` (containing 1 or -1).
  1031. If :math:`y = 1` then it assumed the first input should be ranked higher
  1032. (have a larger value) than the second input, and vice-versa for :math:`y = -1`.
  1033. The loss function for each pair of samples in the mini-batch is:
  1034. .. math::
  1035. \text{loss}(x1, x2, y) = \max(0, -y * (x1 - x2) + \text{margin})
  1036. Args:
  1037. margin (float, optional): Has a default value of :math:`0`.
  1038. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  1039. the losses are averaged over each loss element in the batch. Note that for
  1040. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  1041. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  1042. when :attr:`reduce` is ``False``. Default: ``True``
  1043. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  1044. losses are averaged or summed over observations for each minibatch depending
  1045. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  1046. batch element instead and ignores :attr:`size_average`. Default: ``True``
  1047. reduction (string, optional): Specifies the reduction to apply to the output:
  1048. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  1049. ``'mean'``: the sum of the output will be divided by the number of
  1050. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  1051. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  1052. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  1053. Shape:
  1054. - Input1: :math:`(N)` or :math:`()` where `N` is the batch size.
  1055. - Input2: :math:`(N)` or :math:`()`, same shape as the Input1.
  1056. - Target: :math:`(N)` or :math:`()`, same shape as the inputs.
  1057. - Output: scalar. If :attr:`reduction` is ``'none'`` and Input size is not :math:`()`, then :math:`(N)`.
  1058. Examples::
  1059. >>> loss = nn.MarginRankingLoss()
  1060. >>> input1 = torch.randn(3, requires_grad=True)
  1061. >>> input2 = torch.randn(3, requires_grad=True)
  1062. >>> target = torch.randn(3).sign()
  1063. >>> output = loss(input1, input2, target)
  1064. >>> output.backward()
  1065. """
  1066. __constants__ = ['margin', 'reduction']
  1067. margin: float
  1068. def __init__(self, margin: float = 0., size_average=None, reduce=None, reduction: str = 'mean') -> None:
  1069. super(MarginRankingLoss, self).__init__(size_average, reduce, reduction)
  1070. self.margin = margin
  1071. def forward(self, input1: Tensor, input2: Tensor, target: Tensor) -> Tensor:
  1072. return F.margin_ranking_loss(input1, input2, target, margin=self.margin, reduction=self.reduction)
  1073. class MultiMarginLoss(_WeightedLoss):
  1074. r"""Creates a criterion that optimizes a multi-class classification hinge
  1075. loss (margin-based loss) between input :math:`x` (a 2D mini-batch `Tensor`) and
  1076. output :math:`y` (which is a 1D tensor of target class indices,
  1077. :math:`0 \leq y \leq \text{x.size}(1)-1`):
  1078. For each mini-batch sample, the loss in terms of the 1D input :math:`x` and scalar
  1079. output :math:`y` is:
  1080. .. math::
  1081. \text{loss}(x, y) = \frac{\sum_i \max(0, \text{margin} - x[y] + x[i])^p}{\text{x.size}(0)}
  1082. where :math:`x \in \left\{0, \; \cdots , \; \text{x.size}(0) - 1\right\}`
  1083. and :math:`i \neq y`.
  1084. Optionally, you can give non-equal weighting on the classes by passing
  1085. a 1D :attr:`weight` tensor into the constructor.
  1086. The loss function then becomes:
  1087. .. math::
  1088. \text{loss}(x, y) = \frac{\sum_i \max(0, w[y] * (\text{margin} - x[y] + x[i]))^p}{\text{x.size}(0)}
  1089. Args:
  1090. p (int, optional): Has a default value of :math:`1`. :math:`1` and :math:`2`
  1091. are the only supported values.
  1092. margin (float, optional): Has a default value of :math:`1`.
  1093. weight (Tensor, optional): a manual rescaling weight given to each
  1094. class. If given, it has to be a Tensor of size `C`. Otherwise, it is
  1095. treated as if having all ones.
  1096. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  1097. the losses are averaged over each loss element in the batch. Note that for
  1098. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  1099. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  1100. when :attr:`reduce` is ``False``. Default: ``True``
  1101. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  1102. losses are averaged or summed over observations for each minibatch depending
  1103. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  1104. batch element instead and ignores :attr:`size_average`. Default: ``True``
  1105. reduction (string, optional): Specifies the reduction to apply to the output:
  1106. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  1107. ``'mean'``: the sum of the output will be divided by the number of
  1108. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  1109. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  1110. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  1111. Shape:
  1112. - Input: :math:`(N, C)` or :math:`(C)`, where :math:`N` is the batch size and :math:`C` is the number of classes.
  1113. - Target: :math:`(N)` or :math:`()`, where each value is :math:`0 \leq \text{targets}[i] \leq C-1`.
  1114. - Output: scalar. If :attr:`reduction` is ``'none'``, then same shape as the target.
  1115. Examples::
  1116. >>> loss = nn.MultiMarginLoss()
  1117. >>> x = torch.tensor([[0.1, 0.2, 0.4, 0.8]])
  1118. >>> y = torch.tensor([3])
  1119. >>> loss(x, y)
  1120. >>> # 0.25 * ((1-(0.8-0.1)) + (1-(0.8-0.2)) + (1-(0.8-0.4)))
  1121. tensor(0.3250)
  1122. """
  1123. __constants__ = ['p', 'margin', 'reduction']
  1124. margin: float
  1125. p: int
  1126. def __init__(self, p: int = 1, margin: float = 1., weight: Optional[Tensor] = None, size_average=None,
  1127. reduce=None, reduction: str = 'mean') -> None:
  1128. super(MultiMarginLoss, self).__init__(weight, size_average, reduce, reduction)
  1129. if p != 1 and p != 2:
  1130. raise ValueError("only p == 1 and p == 2 supported")
  1131. assert weight is None or weight.dim() == 1
  1132. self.p = p
  1133. self.margin = margin
  1134. def forward(self, input: Tensor, target: Tensor) -> Tensor:
  1135. return F.multi_margin_loss(input, target, p=self.p, margin=self.margin,
  1136. weight=self.weight, reduction=self.reduction)
  1137. class TripletMarginLoss(_Loss):
  1138. r"""Creates a criterion that measures the triplet loss given an input
  1139. tensors :math:`x1`, :math:`x2`, :math:`x3` and a margin with a value greater than :math:`0`.
  1140. This is used for measuring a relative similarity between samples. A triplet
  1141. is composed by `a`, `p` and `n` (i.e., `anchor`, `positive examples` and `negative
  1142. examples` respectively). The shapes of all input tensors should be
  1143. :math:`(N, D)`.
  1144. The distance swap is described in detail in the paper `Learning shallow
  1145. convolutional feature descriptors with triplet losses`_ by
  1146. V. Balntas, E. Riba et al.
  1147. The loss function for each sample in the mini-batch is:
  1148. .. math::
  1149. L(a, p, n) = \max \{d(a_i, p_i) - d(a_i, n_i) + {\rm margin}, 0\}
  1150. where
  1151. .. math::
  1152. d(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_p
  1153. See also :class:`~torch.nn.TripletMarginWithDistanceLoss`, which computes the
  1154. triplet margin loss for input tensors using a custom distance function.
  1155. Args:
  1156. margin (float, optional): Default: :math:`1`.
  1157. p (int, optional): The norm degree for pairwise distance. Default: :math:`2`.
  1158. swap (bool, optional): The distance swap is described in detail in the paper
  1159. `Learning shallow convolutional feature descriptors with triplet losses` by
  1160. V. Balntas, E. Riba et al. Default: ``False``.
  1161. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
  1162. the losses are averaged over each loss element in the batch. Note that for
  1163. some losses, there are multiple elements per sample. If the field :attr:`size_average`
  1164. is set to ``False``, the losses are instead summed for each minibatch. Ignored
  1165. when :attr:`reduce` is ``False``. Default: ``True``
  1166. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
  1167. losses are averaged or summed over observations for each minibatch depending
  1168. on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
  1169. batch element instead and ignores :attr:`size_average`. Default: ``True``
  1170. reduction (string, optional): Specifies the reduction to apply to the output:
  1171. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  1172. ``'mean'``: the sum of the output will be divided by the number of
  1173. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  1174. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  1175. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  1176. Shape:
  1177. - Input: :math:`(N, D)` or :math:`(D)` where :math:`D` is the vector dimension.
  1178. - Output: A Tensor of shape :math:`(N)` if :attr:`reduction` is ``'none'`` and
  1179. input shape is :math:`(N, D)`; a scalar otherwise.
  1180. Examples::
  1181. >>> triplet_loss = nn.TripletMarginLoss(margin=1.0, p=2)
  1182. >>> anchor = torch.randn(100, 128, requires_grad=True)
  1183. >>> positive = torch.randn(100, 128, requires_grad=True)
  1184. >>> negative = torch.randn(100, 128, requires_grad=True)
  1185. >>> output = triplet_loss(anchor, positive, negative)
  1186. >>> output.backward()
  1187. .. _Learning shallow convolutional feature descriptors with triplet losses:
  1188. http://www.bmva.org/bmvc/2016/papers/paper119/index.html
  1189. """
  1190. __constants__ = ['margin', 'p', 'eps', 'swap', 'reduction']
  1191. margin: float
  1192. p: float
  1193. eps: float
  1194. swap: bool
  1195. def __init__(self, margin: float = 1.0, p: float = 2., eps: float = 1e-6, swap: bool = False, size_average=None,
  1196. reduce=None, reduction: str = 'mean'):
  1197. super(TripletMarginLoss, self).__init__(size_average, reduce, reduction)
  1198. self.margin = margin
  1199. self.p = p
  1200. self.eps = eps
  1201. self.swap = swap
  1202. def forward(self, anchor: Tensor, positive: Tensor, negative: Tensor) -> Tensor:
  1203. return F.triplet_margin_loss(anchor, positive, negative, margin=self.margin, p=self.p,
  1204. eps=self.eps, swap=self.swap, reduction=self.reduction)
  1205. class TripletMarginWithDistanceLoss(_Loss):
  1206. r"""Creates a criterion that measures the triplet loss given input
  1207. tensors :math:`a`, :math:`p`, and :math:`n` (representing anchor,
  1208. positive, and negative examples, respectively), and a nonnegative,
  1209. real-valued function ("distance function") used to compute the relationship
  1210. between the anchor and positive example ("positive distance") and the
  1211. anchor and negative example ("negative distance").
  1212. The unreduced loss (i.e., with :attr:`reduction` set to ``'none'``)
  1213. can be described as:
  1214. .. math::
  1215. \ell(a, p, n) = L = \{l_1,\dots,l_N\}^\top, \quad
  1216. l_i = \max \{d(a_i, p_i) - d(a_i, n_i) + {\rm margin}, 0\}
  1217. where :math:`N` is the batch size; :math:`d` is a nonnegative, real-valued function
  1218. quantifying the closeness of two tensors, referred to as the :attr:`distance_function`;
  1219. and :math:`margin` is a nonnegative margin representing the minimum difference
  1220. between the positive and negative distances that is required for the loss to
  1221. be 0. The input tensors have :math:`N` elements each and can be of any shape
  1222. that the distance function can handle.
  1223. If :attr:`reduction` is not ``'none'``
  1224. (default ``'mean'``), then:
  1225. .. math::
  1226. \ell(x, y) =
  1227. \begin{cases}
  1228. \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\
  1229. \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.}
  1230. \end{cases}
  1231. See also :class:`~torch.nn.TripletMarginLoss`, which computes the triplet
  1232. loss for input tensors using the :math:`l_p` distance as the distance function.
  1233. Args:
  1234. distance_function (callable, optional): A nonnegative, real-valued function that
  1235. quantifies the closeness of two tensors. If not specified,
  1236. `nn.PairwiseDistance` will be used. Default: ``None``
  1237. margin (float, optional): A nonnegative margin representing the minimum difference
  1238. between the positive and negative distances required for the loss to be 0. Larger
  1239. margins penalize cases where the negative examples are not distant enough from the
  1240. anchors, relative to the positives. Default: :math:`1`.
  1241. swap (bool, optional): Whether to use the distance swap described in the paper
  1242. `Learning shallow convolutional feature descriptors with triplet losses` by
  1243. V. Balntas, E. Riba et al. If True, and if the positive example is closer to the
  1244. negative example than the anchor is, swaps the positive example and the anchor in
  1245. the loss computation. Default: ``False``.
  1246. reduction (string, optional): Specifies the (optional) reduction to apply to the output:
  1247. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  1248. ``'mean'``: the sum of the output will be divided by the number of
  1249. elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``
  1250. Shape:
  1251. - Input: :math:`(N, *)` where :math:`*` represents any number of additional dimensions
  1252. as supported by the distance function.
  1253. - Output: A Tensor of shape :math:`(N)` if :attr:`reduction` is ``'none'``, or a scalar
  1254. otherwise.
  1255. Examples::
  1256. >>> # Initialize embeddings
  1257. >>> embedding = nn.Embedding(1000, 128)
  1258. >>> anchor_ids = torch.randint(0, 1000, (1,))
  1259. >>> positive_ids = torch.randint(0, 1000, (1,))
  1260. >>> negative_ids = torch.randint(0, 1000, (1,))
  1261. >>> anchor = embedding(anchor_ids)
  1262. >>> positive = embedding(positive_ids)
  1263. >>> negative = embedding(negative_ids)
  1264. >>>
  1265. >>> # Built-in Distance Function
  1266. >>> triplet_loss = \
  1267. >>> nn.TripletMarginWithDistanceLoss(distance_function=nn.PairwiseDistance())
  1268. >>> output = triplet_loss(anchor, positive, negative)
  1269. >>> output.backward()
  1270. >>>
  1271. >>> # Custom Distance Function
  1272. >>> def l_infinity(x1, x2):
  1273. >>> return torch.max(torch.abs(x1 - x2), dim=1).values
  1274. >>>
  1275. >>> triplet_loss = \
  1276. >>> nn.TripletMarginWithDistanceLoss(distance_function=l_infinity, margin=1.5)
  1277. >>> output = triplet_loss(anchor, positive, negative)
  1278. >>> output.backward()
  1279. >>>
  1280. >>> # Custom Distance Function (Lambda)
  1281. >>> triplet_loss = \
  1282. >>> nn.TripletMarginWithDistanceLoss(
  1283. >>> distance_function=lambda x, y: 1.0 - F.cosine_similarity(x, y))
  1284. >>> output = triplet_loss(anchor, positive, negative)
  1285. >>> output.backward()
  1286. Reference:
  1287. V. Balntas, et al.: Learning shallow convolutional feature descriptors with triplet losses:
  1288. http://www.bmva.org/bmvc/2016/papers/paper119/index.html
  1289. """
  1290. __constants__ = ['margin', 'swap', 'reduction']
  1291. margin: float
  1292. swap: bool
  1293. def __init__(self, *, distance_function: Optional[Callable[[Tensor, Tensor], Tensor]] = None,
  1294. margin: float = 1.0, swap: bool = False, reduction: str = 'mean'):
  1295. super(TripletMarginWithDistanceLoss, self).__init__(size_average=None, reduce=None, reduction=reduction)
  1296. self.distance_function: Optional[Callable[[Tensor, Tensor], Tensor]] = \
  1297. distance_function if distance_function is not None else PairwiseDistance()
  1298. self.margin = margin
  1299. self.swap = swap
  1300. def forward(self, anchor: Tensor, positive: Tensor, negative: Tensor) -> Tensor:
  1301. return F.triplet_margin_with_distance_loss(anchor, positive, negative,
  1302. distance_function=self.distance_function,
  1303. margin=self.margin, swap=self.swap, reduction=self.reduction)
  1304. class CTCLoss(_Loss):
  1305. r"""The Connectionist Temporal Classification loss.
  1306. Calculates loss between a continuous (unsegmented) time series and a target sequence. CTCLoss sums over the
  1307. probability of possible alignments of input to target, producing a loss value which is differentiable
  1308. with respect to each input node. The alignment of input to target is assumed to be "many-to-one", which
  1309. limits the length of the target sequence such that it must be :math:`\leq` the input length.
  1310. Args:
  1311. blank (int, optional): blank label. Default :math:`0`.
  1312. reduction (string, optional): Specifies the reduction to apply to the output:
  1313. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  1314. ``'mean'``: the output losses will be divided by the target lengths and
  1315. then the mean over the batch is taken. Default: ``'mean'``
  1316. zero_infinity (bool, optional):
  1317. Whether to zero infinite losses and the associated gradients.
  1318. Default: ``False``
  1319. Infinite losses mainly occur when the inputs are too short
  1320. to be aligned to the targets.
  1321. Shape:
  1322. - Log_probs: Tensor of size :math:`(T, N, C)` or :math:`(T, C)`,
  1323. where :math:`T = \text{input length}`,
  1324. :math:`N = \text{batch size}`, and
  1325. :math:`C = \text{number of classes (including blank)}`.
  1326. The logarithmized probabilities of the outputs (e.g. obtained with
  1327. :func:`torch.nn.functional.log_softmax`).
  1328. - Targets: Tensor of size :math:`(N, S)` or
  1329. :math:`(\operatorname{sum}(\text{target\_lengths}))`,
  1330. where :math:`N = \text{batch size}` and
  1331. :math:`S = \text{max target length, if shape is } (N, S)`.
  1332. It represent the target sequences. Each element in the target
  1333. sequence is a class index. And the target index cannot be blank (default=0).
  1334. In the :math:`(N, S)` form, targets are padded to the
  1335. length of the longest sequence, and stacked.
  1336. In the :math:`(\operatorname{sum}(\text{target\_lengths}))` form,
  1337. the targets are assumed to be un-padded and
  1338. concatenated within 1 dimension.
  1339. - Input_lengths: Tuple or tensor of size :math:`(N)` or :math:`()`,
  1340. where :math:`N = \text{batch size}`. It represent the lengths of the
  1341. inputs (must each be :math:`\leq T`). And the lengths are specified
  1342. for each sequence to achieve masking under the assumption that sequences
  1343. are padded to equal lengths.
  1344. - Target_lengths: Tuple or tensor of size :math:`(N)` or :math:`()`,
  1345. where :math:`N = \text{batch size}`. It represent lengths of the targets.
  1346. Lengths are specified for each sequence to achieve masking under the
  1347. assumption that sequences are padded to equal lengths. If target shape is
  1348. :math:`(N,S)`, target_lengths are effectively the stop index
  1349. :math:`s_n` for each target sequence, such that ``target_n = targets[n,0:s_n]`` for
  1350. each target in a batch. Lengths must each be :math:`\leq S`
  1351. If the targets are given as a 1d tensor that is the concatenation of individual
  1352. targets, the target_lengths must add up to the total length of the tensor.
  1353. - Output: scalar. If :attr:`reduction` is ``'none'``, then
  1354. :math:`(N)` if input is batched or :math:`()` if input is unbatched, where :math:`N = \text{batch size}`.
  1355. Examples::
  1356. >>> # Target are to be padded
  1357. >>> T = 50 # Input sequence length
  1358. >>> C = 20 # Number of classes (including blank)
  1359. >>> N = 16 # Batch size
  1360. >>> S = 30 # Target sequence length of longest target in batch (padding length)
  1361. >>> S_min = 10 # Minimum target length, for demonstration purposes
  1362. >>>
  1363. >>> # Initialize random batch of input vectors, for *size = (T,N,C)
  1364. >>> input = torch.randn(T, N, C).log_softmax(2).detach().requires_grad_()
  1365. >>>
  1366. >>> # Initialize random batch of targets (0 = blank, 1:C = classes)
  1367. >>> target = torch.randint(low=1, high=C, size=(N, S), dtype=torch.long)
  1368. >>>
  1369. >>> input_lengths = torch.full(size=(N,), fill_value=T, dtype=torch.long)
  1370. >>> target_lengths = torch.randint(low=S_min, high=S, size=(N,), dtype=torch.long)
  1371. >>> ctc_loss = nn.CTCLoss()
  1372. >>> loss = ctc_loss(input, target, input_lengths, target_lengths)
  1373. >>> loss.backward()
  1374. >>>
  1375. >>>
  1376. >>> # Target are to be un-padded
  1377. >>> T = 50 # Input sequence length
  1378. >>> C = 20 # Number of classes (including blank)
  1379. >>> N = 16 # Batch size
  1380. >>>
  1381. >>> # Initialize random batch of input vectors, for *size = (T,N,C)
  1382. >>> input = torch.randn(T, N, C).log_softmax(2).detach().requires_grad_()
  1383. >>> input_lengths = torch.full(size=(N,), fill_value=T, dtype=torch.long)
  1384. >>>
  1385. >>> # Initialize random batch of targets (0 = blank, 1:C = classes)
  1386. >>> target_lengths = torch.randint(low=1, high=T, size=(N,), dtype=torch.long)
  1387. >>> target = torch.randint(low=1, high=C, size=(sum(target_lengths),), dtype=torch.long)
  1388. >>> ctc_loss = nn.CTCLoss()
  1389. >>> loss = ctc_loss(input, target, input_lengths, target_lengths)
  1390. >>> loss.backward()
  1391. >>>
  1392. >>>
  1393. >>> # Target are to be un-padded and unbatched (effectively N=1)
  1394. >>> T = 50 # Input sequence length
  1395. >>> C = 20 # Number of classes (including blank)
  1396. >>>
  1397. >>> # Initialize random batch of input vectors, for *size = (T,C)
  1398. >>> input = torch.randn(T, C).log_softmax(2).detach().requires_grad_()
  1399. >>> input_lengths = torch.tensor(T, dtype=torch.long)
  1400. >>>
  1401. >>> # Initialize random batch of targets (0 = blank, 1:C = classes)
  1402. >>> target_lengths = torch.randint(low=1, high=T, size=(), dtype=torch.long)
  1403. >>> target = torch.randint(low=1, high=C, size=(target_lengths,), dtype=torch.long)
  1404. >>> ctc_loss = nn.CTCLoss()
  1405. >>> loss = ctc_loss(input, target, input_lengths, target_lengths)
  1406. >>> loss.backward()
  1407. Reference:
  1408. A. Graves et al.: Connectionist Temporal Classification:
  1409. Labelling Unsegmented Sequence Data with Recurrent Neural Networks:
  1410. https://www.cs.toronto.edu/~graves/icml_2006.pdf
  1411. Note:
  1412. In order to use CuDNN, the following must be satisfied: :attr:`targets` must be
  1413. in concatenated format, all :attr:`input_lengths` must be `T`. :math:`blank=0`,
  1414. :attr:`target_lengths` :math:`\leq 256`, the integer arguments must be of
  1415. dtype :attr:`torch.int32`.
  1416. The regular implementation uses the (more common in PyTorch) `torch.long` dtype.
  1417. Note:
  1418. In some circumstances when using the CUDA backend with CuDNN, this operator
  1419. may select a nondeterministic algorithm to increase performance. If this is
  1420. undesirable, you can try to make the operation deterministic (potentially at
  1421. a performance cost) by setting ``torch.backends.cudnn.deterministic =
  1422. True``.
  1423. Please see the notes on :doc:`/notes/randomness` for background.
  1424. """
  1425. __constants__ = ['blank', 'reduction']
  1426. blank: int
  1427. zero_infinity: bool
  1428. def __init__(self, blank: int = 0, reduction: str = 'mean', zero_infinity: bool = False):
  1429. super(CTCLoss, self).__init__(reduction=reduction)
  1430. self.blank = blank
  1431. self.zero_infinity = zero_infinity
  1432. def forward(self, log_probs: Tensor, targets: Tensor, input_lengths: Tensor, target_lengths: Tensor) -> Tensor:
  1433. return F.ctc_loss(log_probs, targets, input_lengths, target_lengths, self.blank, self.reduction,
  1434. self.zero_infinity)
  1435. # TODO: L1HingeEmbeddingCriterion
  1436. # TODO: MSECriterion weight
  1437. # TODO: ClassSimplexCriterion