NLLLoss#
- classtorch.nn.NLLLoss(weight=None,size_average=None,ignore_index=-100,reduce=None,reduction='mean')[source]#
The negative log likelihood loss. It is useful to train a classificationproblem withC classes.
If provided, the optional argument
weightshould be a 1D Tensor assigningweight to each of the classes. This is particularly useful when you have anunbalanced training set.Theinput given through a forward call is expected to containlog-probabilities of each class.input has to be a Tensor of size either orwith for theK-dimensional case. The latter is useful forhigher dimension inputs, such as computing NLL loss per-pixel for 2D images.
Obtaining log-probabilities in a neural network is easily achieved byadding aLogSoftmax layer in the last layer of your network.You may useCrossEntropyLoss instead, if you prefer not to add an extralayer.
Thetarget that this loss expects should be a class index in the rangewhereC = number of classes; ifignore_index is specified, this loss also acceptsthis class index (this index may not necessarily be in the class range).
The unreduced (i.e. with
reductionset to'none') loss can be described as:where is the input, is the target, is the weight, and is the batch size. If
reductionis not'none'(default'mean'), then- Parameters
weight (Tensor,optional) – a manual rescaling weight given to eachclass. If given, it has to be a Tensor of sizeC. Otherwise, it istreated as if having all ones.
size_average (bool,optional) – Deprecated (see
reduction). By default,the losses are averaged over each loss element in the batch. Note that forsome losses, there are multiple elements per sample. If the fieldsize_averageis set toFalse, the losses are instead summed for each minibatch. IgnoredwhenreduceisFalse. Default:Noneignore_index (int,optional) – Specifies a target value that is ignoredand does not contribute to the input gradient. When
size_averageisTrue, the loss is averaged overnon-ignored targets.reduce (bool,optional) – Deprecated (see
reduction). By default, thelosses are averaged or summed over observations for each minibatch dependingonsize_average. WhenreduceisFalse, returns a loss perbatch element instead and ignoressize_average. Default:Nonereduction (str,optional) – Specifies the reduction to apply to the output:
'none'|'mean'|'sum'.'none': no reduction willbe applied,'mean': the weighted mean of the output is taken,'sum': the output will be summed. Note:size_averageandreduceare in the process of being deprecated, and inthe meantime, specifying either of those two args will overridereduction. Default:'mean'
- Shape::
Input: or, whereC = number of classes,N = batch size, or within the case ofK-dimensional loss.
Target: or, where each value is, or with in the case ofK-dimensional loss.
Output: If
reductionis'none', shape or with in the case of K-dimensional loss.Otherwise, scalar.
Examples
>>>log_softmax=nn.LogSoftmax(dim=1)>>>loss_fn=nn.NLLLoss()>>># input to NLLLoss is of size N x C = 3 x 5>>>input=torch.randn(3,5,requires_grad=True)>>># each element in target must have 0 <= value < C>>>target=torch.tensor([1,0,4])>>>loss=loss_fn(log_softmax(input),target)>>>loss.backward()>>>>>>>>># 2D loss example (used, for example, with image inputs)>>>N,C=5,4>>>loss_fn=nn.NLLLoss()>>>data=torch.randn(N,16,10,10)>>>conv=nn.Conv2d(16,C,(3,3))>>>log_softmax=nn.LogSoftmax(dim=1)>>># output of conv forward is of shape [N, C, 8, 8]>>>output=log_softmax(conv(data))>>># each element in target must have 0 <= value < C>>>target=torch.empty(N,8,8,dtype=torch.long).random_(0,C)>>># input to NLLLoss is of size N x C x height (8) x width (8)>>>loss=loss_fn(output,target)>>>loss.backward()