mindspore.ops.cross_entropy

mindspore.ops.cross_entropy(input, target, weight=None, ignore_index=- 100, reduction='mean', label_smoothing=0.0)[source]

The cross entropy loss between input and target.

The cross entropy support two kind of targets:

  • Class indices (int) in the range [0,C) where C is the number of classes, the loss with reduction=none can be described as:

    β„“(x,y)=L={l1,…,lN}⊀,ln=βˆ’wynlog⁑exp⁑(xn,yn)βˆ‘c=1Cexp⁑(xn,c)β‹…1{ynβ‰ ignore_index}

    where x is the inputs, y is the target, 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,y)={βˆ‘n=1N1βˆ‘n=1Nwynβ‹…1{ynβ‰ ignore_index}ln,if reduction='mean',βˆ‘n=1Nln,if reduction='sum'.
  • Probabilities (float) for each class, useful when labels beyond a single class per minibatch item are required, the loss with reduction=none can be described as:

    β„“(x,y)=L={l1,…,lN}⊀,ln=βˆ’βˆ‘c=1Cwclog⁑exp⁑(xn,c)βˆ‘i=1Cexp⁑(xn,i)yn,c

    where x is the inputs, y is the target, 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,y)={βˆ‘n=1NlnN,if reduction='mean',βˆ‘n=1Nln,if reduction='sum'.
Parameters
  • input (Tensor) – (N) or (N,C) where C = number of classes or (N,C,H,W) in case of 2D Loss, or (N,C,d1,d2,...,dK). input is expected to be log-probabilities, data type must be float16 or float32.

  • target (Tensor) – For class indices, tensor of shape (), (N) or (N,d1,d2,...,dK) , data type must be int32. For probabilities, tensor of shape (C,) (N,C) or (N,C,d1,d2,...,dK) , data type must be float16 or float32.

  • weight (Tensor) – A rescaling weight applied to the loss of each batch element. If not None, the shape is (C,), data type must be float16 or float32. Default: None.

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

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

  • label_smoothing (float) – Label smoothing values, a regularization tool used to prevent the model from overfitting when calculating Loss. The value range is [0.0, 1.0]. Default value: 0.0.

Returns

Tensor, the computed loss value.

Supported Platforms:

Ascend GPU CPU

Examples

>>> # Case 1: Indices labels
>>> inputs = mindspore.Tensor(np.random.randn(3, 5), mindspore.float32)
>>> target = mindspore.Tensor(np.array([1, 0, 4]), mindspore.int32)
>>> output = ops.cross_entropy(inputs, target)
>>> # Case 2: Probability labels
>>> inputs = mindspore.Tensor(np.random.randn(3, 5), mindspore.float32)
>>> target = mindspore.Tensor(np.random.randn(3, 5), mindspore.float32)
>>> output = ops.cross_entropy(inputs, target)