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

Forward Propagation and Backpropagation

Forward Propagation and Backpropagation

In deep learning, forward propagation and backpropagation are the two core pillars supporting its operation. Like two sides of the same coin, they together form the complete loop of neural networks from learning to application. A thorough understanding of these two processes is the first key to opening the door to deep learning.

This article will guide you step by step through these seemingly complex concepts, using clear logic and vivid analogies, so that you not only know what, but also know why.


What are forward propagation and backpropagation?

Before diving into details, let's first build a big-picture understanding.

Imagine you are teaching a child to recognize cats and dogs. You show the child a picture (Input), and the child makes a judgment based on the knowledge already in their brain (network parameters, namely weights and biases), then tells you it is a cat (Output). This process of seeing the picture -> brain processing -> giving an answer isForward propagation。

But the child's judgment may be wrong. You tell them: No, this is a dog. The difference between this correct answer and the child's answer is theerror. Based on this error, the child needs to reflect: which knowledge (parameters) in my brain caused this misjudgment? How should I adjust them to get it right next time? This process of adjusting knowledge from back to front based on the error isBackpropagation。

In a neural network:

They can be represented by a simple learning loop diagram:


Forward propagation: The inference path of neural networks

Forward propagation is the forward path through which neural networks make predictions. Let's understand it through the simplest three-layer neural network (input layer, one hidden layer, output layer).

Core concepts and computation

Suppose we want to predict house prices, with the input being the house area x. Our miniature network structure is as follows:

The computation of forward propagation is divided into two steps:

1. Hidden layer computation: the input x with weight w1and bias b1 combined, then passed through an activation function (e.g., Sigmoid, denoted σ), producing the hidden layer output a1。

z1 = w1 * x + b1

a1 = σ(z1) = 1 / (1 + exp(-z1))

2. Output layer computation: the hidden layer output a1 as input, combined with the output layer's weight w2and bias b2 , producing the final prediction y_pred. For simplicity here, assume the output layer does not use an activation function (i.e., linear output).

y_pred = w2 * a1 + b2

Code example: Manually implementing forward propagation

Example

import

numpy

as

np

def

sigmoid

(

x

)

:

   

"""Sigmoid activation function"""

   

return

1

/

(

1

exp

(

-x

)

)

Initialize the network parameters (usually randomly initialized; specified values here for demonstration).

w1

,

b1

=

2.0

,

1.0

 

Hidden layer parameters.

w2

,

b2

=

1.5

,

0.5

 

Output layer parameters.

def

forward_pass

(

x

)

:

   

"""Perform one forward propagation"""

   

Hidden layer computation.

    z1

=

w1 * x + b1

    a1

=

sigmoid

(

z1

)

 

Apply the activation function.

   

   

Output layer computation.

    y_pred

=

w2 * a1 + b2  

Linear output.

   

   

Return the intermediate results and the final prediction, for easier understanding later.

   

return

{

'z1'

: z1

,

'a1'

: a1

,

'y_pred'

: y_pred

}

Assume the house area is 3 (unit: 100 square meters).

x_input

=

3.0

result

=

forward_pass

(

x_input

)

print

(

f

"Input x = {x_input}"

)

print

(

f

"Hidden layer linear output z1 = w1*x + b1 = {result['z1']:.4f}"

)

print

(

f

"Hidden layer activation output a1 = sigmoid(z1) = {result['a1']:.4f}"

)

print

(

f

"Final predicted house price y_pred = w2*a1 + b2 = {result['y_pred']:.4f}"

)

Example output:

输入 x = 3.0

隐藏层线性输出 z1 = w1*x + b1 = 5.0000

隐藏层激活输出 a1 = sigmoid(z1) = 0.9933

最终预测房价 y_pred = w2*a1 + b2 = 1.9899

This y_pred is the network's predicted price for a house of area 3. But obviously, this prediction (based on our arbitrarily set parameters) is likely far from the true house price. How can we measure this gap and improve it? This requires theLoss functionand the followingBackpropagation。


loss function: The yardstick for good and bad

Before backpropagation begins, we must first quantify the gap between the predicted value y_pred and the true value y_true . This is the role of the loss function.

Common loss functions:

Taking mean squared error as an example, for a single sample:

Loss = (y_true - y_pred)^2

Our goal is to adjust w1, b1, w2, b2so that this Loss value is as small as possible.


Backpropagation: The learning engine of neural networks

