class torch.nn.CrossEntropyLoss(weight: Optional[torch.Tensor] = None, size_average=None, ignore_index: int = -100, reduce=None, reduction: str = 'mean')
This criterion combines
nn.NLLLoss() in one single class.
It is useful when training a classification problem with
C classes. If provided, the optional argument
weight should be a 1D
Tensor assigning weight to each of the classes. This is particularly useful when you have an unbalanced training set.
input is expected to contain raw, unnormalized scores for each class.
input has to be a Tensor of size either or with for the
K-dimensional case (described later).
This criterion expects a class index in the range as the
target for each value of a 1D tensor of size
ignore_index is specified, this criterion also accepts this class index (this index may not necessarily be in the class range).
The loss can be described as:
or in the case of the
weight argument being specified:
The losses are averaged across observations for each minibatch. If the
weight argument is specified then this is a weighted average:
Can also be used for higher dimension inputs, such as 2D images, by providing an input of size with , where is the number of dimensions, and a target of appropriate shape (see below).
reduction). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there are multiple elements per sample. If the field
size_averageis set to
False, the losses are instead summed for each minibatch. Ignored when reduce is
True, the loss is averaged over non-ignored targets.
reduction). By default, the losses are averaged or summed over observations for each minibatch depending on
False, returns a loss per batch element instead and ignores
'none': no reduction will be applied,
'mean': the weighted mean of the output is taken,
'sum': the output will be summed. Note:
reduceare in the process of being deprecated, and in the meantime, specifying either of those two args will override
C = number of classes, or with in the case of
'none', then the same size as the target: , or with in the case of K-dimensional loss.
>>> loss = nn.CrossEntropyLoss() >>> input = torch.randn(3, 5, requires_grad=True) >>> target = torch.empty(3, dtype=torch.long).random_(5) >>> output = loss(input, target) >>> output.backward()
© 2019 Torch Contributors
Licensed under the 3-clause BSD License.