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.
The input
given through a forward call is expected to contain
log-probabilities of each class. input
has to be a Tensor of size either
\((minibatch, C)\) or \((minibatch, C, d_1, d_2, ..., d_K)\)
with \(K \geq 1\) for the K
-dimensional case (described later).
Obtaining log-probabilities in a neural network is easily achieved by
adding a LogSoftmax
layer in the last layer of your network.
You may use CrossEntropyLoss
instead, if you prefer not to add an extra
layer.
The target
that this loss expects should be a class index in the range \([0, C-1]\)
where C = number of classes
; if ignore_index
is specified, this loss also accepts
this class index (this index may not necessarily be in the class range).
The unreduced (i.e. with reduction
set to 'none'
) loss can be described as:
$$
\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
l_n = - w_{y_n} x_{n,y_n}, \quad
w_{c} = \mbox{weight}[c] \cdot \mbox{1}\{c \not= \mbox{ignore\_index}\},
$$
where \(x\) is the input, \(y\) is the target, \(w\) is the weight, and
\(N\) is the batch size. If reduction
is not 'none'
(default 'mean'
), then
$$
\ell(x, y) = \begin{array}{ll}
\sum_{n=1}^N \frac{1}{\sum_{n=1}^N w_{y_n}} l_n, &
\mbox{if reduction} = \mbox{'mean';}\\
\sum_{n=1}^N l_n, &
\mbox{if reduction} = \mbox{'sum'.}
\end{array}
$$
Can also be used for higher dimension inputs, such as 2D images, by providing
an input of size \((minibatch, C, d_1, d_2, ..., d_K)\) with \(K \geq 1\),
where \(K\) is the number of dimensions, and a target of appropriate shape
(see below). In the case of images, it computes NLL loss per-pixel.