Backpropagation is the core of deep learning's learning algorithm. Its essence is the efficient application of thechain rulein neural networks. The goal is to compute the loss function's L with respect to each parameter (w1, b1, w2, b2) thepartial derivative (gradient), which means it ∂L/∂w1, ∂L/∂b1 , etc. These gradients indicate the direction and magnitude in which each parameter should be adjusted to reduce the loss.

Understanding gradients: The direction and step size for descending the mountain

Imagine you are standing blindfolded on a mountain (loss surface), with the goal of finding the lowest point of the valley (minimum loss). Before each step, you need to feel with your feet the steepest downhill direction around you. This steepest downhill direction is thegradient. Backpropagation helps you precisely compute the gradient at every point under your feet (corresponding to each set of parameters).

Backpropagation computation steps (chain rule differentiation)

We continue with the previous miniature network and assume the true house price y_true = 2.5, with the loss function being mean squared error. L = (y_true - y_pred)^2。

Backpropagation starts from the output layer,backwardcomputing gradients layer by layer:

Compute the gradients of the output layer parameters.

Compute the gradients of the hidden layer parameters.

Code example: Manually implementing backpropagation

Example

Continuing the code and results from forward propagation.

y_true

=

2.5

y_pred

=

result

[

'y_pred'

]

a1

=

result

[

'a1'

]

z1

=

result

[

'z1'

]

x

=

x_input

print

(

f

"True value y_true = {y_true}"

)

print

(

f

"Predicted value y_pred = {y_pred:.4f}"

)

print

(

f

"Initial loss Loss = {(y_true - y_pred)**2:.4f}"

)

print

(

"\n--- Start backpropagation gradient computation ---"

)

1. Compute the gradient of the loss with respect to y_pred.

dL_dy_pred

=

2

(

y_true - y_pred

)

print

(

f

"Gradient ∂L/∂y_pred = -2*(y_true - y_pred) = {dL_dy_pred:.4f}"

)

2. Compute the gradients of the output layer parameters w2, b2.

dL_dw2

=

dL_dy_pred * a1

dL_db2

=

dL_dy_pred *

1

print

(

f

"Gradient ∂L/∂w2 = (∂L/∂y_pred) * a1 = {dL_dw2:.4f}"

)

print

(

f

"Gradient ∂L/∂b2 = (∂L/∂y_pred) * 1 = {dL_db2:.4f}"

)

3. Compute the gradient of the loss with respect to hidden layer output a1.

dL_da1

=

dL_dy_pred * w2

print

(

f

"Gradient ∂L/∂a1 = (∂L/∂y_pred) * w2 = {dL_da1:.4f}"

)

4. Compute the value of the Sigmoid function's derivative at z1.

def

sigmoid_derivative

(

x

)

:

   

"""Derivative of the Sigmoid function"""

    s

=

sigmoid

(

x

)

   

return

s *

(

1

)

sigma_prime_z1

=

sigmoid_derivative

(

z1

)

print

(

f

"Sigmoid derivative σ'(z1) = σ(z1)*(1-σ(z1)) = {sigma_prime_z1:.4f}"

)

5. Compute the gradients of the hidden layer parameters w1, b1.

dL_dw1

=

dL_da1 * sigma_prime_z1 * x

dL_db1

=

dL_da1 * sigma_prime_z1 *

1

print

(

f

"Gradient ∂L/∂w1 = (∂L/∂a1) * σ'(z1) * x = {dL_dw1:.4f}"

)

print

(

f

"Gradient ∂L/∂b1 = (∂L/∂a1) * σ'(z1) * 1 = {dL_db1:.4f}"

)

Example output:

真实值 y_true = 2.5

预测值 y_pred = 1.9899

初始损失 Loss = 0.2602



--- Start backpropagation gradient calculation ---

梯度 ∂L/∂y_pred = -2*(y_true - y_pred) = -1.0202

梯度 ∂L/∂w2 = (∂L/∂y_pred) * a1 = -1.0134

梯度 ∂L/∂b2 = (∂L/∂y_pred) * 1 = -1.0202

梯度 ∂L/∂a1 = (∂L/∂y_pred) * w2 = -1.5303

Sigmoid导数 σ'(z1) = σ(z1)*(1-σ(z1)) = 0.0066

梯度 ∂L/∂w1 = (∂L/∂a1) * σ'(z1) * x = -0.0304

梯度 ∂L/∂b1 = (∂L/∂a1) * σ'(z1) * 1 = -0.0101

Now we have obtained the gradients of all parameters. These negative values mean that if weIncrementthese parameters' values, the loss willincrease(because the gradient direction is the ascending direction). To reduce the loss, we shouldadjust the parameters in the direction opposite to the gradient.


