Jump to content

Backpropagation: Difference between revisions

From Wikibase
No edit summary
No edit summary
 
(9 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Category:Artificial neural network]]
[[Category:Artificial neural network]]
'''Backpropagation''' is an algorithm used to train [[artificial neural network (ANN)|ANNs]].
== Base case ==


'''Backpropagation''' is an algorithm used to train [[artificial neural network (ANN)|ANNs]].
In a simple [[artificial neural network (ANN)]] of N layers obtained by [[artificial neuron#Layer_composition|basic layer composition]] and [[feedforward algorithm]], where each neuron satisfies


== Definition ==
{{#content:Q3075|noNote}}


Let $L$ represent the number of layers in the [[artificial neural network (ANN)]], $\vec a^{(0)}$ be the input value.
Let $\mathbf{W}^{(l)}, \vec b^{(l)}$ represent [[artificial neuron#Basic_form|'''weights''' and '''biases''']].


Let $\mathbf{W}^{(l)}, \vec b^{(l)}$ represents [[artificial neuron|'''weights''' and '''biases''']], $\vec z^{(l)}=\mathbf{W}^{(l)}\vec a^{(l-1)}+\vec b^{(l)}, \vec a^{(l)}=\sigma(\vec z^{(l)})$ pre-activation and activation of layer $l=1,\dots,L$, where $\sigma$ is the [[activation function]].
Let $\vec z^{(l)}=\mathbf{W}^{(l)}\vec a^{(l-1)}+\vec b^{(l)}, \vec a^{(l)}=\sigma(\vec z^{(l)})$ represent the pre-activation and activation of layer $l=1,\dots,N$ in the [[forward pass]], where $\sigma$ is the [[activation function]], commonly the [[sigmoid function]].


For a single training example $(\vec x,\vec y)$, where $\vec x,\vec y$ are input/expected output respectively, by definition
Feed a single training example $(\vec x,\vec y)$ to the [[ANN]], where $\vec x,\vec y$ are input/expected output respectively:


$$
$$
\vec a^{(0)}=\vec x.
\vec a^{(0)}=\vec x.
$$
=== Loss function ===
Define $L$ as a loss [[function]] measuring the difference between the expected output $\vec y=(y_i)$ and actual output $\vec y'=(y'_i)$.
Commonly, take
$$
L=\sum (y'_i-y_i)^2
$$
$$


Line 20: Line 33:


$$
$$
\delta_j^{(l)}=\frac{\partial C}{\partial z_j^{(l)}}
\delta_j^{(l)}=\frac{\partial L}{\partial z_j^{(l)}}
$$
$$


Line 28: Line 41:
\vec{\delta}^{(l)}
\vec{\delta}^{(l)}
=
=
\nabla_{\vec a^{(l)}}C\odot \dot \sigma (\vec z^{(L)}),
\nabla_{\vec a^{(l)}}L\odot \dot \sigma (\vec z^{(N)}),
$$
$$


Line 37: Line 50:
\delta_j^{(l)}
\delta_j^{(l)}
= \sum_k
= \sum_k
\frac{\partial C}{\partial a_k^{(L)}}
\frac{\partial L}{\partial a_k^{(N)}}
\frac{\partial a_k^{(L)}}{\partial z_j^{(L)}}.
\frac{\partial a_k^{(N)}}{\partial z_j^{(N)}}.
$$
$$
{{End hidden}}
{{End hidden}}
Line 51: Line 64:


$$
$$
\vec{\delta}^{(L)}=\nabla_{\vec a^{(L)}}C\odot\sigma'(\vec z^{(L)}).
\vec{\delta}^{(N)}=\nabla_{\vec a^{(N)}}L\odot\sigma'(\vec z^{(N)}).
$$
$$


Line 65: Line 78:
\odot
\odot
\sigma^{\prime}\left(\vec z^{(l)}\right),
\sigma^{\prime}\left(\vec z^{(l)}\right),
\qquad l=L-1,\dots,1.
\qquad l=N-1,\dots,1.
$$
$$


Line 81: Line 94:
\begin{aligned}
\begin{aligned}
\delta_j^{(l)}
\delta_j^{(l)}
&=\frac{\partial C}{\partial z_j^{(l)}}\\
&=\frac{\partial L}{\partial z_j^{(l)}}\\
&=\sum_k
&=\sum_k
\frac{\partial C}{\partial z_k^{(l+1)}}
\frac{\partial L}{\partial z_k^{(l+1)}}
\frac{\partial z_k^{(l+1)}}{\partial a_j^{(l)}}
\frac{\partial z_k^{(l+1)}}{\partial a_j^{(l)}}
\frac{\partial a_j^{(l)}}{\partial z_j^{(l)}}\\
\frac{\partial a_j^{(l)}}{\partial z_j^{(l)}}\\
Line 104: Line 117:
\odot
\odot
\sigma^{\prime}\left(\vec z^{(l)}\right),
\sigma^{\prime}\left(\vec z^{(l)}\right),
\qquad l=L-1,\dots,1.
\qquad l=N-1,\dots,1.
$$
$$
{{End hidden}}
{{End hidden}}
Line 113: Line 126:


$$
$$
\nabla_{\vec b^{(l)}}C=\vec{\delta}^{(l)}.
\nabla_{\vec b^{(l)}}L=\vec{\delta}^{(l)}.
$$
$$


{{Hidden proof}}
{{Hidden proof}}
$$
$$
\delta_k^{(l)}=\frac{\partial C}{\partial z_k^{(l)}} \text{ (by definition)}\\
\delta_k^{(l)}=\frac{\partial L}{\partial z_k^{(l)}} \text{ (by definition)}\\
\frac{\partial z_k^{(l)}}{\partial b_j^{(l)}}=
\frac{\partial z_k^{(l)}}{\partial b_j^{(l)}}=
\begin{cases}
\begin{cases}
Line 129: Line 142:


$$
$$
\frac{\partial C}{\partial b_j^{(l)}}
\frac{\partial L}{\partial b_j^{(l)}}
=
=
\sum_{k=0}^{n_l-1}
\sum_{k=0}^{n_l-1}
\frac{\partial C}{\partial z_k^{(l)}}
\frac{\partial L}{\partial z_k^{(l)}}
\frac{\partial z_k^{(l)}}{\partial b_j^{(l)}}
\frac{\partial z_k^{(l)}}{\partial b_j^{(l)}}
=
=
Line 141: Line 154:


$$
$$
\nabla_{\vec b^{(l)}}C=\vec{\delta}^{(l)}.
\nabla_{\vec b^{(l)}}L=\vec{\delta}^{(l)}.
$$
$$
{{End hidden}}
{{End hidden}}
Line 148: Line 161:


$$
$$
\nabla_{\mathbf{W}^{(l)}}C
\nabla_{\mathbf{W}^{(l)}}L
=
=
\vec{\delta}^{(l)}
\vec{\delta}^{(l)}
Line 166: Line 179:


$$
$$
\frac{\partial C}{\partial W_{ij}^{(l)}}
\frac{\partial L}{\partial W_{ij}^{(l)}}
=
=
\sum_{k=0}^{n_l-1}
\sum_{k=0}^{n_l-1}
\frac{\partial C}{\partial z_k^{(l)}}
\frac{\partial L}{\partial z_k^{(l)}}
\frac{\partial z_k^{(l)}}{\partial W_{ij}^{(l)}}
\frac{\partial z_k^{(l)}}{\partial W_{ij}^{(l)}}
=
=
Line 178: Line 191:


$$
$$
\nabla_{\mathbf{W}^{(l)}}C
\nabla_{\mathbf{W}^{(l)}}L
=
=
\vec{\delta}^{(l)}
\vec{\delta}^{(l)}
Line 185: Line 198:
{{End hidden}}
{{End hidden}}


== Training ==
=== Training ===


From [[#Definition]],
Since


$$
$$
\begin{cases}
\begin{cases}
\nabla_{\vec b^{(l)}}C=\vec{\delta}^{(l)},\\
\nabla_{\vec b^{(l)}}L=\vec{\delta}^{(l)},\\
\nabla_{\mathbf{W}^{(l)}}C=\vec{\delta}^{(l)}\left(\vec a^{(l-1)}\right)^T.
\nabla_{\mathbf{W}^{(l)}}L=\vec{\delta}^{(l)}\left(\vec a^{(l-1)}\right)^T.
\end{cases}
\end{cases}
$$
$$
Line 200: Line 213:
$$
$$
\begin{cases}
\begin{cases}
\mathbf{W}^{(l)}\leftarrow\mathbf{W}^{(l)}-\frac{\eta}{m}\sum_{x\in B}\nabla_{\mathbf{W}^{(l)}}C_x,\\
\mathbf{W}^{(l)}\leftarrow\mathbf{W}^{(l)}-\frac{\eta}{|B|}\sum_{x\in B}\nabla_{\mathbf{W}^{(l)}}L_x,\\
\vec b^{(l)}\leftarrow\vec b^{(l)}-\frac{\eta}{m}\sum_{x\in B}\nabla_{\vec b^{(l)}}C_x.
\vec b^{(l)}\leftarrow\vec b^{(l)}-\frac{\eta}{|B|}\sum_{x\in B}\nabla_{\vec b^{(l)}}L_x.
\end{cases}
\end{cases}
$$
$$


== Python [[pseudocode]] ==
where $\eta\in \mathbb{R}$ is the '''learning rate''' to be set before training begins, generally in the range of $10^{-3} \to 10^{-1}$.
 
== General case ==
 
The same backpropagation process applies for determining local gradients with regard to different [[model parameters]], and training algorithms are empirically-optimised variants of the base case.
 
== Python [[pseudocode]] (base case) ==


=== Backpropagation ===
=== Backpropagation ===
Line 243: Line 262:
         activations.append(activation)
         activations.append(activation)


     # --- output layer error (quadratic cost: dC/da = a - y) ---
     # --- output layer error (quadratic loss: dL/da = a - y) ---
     delta = (activations[-1] - y) * sigmoid_prime(zs[-1])
     delta = (activations[-1] - y) * sigmoid_prime(zs[-1])


Line 280: Line 299:
         nabla_w = [nw + dnw for nw, dnw in zip(nabla_w, d_nabla_w)]
         nabla_w = [nw + dnw for nw, dnw in zip(nabla_w, d_nabla_w)]


     # W^(l) <- W^(l) - (eta/m) * sum_{x in B} grad_W C_x
     # W^(l) <- W^(l) - (eta/m) * sum_{x in B} grad_W L_x
     # b^(l) <- b^(l) - (eta/m) * sum_{x in B} grad_b C_x
     # b^(l) <- b^(l) - (eta/m) * sum_{x in B} grad_b L_x
     self.weights = [w - (eta / m) * nw for w, nw in zip(self.weights, nabla_w)]
     self.weights = [w - (eta / m) * nw for w, nw in zip(self.weights, nabla_w)]
     self.biases  = [b - (eta / m) * nb for b, nb in zip(self.biases,  nabla_b)]
     self.biases  = [b - (eta / m) * nb for b, nb in zip(self.biases,  nabla_b)]

Latest revision as of 11:35, 17 November 2026

Backpropagation is an algorithm used to train ANNs.

Base case

In a simple artificial neural network (ANN) of N layers obtained by basic layer composition and feedforward algorithm, where each neuron satisfies

$$\begin{gathered}a = f\left(z \right)\\ \text{Basic form}: z = \sum_{i=1}^{n} w_i x_i + b\end{gathered}$$

Let $\mathbf{W}^{(l)}, \vec b^{(l)}$ represent weights and biases.

Let $\vec z^{(l)}=\mathbf{W}^{(l)}\vec a^{(l-1)}+\vec b^{(l)}, \vec a^{(l)}=\sigma(\vec z^{(l)})$ represent the pre-activation and activation of layer $l=1,\dots,N$ in the forward pass, where $\sigma$ is the activation function, commonly the sigmoid function.

Feed a single training example $(\vec x,\vec y)$ to the ANN, where $\vec x,\vec y$ are input/expected output respectively:

$$ \vec a^{(0)}=\vec x. $$

Loss function

Define $L$ as a loss function measuring the difference between the expected output $\vec y=(y_i)$ and actual output $\vec y'=(y'_i)$.

Commonly, take

$$ L=\sum (y'_i-y_i)^2 $$

Sensitivity

Define sensitivity at layer $l$:

$$ \delta_j^{(l)}=\frac{\partial L}{\partial z_j^{(l)}} $$

In vector form:

$$ \vec{\delta}^{(l)} = \nabla_{\vec a^{(l)}}L\odot \dot \sigma (\vec z^{(N)}), $$

In some textbook, $\delta_j^{(l)}$ is referred to as error. We discourage this use, as $\delta_j^{(l)}$ is a local gradient, not an "error" in its ususal sense, and calling it an error can lead to serious confusion.

Sensitivity of the output layer

By definition of sensitivity,

$$ \vec{\delta}^{(N)}=\nabla_{\vec a^{(N)}}L\odot\sigma'(\vec z^{(N)}). $$

Sensitivity of previous layers

$$ \vec{\delta}^{(l)} = \left( \left(\mathbf{W}^{(l+1)}\right)^T \vec{\delta}^{(l+1)} \right) \odot \sigma^{\prime}\left(\vec z^{(l)}\right), \qquad l=N-1,\dots,1. $$

Local gradients

Biases

$$ \nabla_{\vec b^{(l)}}L=\vec{\delta}^{(l)}. $$

Weights

$$ \nabla_{\mathbf{W}^{(l)}}L = \vec{\delta}^{(l)} \left(\vec a^{(l-1)}\right)^T, $$

Training

Since

$$ \begin{cases} \nabla_{\vec b^{(l)}}L=\vec{\delta}^{(l)},\\ \nabla_{\mathbf{W}^{(l)}}L=\vec{\delta}^{(l)}\left(\vec a^{(l-1)}\right)^T. \end{cases} $$

With training dataset $S$ and sample batch $B \in S$,

$$ \begin{cases} \mathbf{W}^{(l)}\leftarrow\mathbf{W}^{(l)}-\frac{\eta}{|B|}\sum_{x\in B}\nabla_{\mathbf{W}^{(l)}}L_x,\\ \vec b^{(l)}\leftarrow\vec b^{(l)}-\frac{\eta}{|B|}\sum_{x\in B}\nabla_{\vec b^{(l)}}L_x. \end{cases} $$

where $\eta\in \mathbb{R}$ is the learning rate to be set before training begins, generally in the range of $10^{-3} \to 10^{-1}$.

General case

The same backpropagation process applies for determining local gradients with regard to different model parameters, and training algorithms are empirically-optimised variants of the base case.

Python pseudocode (base case)

Backpropagation

import numpy as np


def sigmoid(z):
    return 1.0 / (1.0 + np.exp(-z))


def sigmoid_prime(z):
    s = sigmoid(z)
    return s * (1.0 - s)


def feedforward(self, a):
    """Feedforward input vector a to a_1."""
    for b, w in zip(self.biases, self.weights):
        a = sigmoid(np.dot(w, a) + b)   # note: overwrite a each layer
    return a


def backprop(self, x, y):
    """Return (nabla_b, nabla_w) for a single training example (x, y)."""
    # --- forward pass (recompute zs and activations, since feedforward
    #     only returns the final a_1) ---
    activation = x
    activations = [x]
    zs = []

    for b, w in zip(self.biases, self.weights):
        z = np.dot(w, activation) + b
        zs.append(z)
        activation = sigmoid(z)
        activations.append(activation)

    # --- output layer error (quadratic loss: dL/da = a - y) ---
    delta = (activations[-1] - y) * sigmoid_prime(zs[-1])

    nabla_b = [np.zeros(b.shape) for b in self.biases]
    nabla_w = [np.zeros(w.shape) for w in self.weights]

    nabla_b[-1] = delta
    nabla_w[-1] = np.dot(delta, activations[-2].T)

    # --- backpropagate through hidden layers ---
    num_layers = len(self.weights) + 1
    for l in range(2, num_layers):
        z = zs[-l]
        sp = sigmoid_prime(z)
        delta = np.dot(self.weights[-l + 1].T, delta) * sp
        nabla_b[-l] = delta
        nabla_w[-l] = np.dot(delta, activations[-l - 1].T)

    return nabla_b, nabla_w

Training

import random

def update_mini_batch(self, batch, eta):
    """One SGD step on mini-batch B: sum per-sample gradients, apply W -= (eta/m) * sum."""
    nabla_b = [np.zeros(b.shape) for b in self.biases]
    nabla_w = [np.zeros(w.shape) for w in self.weights]

    m = len(batch)                       # m = |B|  (use actual size; last batch may be short)
    for x, y in batch:
        d_nabla_b, d_nabla_w = self.backprop(x, y)   # = (delta^(l), delta^(l) a^(l-1)^T)
        nabla_b = [nb + dnb for nb, dnb in zip(nabla_b, d_nabla_b)]
        nabla_w = [nw + dnw for nw, dnw in zip(nabla_w, d_nabla_w)]

    # W^(l) <- W^(l) - (eta/m) * sum_{x in B} grad_W L_x
    # b^(l) <- b^(l) - (eta/m) * sum_{x in B} grad_b L_x
    self.weights = [w - (eta / m) * nw for w, nw in zip(self.weights, nabla_w)]
    self.biases  = [b - (eta / m) * nb for b, nb in zip(self.biases,  nabla_b)]


def train(self, training_data, epochs, mini_batch_size, eta, test_data=None):
    """training_data: iterable of (x, y) examples."""
    training_data = list(training_data)
    n = len(training_data)

    for epoch in range(epochs):
        random.shuffle(training_data)
        mini_batches = [
            training_data[k:k + mini_batch_size]
            for k in range(0, n, mini_batch_size)
        ]
        for batch in mini_batches:
            self.update_mini_batch(batch, eta)

        if test_data is not None:
            n_test = len(test_data)
            n_correct = sum(
                int(np.argmax(self.feedforward(x)) == np.argmax(y))
                for x, y in test_data
            )
            print(f"Epoch {epoch}: {n_correct}/{n_test}")
        else:
            print(f"Epoch {epoch} complete")