Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Loss Function and Gradient

Loss Function and Gradient

In this chapter, we will explore two crucial core concepts together:Loss function and gradient, which are the cornerstones that enable machine learning algorithms to learn and improve.

Imagine you are learning to shoot baskets. After each shot, you observe whether the ball went in, missed to the left, or missed to the right. The gap between this observation and a perfect shot is your loss. To shoot more accurately next time, you adjust your posture and strength based on the direction and magnitude of this deviation. Thisdirection and magnitude of the adjustmentis analogous to the gradient.

In machine learning, the model is the learner, the loss function measures how wrong it is, and the gradient tells ithow to improve. Understanding them means you have grasped the core logic of how machine learning works.


I. Loss Function: The Model's Report Card

1.1 What Is a Loss Function?

Loss function, sometimes also calledthe cost functionorthe objective function, is one used toquantify the difference between the model's predicted values and the true values.

1.2 Examples of Common Loss Functions

Different tasks require the use of differentscoring criteria, and the following are the two most fundamental loss functions:

Mean squared error - Suitable for regression problems (predicting continuous values such as house prices and temperature)

Mean Squared Error computes theaverage of the squared differences between the predicted values and the true values。

Formula: MSE = (1/n) * Σ(真实值ᵢ - 预测值ᵢ)²

Feature: Because squaring is used, it penalizes larger errors more heavily (when the error is 2, the squared contribution is 4; when the error is 10, the squared contribution reaches 100).

Code Example:

Example

import

numpy

as

np

Suppose we have the true values and predicted values of 5 samples

y_true

=

np.

array

(

[

3

,

0.5

,

2

,

7

,

4

]

)

     

True values

y_pred

=

np.

array

(

[

2.5

,

0.0

,

2

,

8

,

5

]

)

   

Predicted values

Calculate MSE manually

n

=

len

(

y_true

)

squared_errors

=

(

y_true - y_pred

)

**

2

   

Compute the squared error for each sample

mse_manual

=

np.

sum

(

squared_errors

)

/ n    

Sum and take the average

print

(

f

"Manually calculated MSE: {mse_manual}"

)

Verify using the sklearn library function

from

sklearn.

metrics

import

mean_squared_error

mse_sklearn

=

mean_squared_error

(

y_true

,

y_pred

)

print

(

f

"MSE calculated by Sklearn: {mse_sklearn}"

)

Cross entropy loss - Suitable for classification problems (predicting categories, such as whether an image is a cat or a dog)

Cross-entropy measures theprobability distribution predicted by the modelThe difference betweenthe true probability distributiondifference between them. In binary classification, the true distribution is usually [1, 0](is class A) or [0, 1](is class B).

Binary Classification Formula (Log Loss): Log Loss = - (1/n) * Σ [真实值ᵢ * log(预测概率ᵢ) + (1 - 真实值ᵢ) * log(1 - 预测概率ᵢ)]

Intuitive Understanding: When the true label is 1, we want the probability predicted by the model to be close to 1 as well. If the model predicts a very low probability at this point (such as 0.1), then log(0.1) will be a large negative number, and multiplying by the preceding negative sign will make the loss value very large, indicating a heavy penalty.

Code Example:

Example

import

numpy

as

np

from

sklearn.

metrics

import

log_loss

Binary Classification Example: True Labels (1 represents "yes", 0 represents "no")

y_true_binary

=

np.

array

(

[

1

,

0

,

0

,

1

]

)

True classes: yes, no, no, yes

The probability that the model predicts for the "yes" class

y_pred_prob

=

np.

array

(

[

0.9

,

0.1

,

0.2

,

0.8

]

)

Predicted probabilities: 0.9, 0.1, 0.2, 0.8

Compute cross-entropy loss (log loss) using sklearn

ce_loss

=

log_loss

(

y_true_binary

,

y_pred_prob

)

print

(

f

"Cross-Entropy Loss (Log Loss): {ce_loss}"

)


II. Gradient: The "Compass" That Guides the Optimization Direction

Now that we know how to score the model (the loss function), the next most critical question is:How does the model improve itself based on this score? The answer is throughgradient。

2.1 What Is a Gradient?

