Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Cross-entropy loss function

In the previous two chapters, encoding and embedding, we solved the problem of making a network model understand text, and built a simple text generation model.

A text generation model is essentially a multi-class classification model, so we put a Softmax activation function after the output layer of the network, which successfully turned the model’s numerical output into a probability distribution. But in actual training we did not see a clear effect. The root of the problem is not the Softmax activation function itself, but the way we measure error: the mean squared error loss function.

The mean squared error loss function measures how far the model’s prediction is from the target by the squared error between the prediction and the label, and gives different gradients accordingly to adjust the model parameters. The larger the loss, the larger the gradient.

But the Softmax activation function turns the raw predictions into a relative probability distribution.

When a prediction is far from the label, the result of Softmax is very close to 0 or 1 and its curve becomes very flat, so the probability distribution changes very little. This is gradient saturation. It means that for large prediction errors, Softmax has a clear weakening effect. If we keep using the mean squared error loss function in this situation, the gradient is weakened and training stalls.


To resolve the logical contradiction of “the worse the prediction, the smaller the correction”, we introduce a new evaluation criterion for classification tasks: the cross-entropy loss function. It works perfectly with the Softmax activation function. When the model’s prediction is far off, it provides a strong corrective push that makes up for the weakening effect of Softmax, and it becomes gentle when the prediction is close to correct.

Tensor

Dataset

Abstract class

Character-encoding dataset

Model

Abstract layer

Linear layer

Sequential layer

Embedding layer

Mean pooling layer

Activation functions

Rectified linear unit (ReLU)

Softmax

Loss functions

We first extract an abstract class for loss functions, which makes it easy to add new ones.

Abstract class

The abstract class defines only one abstract method:

  • loss (loss method): computes the loss.

Mean squared error loss function

Then we change the mean squared error loss function to inherit from the abstract class.

Cross-entropy loss function

The core idea of cross-entropy is:

  • the closer the predicted probability is to the label, the smaller the loss;

  • the further the predicted probability is from the true label, the loss grows sharply (logarithmically).

Forward propagation: the cross-entropy loss is defined as:

L=−∑i=1nyilog⁡(ai)L = -\sum_{i=1}^{n} y_i \log(a_i)

Where:

  • yiy_i: the probability of the label (one-hot encoding);

  • aia_i: the class probability of the activation (the output of the Softmax activation function).

The log function changes slowly when the probability is close to 1 and sharply when it is close to 0. It is the natural enemy of the exponential in Softmax. When the two are differentiated together, the gradient that vanished in the saturated region of Softmax is amplified again by the log function.

Gradient computation: implementations of the cross-entropy loss function usually include the Softmax computation. This greatly simplifies the gradient computation, and the formula is:

δ=ai−yi\delta = a_i - y_i

Where:

  • yiy_i: the probability of the label (one-hot encoding);

  • aia_i: the class probability of the prediction after Softmax.

In the code, the loss is the average over a batch of samples, so the gradient is also divided by the batch size.

Parent list (parents): the prediction (without the Softmax activation function).

Parameter list (parameters): none.

💡 Tip: The cross-entropy loss function already includes the Softmax computation. So there is no need for an output layer activation function when you use it.

Binary cross-entropy loss function

In a binary classification problem, we usually care about only one predicted probability. We can no longer use a vector activation function such as Softmax; instead we use the Sigmoid activation function to map the output into the interval (0,1)(0, 1).

Forward propagation: the binary cross-entropy loss is defined as:

L=−(ylog⁡(a)+(1−y)log⁡(1−a))L = -(y \log(a) + (1 - y) \log(1 - a))

Where:

  • yy: the probability of the label (0 or 1);

  • aa: the probability of the activation (the output of the Sigmoid activation function).

This formula measures the difference between the predicted probability and the label. The closer aa is to yy, the smaller the loss.

Gradient computation: the derivative with respect to the activation aa:

δ=a−ya(1−a)\delta = \frac{a - y}{a (1 - a)}

Where:

  • yy: the probability of the label (0 or 1);

  • aa: the probability of the activation (the output of the Sigmoid activation function).

The binary cross-entropy loss function is always used together with the Sigmoid activation function. This formula exactly cancels the gradient formula of Sigmoid, which solves the gradient saturation of Sigmoid for large predicted values.

Parent list (parents): the activation.

Parameter list (parameters): none.

💡 Tip: The binary cross-entropy loss function does not include the Sigmoid computation. So you still need an output layer activation function when you use it.

Optimizer (stochastic gradient descent)

Trainer

Hyperparameters

Learning rate

The cross-entropy loss function is sensitive to large changes in the gradient, which can easily cause oscillation, divergence, or failure to converge. We can choose a smaller learning rate.

Batch size

Number of epochs

Context size

Embedding size

Modeling

Let’s try the cross-entropy loss function and see how training goes.

Remember to remove the Softmax activation function after the output layer, because our cross-entropy loss function already includes the Softmax computation.

Training

Evaluation

prediction:	(6970, 65)
loss:	Tensor(3.3545101560265147)

We cannot compare the loss directly with the previous chapter, because a different loss function is used.

Inference

ROMEO:taots uaa e AVrsQsso nunaelf Urs uamoruUs nomAs  oesc sh ogiesso snnbto et vnlLEuSpd 
hwaaagetff yA middp rldeAofUiyeta 'd,
tso   ote fablo 
y:   draengss
peyeyoAhys na
d:rar
R:-  hJdasteY u OOW p l  t&rh uEs s
gottrt,PRcdh n afrol h bd Iuua  du o wdpal' u

With the new cross-entropy loss function, the generated text does not look very different. This is because an important problem is still unsolved: we build the features with a bag of words or mean pooling, which ignores the word order of the text.

Exercises

  1. The cross-entropy loss function already includes the Softmax of the output layer. Try adding a Softmax activation function after the output layer anyway, and see how the loss and the final inference result behave.