Backpropagation: Difference between revisions
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 == | |||
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 | |||
{{#content:Q3075|noNote}} | |||
Let $ | Let $\mathbf{W}^{(l)}, \vec b^{(l)}$ represent [[artificial neuron#Basic_form|'''weights''' and '''biases''']]. | ||
Let | 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. | \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 | \delta_j^{(l)}=\frac{\partial L}{\partial z_j^{(l)}} | ||
$$ | $$ | ||
| Line 28: | Line 41: | ||
\vec{\delta}^{(l)} | \vec{\delta}^{(l)} | ||
= | = | ||
\nabla_{\vec a^{(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 | \frac{\partial L}{\partial a_k^{(N)}} | ||
\frac{\partial a_k^{( | \frac{\partial a_k^{(N)}}{\partial z_j^{(N)}}. | ||
$$ | $$ | ||
{{End hidden}} | {{End hidden}} | ||
| Line 51: | Line 64: | ||
$$ | $$ | ||
\vec{\delta}^{( | \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= | \qquad l=N-1,\dots,1. | ||
$$ | $$ | ||
| Line 81: | Line 94: | ||
\begin{aligned} | \begin{aligned} | ||
\delta_j^{(l)} | \delta_j^{(l)} | ||
&=\frac{\partial | &=\frac{\partial L}{\partial z_j^{(l)}}\\ | ||
&=\sum_k | &=\sum_k | ||
\frac{\partial | \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= | \qquad l=N-1,\dots,1. | ||
$$ | $$ | ||
{{End hidden}} | {{End hidden}} | ||
| Line 113: | Line 126: | ||
$$ | $$ | ||
\nabla_{\vec b^{(l)}} | \nabla_{\vec b^{(l)}}L=\vec{\delta}^{(l)}. | ||
$$ | $$ | ||
{{Hidden proof}} | {{Hidden proof}} | ||
$$ | $$ | ||
\delta_k^{(l)}=\frac{\partial | \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 | \frac{\partial L}{\partial b_j^{(l)}} | ||
= | = | ||
\sum_{k=0}^{n_l-1} | \sum_{k=0}^{n_l-1} | ||
\frac{\partial | \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)}} | \nabla_{\vec b^{(l)}}L=\vec{\delta}^{(l)}. | ||
$$ | $$ | ||
{{End hidden}} | {{End hidden}} | ||
| Line 148: | Line 161: | ||
$$ | $$ | ||
\nabla_{\mathbf{W}^{(l)}} | \nabla_{\mathbf{W}^{(l)}}L | ||
= | = | ||
\vec{\delta}^{(l)} | \vec{\delta}^{(l)} | ||
| Line 166: | Line 179: | ||
$$ | $$ | ||
\frac{\partial | \frac{\partial L}{\partial W_{ij}^{(l)}} | ||
= | = | ||
\sum_{k=0}^{n_l-1} | \sum_{k=0}^{n_l-1} | ||
\frac{\partial | \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)}} | \nabla_{\mathbf{W}^{(l)}}L | ||
= | = | ||
\vec{\delta}^{(l)} | \vec{\delta}^{(l)} | ||
| Line 185: | Line 198: | ||
{{End hidden}} | {{End hidden}} | ||
== Training == | === Training === | ||
Since | |||
$$ | $$ | ||
\begin{cases} | \begin{cases} | ||
\nabla_{\vec b^{(l)}} | \nabla_{\vec b^{(l)}}L=\vec{\delta}^{(l)},\\ | ||
\nabla_{\mathbf{W}^{(l)}} | \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}{ | \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}{ | \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 | # --- 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 | # 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 | # 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
$$ \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")