mindspore.nn.NLLLoss

class mindspore.nn.NLLLoss(weight=None, ignore_index=- 100, reduction='mean')[source]

Gets the negative log likelihood loss between logits and labels.

The nll loss with reduction=none can be described as:

β„“(x,t)=L={l1,…,lN}⊀,ln=βˆ’wtnxn,tn,wc= weight [c]β‹…1{cβ‰ ignore_index}

where x is the logits, t is the labels, w is the weight, N is the batch size, c belonging to [0,Cβˆ’1] is class index, where C is the number of classes.

If reduction is not β€˜none’ (default β€˜mean’), then

β„“(x,t)={βˆ‘n=1N1βˆ‘n=1Nwtnln, if reduction = 'mean', βˆ‘n=1Nln, if reduction = 'sum' 
Parameters
  • weight (Tensor) – The rescaling weight to each class. If the value is not None, the shape is (C,). The data type only supports float32 or float16. Default: None.

  • ignore_index (int) – Specifies a target value that is ignored (typically for padding value) and does not contribute to the gradient. Default: -100.

  • reduction (str) – Apply specific reduction method to the output: β€˜none’, β€˜mean’, or β€˜sum’. Default: β€˜mean’.

Inputs:
  • logits (Tensor) - Tensor of shape (N,C) or (N,C,d1,d2,...,dK) for K-dimensional data, where C = number of classes. Data type must be float16 or float32. inputs needs to be logarithmic probability.

  • labels (Tensor) -(N) or (N,d1,d2,...,dK) for K-dimensional data. Data type must be int32.

Returns

Tensor, the computed negative log likelihood loss value.

Raises
  • TypeError – If weight is not a Tensor.

  • TypeError – If ignore_index is not an int.

  • TypeError – If the data type of weight is not float16 or float32.

  • ValueError – If reduction is not one of β€˜none’, β€˜mean’, β€˜sum’.

  • TypeError – If logits is not a Tensor.

  • TypeError – If labels is not a Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> logits = mindspore.Tensor(np.random.randn(3, 5), mindspore.float32)
>>> labels = mindspore.Tensor(np.array([1, 0, 4]), mindspore.int32)
>>> loss = nn.NLLLoss()
>>> output = loss(logits, labels)