In machine learning, a model is usually composed of manyParameters(or calledWeight). We can treatthe loss function L as a function of all these parameters:L(w1, w2, ..., wn)。

  • Direction: The direction pointed to by the gradient vector is the direction in which the loss function at that pointincreases fastest.
  • Size: The absolute magnitude of each partial derivative indicates thesensitivity。
  • 1. **Direction**: The direction pointed to by the gradient vector is the direction in which the loss function at that point **increases fastest**. 2. **Magnitude**: The absolute magnitude of each partial derivative indicates the **sensitivity** of the loss function to changes in that parameter.

    2.2 Why Can Gradients Guide Optimization?

    Our goal is tominimize the loss function. Since the gradient points in the direction of the fastest increase in loss, its opposite direction -∇L is naturally the direction where the lossdecreases fastest.

    The optimization process (gradient descent) can be vividly understood as:

    You are standing on a hillside of a valley (the loss surface), blindfolded, trying to reach the bottom (the point of minimum loss). Before each step, you use your feet to sense which direction around you is the steepest (compute the gradient), and then take a step toward the steepestdownhill direction(the negative gradient direction) (updating the parameters). Repeating this process, you will eventually reach the bottom of the valley.

    This process can be summarized by the following flowchart:

    2.3 A Simple Example of Gradient Descent

    Let us use the simplest example—a linear model with only one parameter w , to demonstrate gradient descent.

    Suppose our loss function is L(w) = w². Obviously, when w = 0 , the loss is minimized.

    - `η` is the **learning rate**, controlling how big each step is.

    Example

    import

    numpy

    as

    np

    import

    matplotlib.

    pyplot

    as

    plt

    Define the loss function L(w) = w^2

    def

    loss

    (

    w

    )

    :

       

    return

    w **

    2

    Define the gradient dL/dw = 2*w

    def

    gradient

    (

    w

    )

    :

       

    return

    2

    Gradient Descent Algorithm

    def

    gradient_descent

    (

    start_w

    ,

    learning_rate

    ,

    iterations

    )

    :

        w

    =

    start_w

        w_history

    =

    [

    w

    ]

     

    Record the history of changes in w

        loss_history

    =

    [

    loss

    (

    w

    )

    ]

     

    Record the history of changes in the loss

       

    for

    i

    in

    range

    (

    iterations

    )

    :

            grad

    =

    gradient

    (

    w

    )

     

    Compute the gradient at the current point

            w

    =

    w - learning_rate * grad  

    Update the parameters along the negative gradient direction

            w_history.

    append

    (

    w

    )

            loss_history.

    append

    (

    loss

    (

    w

    )

    )

       

    return

    w_history

    ,

    loss_history

    Perform gradient descent: starting from w=5, learning rate 0.1, 20 iterations

    w_start

    =

    5.0

    lr

    =

    0.1

    iters

    =

    20

    w_hist

    ,

    loss_hist

    =

    gradient_descent

    (

    w_start

    ,

    lr

    ,

    iters

    )

    print

    (

    f

    "Initial w: {w_hist[0]:.4f}, initial loss: {loss_hist[0]:.4f}"

    )

    print

    (

    f

    "Final w: {w_hist[-1]:.4f}, final loss: {loss_hist[-1]:.4f}"

    )

    Visualize the optimization process

    plt.

    figure

    (

    figsize

    =

    (

    12

    ,

    4

    )

    )

    Figure 1: Loss function curve and optimization path

    plt.

    subplot

    (

    1

    ,

    2

    ,

    1

    )

    w_vals

    =

    np.

    linspace

    (

    6

    ,

    6

    ,

    100

    )

    plt.

    plot

    (

    w_vals

    ,

    loss

    (

    w_vals

    )

    ,

    label

    =

    'L(w) = w²'

    )

    plt.

    scatter

    (

    w_hist

    ,

    loss_hist

    ,

    c

    =

    'red'

    ,

    s

    =

    20

    ,

    label

    =

    'Gradient Descent Steps'

    )

    plt.

    plot

    (

    w_hist

    ,

    loss_hist

    ,

    'r--'

    ,

    alpha

    =

    0.5

    )

    plt.

    xlabel

    (

    'Parameter w'

    )

    plt.

    ylabel

    (

    'Loss L(w)'

    )

    plt.

    title

    (

    'Gradient Descent on L(w)=w²'

    )

    plt.

    legend

    (

    )

    plt.

    grid

    (

    True

    )

    Figure 2: Decline of the loss value with the number of iterations

    plt.

    subplot

    (

    1

    ,

    2

    ,

    2

    )

    plt.

    plot

    (

    range

    (

    len

    (

    loss_hist

    )

    )

    ,

    loss_hist

    ,

    'b-o'

    )

    plt.

    xlabel

    (

    'Iteration'

    )

    plt.

    ylabel

    (

    'Loss'

    )

    plt.

    title

    (

    'Loss Reduction Over Iterations'

    )

    plt.

    grid

    (

    True

    )

    plt.

    tight_layout

    (

    )

    plt.

    show

    (

    )

    Run this code and you will see:

    1. the left figure shows how the parameter w starts from 5.0, "rolls down" the parabola step by step, and finally approaches the minimum point 0.
    2. The right figure shows how the loss value decreases rapidly as the number of iterations increases.

    III. Summary of Core Points and Connections

    Concept Analogy Core Role Key points
    Loss function Report card / error measuring ruler Quantitatively evaluate how good or bad the model's predictions are. 1. Different types of tasks (regression, classification) use different loss functions.
    2. The smaller the loss value, the better the model performance.
    gradient Compass / steepest downhill direction Indicates how each model parameter should be adjusted in order to reduce the loss as quickly as possible. 1. It is the vector of partial derivatives of the loss function with respect to all parameters.
    2. Negative gradient directionIt is the direction in which the loss decreases fastest.
    gradient descent Blindfolded Descent Method Use gradient information to iteratively update parameters in order to minimize the loss. 1. Learning Rateis a key hyperparameter; if it is too small, learning is slow, and if it is too large, convergence may fail.
    2. It is the underlying optimization algorithm for training most machine learning models.

    The chain of relationships among them is: Model makes predictions → Loss function computes the error → Compute the gradient of the error with respect to each parameter → Update parameters along the negative gradient direction → Model improves → Repeat...