Parameter update: Gradient descent

After obtaining the gradients, we use thegradient descentalgorithm to update the parameters:

参数 = 参数 - 学习率 * 该参数的梯度

WhereLearning Rateis a very important hyperparameter that controls the step size of each parameter update. Too small a step leads to slow learning; too large a step may fail to converge or even diverge.

Code example: Applying gradient descent to update parameters.

Example

learning_rate

=

0.1

Update parameters

w1_new

=

w1 - learning_rate * dL_dw1

b1_new

=

b1 - learning_rate * dL_db1

w2_new

=

w2 - learning_rate * dL_dw2

b2_new

=

b2 - learning_rate * dL_db2

print

(

"--- Updated parameters ---"

)

print

(

f

"w1: {w1:.4f} -> {w1_new:.4f}"

)

print

(

f

"b1: {b1:.4f} -> {b1_new:.4f}"

)

print

(

f

"w2: {w2:.4f} -> {w2_new:.4f}"

)

print

(

f

"b2: {b2:.4f} -> {b2_new:.4f}"

)

Perform one forward propagation with the new parameters to verify whether the loss decreases.

def

forward_pass_with_params

(

x

,

w1

,

b1

,

w2

,

b2

)

:

    z1

=

w1 * x + b1

    a1

=

sigmoid

(

z1

)

    y_pred

=

w2 * a1 + b2

   

return

y_pred

y_pred_new

=

forward_pass_with_params

(

x_input

,

w1_new

,

b1_new

,

w2_new

,

b2_new

)

loss_new

=

(

y_true - y_pred_new

)

**

2

print

(

f

"\nPrediction with new parameters: y_pred_new = {y_pred_new:.4f}"

)

print

(

f

"Updated loss New Loss = {loss_new:.4f}"

)

print

(

f

"Loss change: {loss_new - (y_true-y_pred)**2:.4f} (negative value indicates loss decreased)"

)

Example output:

--- 更新后的参数 ---

w1: 2.0000 -> 2.0030

b1: -1.0000 -> -0.9990

w2: 1.5000 -> 1.6013

b2: 0.5000 -> 0.6020



用新参数预测: y_pred_new = 2.1933

更新后的损失 New Loss = 0.0940

损失变化: -0.1662 (负值表示损失减小)

Great! After oneforward propagation -> loss computation -> backpropagation -> gradient descent updatecomplete cycle, our predicted value y_pred From the 1.99 is closer to the true value 2.5, and the loss also decreased from 0.260 to 0.094. Repeating this cycle thousands or tens of thousands of times (on large amounts of data), the neural network can learn effective parameters and make accurate predictions.


Practical exercise: Consolidate your understanding.

Now it's time to consolidate what you've learned hands-on.

Exercise 1: Expand the network. Modify the code above to increase the hidden layer to 2 neurons. You need to initialize w1 as a shape of (2,) array (two weights),b1 is (2,) array. Adjust the forward propagation and backpropagation computations accordingly. Observe how the network's capability changes.

Exercise 2: Change the activation function. Replace the Sigmoid activation function with the ReLU function (f(x) = max(0, x)). You need to re-derive and implement the derivative of ReLU (f'(x) = 1 if x>0 else 0). Compare how the training process differs when using different activation functions.

Exercise 3: Implement a training loop. Write a complete training loop that, on some simple dataset (e.g., self-constructed y = 2x + 1 + 噪声 data), trains a miniature network to fit it. Set the number of iterations (epoch), print the loss after each iteration, and observe whether the loss continues to decrease with training.

Exercise 4: Understand the impact of the learning rate. Building on Exercise 3, try different learning_rate(e.g., 0.01, 0.1, 0.5, 1.0). Observe how the loss curve changes when the learning rate is too large or too small (whether it oscillates, diverges, or converges slowly), and deeply understand the importance of the learning rate as the step size.


Summary

Forward propagation and backpropagation are the core dynamics of neural network learning:

  1. Forward propagationIsInference path, which uses current parameters to map inputs to outputs and computes a score (loss) of the current performance.
  2. BackpropagationIsLearning algorithm, which uses the chain rule to efficiently compute the gradient of the loss function with respect to every parameter in the network, indicating the direction of parameter optimization.
  3. gradient descentIsOptimization strategy, which, based on the gradients provided by backpropagation and using the learning rate as the step size, actually updates parameters so that the network's performance gradually improves.