Skip to content
← writing

Hello world of neural networks

Oct 25, 2025 · 31 min read · ml, from-scratch

contents
  1. 1introduction
  2. 2neural network
  3. 3gradient descent
  4. 4backpropagation
  5. 5time 4 math
  6. 6loss vs accuracy graph:
  7. 7problems with gradient descent
  8. 8conclusion
  9. 9references

introduction

Neural Networks: understanding the brain, how people learn stuff, taking this idea and teaching it to a computer so it can learn on it's own..

perceptron

The idea of neural networks comes from the perceptron (Rosenblatt, 1958).

Perceptron

A feedforward neural network is a network of perceptrons. The outputs of one layer are the inputs to the next layer.

A perceptron can only make a linear decision boundary. Modern neural networks use multiple layers and non-linear activation functions to remove this limit.

problem statement

Given an image of a handwritten number, how do you identify the number?

We know what strokes a 2 has: a little horizontal line as a base and a slight curved S shaped line. We see that pattern at once. It is difficult to write it as exact rules for a computer.

How can we make a computer learn this?

Visual pattern recognition is hard to write as a program. Rules like "a 9 has a loop at the top, and a vertical stroke in the bottom right" fail when you try to make them exact.

The idea is:

  • Take a large number of handwritten digits (training data)
  • Build a system that learns from this data (it infers rules for recognizing handwritten digits)
  • Test the system on a new image. Measure how well it predicts.

framework

  • Each image is 28 * 28 pixels (each pixel is a number)
  • Each of these pixels has a weight value. The weight shows how much that pixel matters.
    • Example: in a '2', only the pixels on the horizontal base and the S shaped curve matter. All other pixels are dead weight.
    • A large weight means that the pixel matters a lot. Different weights and thresholds give different models of decision-making.
  • The network must learn the underlying pattern in these images and recognize what each image shows.
    • This happens by trial and error. At first, the network predicts garbage (this step is the forward pass)
    • Then the network decreases that error (this step is the backward pass)
  • Given a new image, how well can the neural network predict what number this image is?

basics revisited

  • Neuron: A thing that holds a number between 0 and 1, the activation value (grayscale: white is 1, black is 0)
  • Activation functions: Add non-linearity. Without them, the network is a stack of matrix multiplications.
    • Examples: Sigmoid, tanh, ReLU (more on these later. Think of them as math functions that transform your data x into f(x))
  • Weights: Determine the strength of connections.
  • Biases: Shift activations to improve flexibility.

bias and weights

bias: the intercept

Without bias, zero input forces zero output. That’s a problem because it means every line your model learns has to pass through the origin (0, 0).

Bias is the constant cc in y=mx+cy = mx + c. It shifts the output up or down. With it, the model can fit data that doesn’t pass through zero.

Mathematically: output=w1x1+w2x2+⋯+b\text{output} = w_1 x_1 + w_2 x_2 + \dots + b

weights: the slope

Weights determine the strength of the connection between inputs and outputs. They're the slope (m) in (y = mx + c): how much influence each input xix_i has on the output.

Large weights = this input matters a lot. Small weights = not so much. Training finds which inputs matter most.

neural network

  • Input : 784 neurons → Output : 10 neurons (Probability of number being that number (0 to 9))
  • In between hidden layers → the activation of the first layer determines the activation of the second layer, and so on... Similar to how neurons in our brain work.

Visually:

Neural Network Neural Network2

The training data is many 28 * 28 pixel images of scanned handwritten digits. Thus the input layer contains 784=28×28 neurons.

The input pixels are greyscale. A value of 0.0 is black, a value of 1.0 is white, and the values in between are shades of grey.

The second layer of the network is a hidden layer. We call the number of neurons in this hidden layer n, and we'll try different values for n. The example shows a small hidden layer with n=15 neurons.

The output layer of the network contains 10 neurons. If the first neuron fires, the network thinks the digit is a 0. If the second neuron fires, the network thinks the digit is a 1. And so on.

In these drawings, each neuron in one layer connects to every neuron in the next layer. Each activation has some influence on the activations in the next layer.

But not all connections are equal. Some connections are more equal than others (shoutout George Orwell). Training finds how strong each connection should be.

neural network setup

  • Think about y = mx + c: we know x (input) and y (expected output), and we're trying to learn m (weight) and c (bias).
  • Supervised ML problems follow this pattern. We have x (our sample training data) and y (the correct answers). We need to find m (weights) and c (bias) so that the model makes useful predictions.

Question: What happens in one layer?

  • First layer weights to next layer neuron : wiw_i

  • Inputs of first layer neurons : xix_i

  • Calculate slope line for all, y = mx + c = sum(wi∗xi+bi)sum(w_i*x_i + bi) (xix_i is replaced by aia_i here after 'activating' all inputs xix_i)

The weights tell you which pixel pattern this neuron in the second layer detects. The bias tells you how big the weighted sum must be before the neuron becomes active.

Basic equation → y = mx + c translates to y=sum(weights∗activations+bias)y = sum(weights * activations + bias) for all neurons. This y can be any real number, so it doesn't mean much yet. We squash it into a fixed range. That's where activation functions come in.

Many functions can do this. One of them is sigmoid, a function that maps any real number to a value between 0 and 1.

You put this sum(weights∗activations+bias)=zsum(weights * activations + bias) = z into the sigmoid activation function = sigmoid(z)sigmoid(z)

Once again:

  • Input : 28 * 28 = 784 neurons. Let's say I have 10 neurons in the second layer and 10 in the last layer.
  • Total : 784 * 10 weights + 10 biases (second layer), plus 10 * 10 weights + 10 biases (last layer) = 7,960, approximately 8000 weights and biases. Training tweaks all of them.

Learning: finding the right weights and biases, so that our network learns the underlying patterns of these numbers (the strokes).

The equation for a single neuron's output is: σ(∑iaiwi+b)\sigma\left(\sum_i a_i w_i + b\right) This is long to write for entire layers. Vectors and matrices from linear algebra make it shorter.

representing layers with vectors and matrices

  • Activations ((a)): We write the outputs from the previous layer as a single column vector:
a=[a0a1a2⋮an]a = \begin{bmatrix} a_0 \\ a_1 \\ a_2 \\ \vdots \\ a_n \end{bmatrix}
  • Weights ((W)): We put all the weights from the previous layer to the current layer into a single matrix:
W=[w0,0w0,1…w0,nw1,0w1,1…w1,n⋮⋮⋱⋮wk,0wk,1…wk,n]W = \begin{bmatrix} w_{0,0} & w_{0,1} & \dots & w_{0,n} \\ w_{1,0} & w_{1,1} & \dots & w_{1,n} \\ \vdots & \vdots & \ddots & \vdots \\ w_{k,0} & w_{k,1} & \dots & w_{k,n} \end{bmatrix}

Here, wj,iw_{j,i} is the weight connecting the ii-th neuron of the previous layer to the jj-th neuron of the current layer.

  • Biases ((b)): We write the biases of the current layer as a column vector:
b=[b0b1b2⋮bk]b = \begin{bmatrix} b_0 \\ b_1 \\ b_2 \\ \vdots \\ b_k \end{bmatrix}

Using this notation, the calculation for the pre-activation values zz of an entire layer becomes a matrix-vector operation:

z=Wa+bz = W a + b

Finally, to get the output activations of the current layer, we apply the sigmoid function σ\sigma element-wise:

a′=σ(z)=[σ(z0)σ(z1)σ(z2)⋮σ(zk)]a' = \sigma(z) = \begin{bmatrix} \sigma(z_0) \\ \sigma(z_1) \\ \sigma(z_2) \\ \vdots \\ \sigma(z_k) \end{bmatrix}

A neuron is a function. It takes the outputs of all neurons in the previous layer and spits out a number between 0 and 1.

Also no one uses sigmoid in hidden layers anymore.

They use ReLU(a)=max⁡(0,a)\text{ReLU}(a) = \max(0, a) (if any input is negative → make it 0, otherwise → let it be)

Why is this the case? The sigmoid function is flat at the extremes, when the weighted sum has a large magnitude. There its gradient is almost zero (tldr; relu is better, trust me)

With ReLU, wiggling a weight gives useful feedback whenever the neuron's input is positive.

Training becomes faster, especially with more layers (the “deep” in “deep learning” means many layers).

We assign a weight to each connection between our neuron and the neurons in the first layer. These weights are random numbers (for now).

Each weight is an indication of how its neuron in the first layer is correlated with this new neuron in the second layer.

Say the neuron in the first layer is on. A positive weight then suggests that the neuron in the second layer should also be on. A negative weight suggests that it should be off.

To compute the value of this second-layer neuron, take all the activations from the first layer and compute their weighted sum:

w1a1+w2a2+w3a3+w4a4+...+wn∗anw1a1 + w2a2 + w3a3 + w4a4 + ... + wn * an

Two ways to write this more formally:

writing in summation form

∑i=1nwiai\sum_{i=1}^{n} w_i a_i
  • ∑\sum is the Greek letter Sigma, which means "sum up."
  • i=1i = 1 below the Sigma indicates that the sum starts with the index ii equal to 1.
  • nn above the Sigma indicates that the sum ends when the index ii reaches nn.
  • wiaiw_i a_i is the expression for each term in the sum.

This notation says: "Sum the product of wiw_i and aia_i for all integer values of ii from 1 to nn."

writing in linear algebra (standard form)

In linear algebra this is the dot product of two vectors. This is how NumPy and PyTorch implement it.

First, we define a weight vector (W) and an activation (or input) vector (a):

W=[w1w2⋮wn],a=[a1a2⋮an]W = \begin{bmatrix} w_1 \\ w_2 \\ \vdots \\ w_n \end{bmatrix}, \quad a = \begin{bmatrix} a_1 \\ a_2 \\ \vdots \\ a_n \end{bmatrix}

The weighted sum is then the dot product W⋅aW \cdot a. Machine learning papers often write it as a matrix multiplication with a transpose:

WTaW^T a
  • WTW^T is the transpose of the vector WW, which turns the column vector into a row vector: [w1,w2,…,wn][w_1, w_2, \dots, w_n].
  • When you multiply the row vector WTW^T by the column vector aa, you get the exact same weighted sum:
WTa=[w1,w2,…,wn][a1a2⋮an]=w1a1+w2a2+⋯+wnanW^T a = [w_1, w_2, \dots, w_n] \begin{bmatrix} a_1 \\ a_2 \\ \vdots \\ a_n \end{bmatrix} = w_1 a_1 + w_2 a_2 + \dots + w_n a_n

So maybe the first layer detects the edges → the second layer detects the patterns → the final layer knows what number we have as input.

Image

So how does it learn? The whole point of training is to make the error as small as possible → How does it do that?

defining the error

How does a computer define error in a machine learning model?

There are multiple error functions. The basic one is:

error=y^−y{error} = \hat{y} - y

where,

  • y^\hat{y} = what our neural network predicts.
  • yy = the correct number for the image

Image2

Our job is to make these the same. That means we make the error as small as possible.

How do you minimize a function? Calculus.

gradient descent

One solution: start with random weights → calculate the error → tweak the weights and calculate the error again. (Expensive. It takes too much time to do this for all neurons and layers.)

Error is predicted_output (y') - actual_output (y), where

  • y′=output=w1x1+w2x2+⋯+by' = \text{output} = w_1 x_1 + w_2 x_2 + \dots + b

So y' depends on the weights and biases. That means the loss depends on the weights and biases (the parameters of the curve, to be precise).

This means our loss is a function of the parameters → hence the name loss function. So we need to find the configuration of these parameters that gives the minimum loss.

Put the coefficients that minimize the loss function into the curve equation. The result is the best description of the data.

How do we find these configurations? More importantly, how do we find the minimum loss of a function? We differentiate it.

We can change the weight/bias knobs one at a time and check whether the resulting curve is a better fit (This is bad. Slow. It does work though)

How can we be more intelligent?

Calculus. These curves are differentiable, so the derivative tells us the best knob settings much faster.

The computer tells us which direction to change the knob and by how much.

We are asking the computer to estimate the effect of knob adjustments on the loss function without trial & error.

revisiting the setup

Neural Network

  • Input: 784 numbers / pixels
  • Output: 10 numbers
  • Parameters: 8000 weights / biases

Initialize the weights and biases randomly.

Loss=(Predicted−Actual)2\text{Loss} = (\text{Predicted} - \text{Actual})^2

In expanded form

C=1N∑i=1N(y^i−yi)2C = \frac{1}{N} \sum_{i=1}^{N} (\hat{y}_i - y_i)^2

Why do we square it? We take the average of the errors. Positive and negative errors cancel out in an average. The cost then looks minimal when it's not. Hence the square.

Assume we send an image of '9'. The error is large when the network doesn't seem to know what it's doing. It is small when the prediction is close to 9.

The cost C(w,b)C(w, b) becomes small, C(w,b)≈0C(w,b) ≈ 0, when y^=y\hat{y} = y for all inputs x.

  • Input : The number 9
  • Output: Grey and white colors on multiple neurons (0-9)

This is what the output looks like

Output2

This is what we want

Output

What you gave me is utter trash (prediction), I need the output to be 9 (actual) ~ only cell 9 should fire.

So our training algorithm works if it finds weights and biases so that C(w,b)≈0.C(w,b) ≈ 0.

It does badly when C(w,b)C(w,b) is large.

The aim of our training algorithm is to minimize the cost C(w,b)C(w,b) as a function of the weights and biases.

Gradient descent updates the weights and biases step by step to minimize the cost function:

W←W−η∂C∂W,b←b−η∂C∂b\mathbf{W} \leftarrow \mathbf{W} - \eta \frac{\partial C}{\partial \mathbf{W}}, \quad \mathbf{b} \leftarrow \mathbf{b} - \eta \frac{\partial C}{\partial \mathbf{b}}

tuning knobs to minimize loss

Your model has one “knob” (parameter) ww. Turning it up or down changes the prediction, and thus the loss. We want to find the setting of ww that makes the loss as small as possible.

We take only one parameter, the weight, for now (let’s say the bias is fixed).

plotting loss vs. (ww)

  • Horizontal axis (xx) = parameter ww
  • Vertical axis (yy) = loss L(w)L(w)

This plot is a curve y=L(w)y=L(w). We want the minimum point on that curve.

Plot

the derivative

The derivative at a point tells us the instantaneous slope of the curve:

dLdw=lim⁡Δw→0L(w+Δw)−L(w)Δw\frac{dL}{dw} = \lim_{\Delta w \to 0} \frac{L(w + \Delta w) - L(w)}{\Delta w}
  • If dLdw>0\tfrac{dL}{dw} > 0, the curve is rising as we move right (loss increases if ww increases).
  • If dLdw<0\tfrac{dL}{dw} < 0, the curve is falling as we move right (loss decreases if ww increases).

ball on a hill

Picture a ball sitting on the curve. The derivative is “which way is downhill?”

  • If the slope is positive, the ball rolls left (decrease ww).
  • If the slope is negative, the ball rolls right (increase ww).

The gradient gives the direction of steepest ascent. So to minimize the function → take steps in the opposite direction.

the update rule

We take a small step opposite the slope:

w←w−η⏟learning ratedLdww \leftarrow w - \underbrace{\eta}_{\text{learning rate}} \frac{dL}{dw}
  • η\eta controls the step size.

  • We repeat: compute the slope, step downhill, repeat… until the slope is (nearly) zero.

same but for two variables k1 and k2 (weights and bias in our case)

How do we measure change with respect to multi variables? Multivariate calculus.

Partial derivatives: focus only on the variable you're differentiating with respect to. Treat everything else like a constant.

Now suppose we have two knobs (k1,k2)(k_1, k_2).

We measure how the loss changes if we wiggle one parameter at a time:

∂L∂k1and∂L∂k2\frac{\partial L}{\partial k_1} \quad \text{and} \quad \frac{\partial L}{\partial k_2}
  • ∂L∂k1\tfrac{\partial L}{\partial k_1} = rate of change if we nudge k1k_1 while keeping k2k_2 fixed.
  • ∂L∂k2\tfrac{\partial L}{\partial k_2} = rate of change if we nudge k2k_2 while keeping k1k_1 fixed.

the gradient vector

Collect these partials into the gradient:

∇L=[∂L∂k1∂L∂k2]\nabla L = \begin{bmatrix} \dfrac{\partial L}{\partial k_1} \\ \dfrac{\partial L}{\partial k_2} \end{bmatrix}
  • This points in the direction of steepest ascent on the loss surface.
  • To go downhill, we move in the opposite direction.

updating again

[k1k2]←[k1k2]−η ∇L=[k1k2]−η [∂L∂k1∂L∂k2]\begin{bmatrix} k_1 \\ k_2 \end{bmatrix} \leftarrow \begin{bmatrix} k_1 \\ k_2 \end{bmatrix} - \eta\, \nabla L = \begin{bmatrix} k_1 \\ k_2 \end{bmatrix} - \eta\, \begin{bmatrix} \tfrac{\partial L}{\partial k_1} \\ \tfrac{\partial L}{\partial k_2} \end{bmatrix}

And in nn-dimensional parameter space k=(k1,…,kn)\mathbf{k}=(k_1,\dots,k_n):

k←k−η ∇L(k),∇L(k)=[∂L∂k1⋮∂L∂kn]\mathbf{k} \leftarrow \mathbf{k} - \eta\, \nabla L(\mathbf{k}), \quad \nabla L(\mathbf{k}) = \begin{bmatrix} \dfrac{\partial L}{\partial k_1} \\ \vdots \\ \dfrac{\partial L}{\partial k_n} \end{bmatrix}

Continuing with our ball rolling example:

  1. Draw the loss as a surface over your parameters (the hill).
  2. Compute the (partial) derivatives. They tell you “uphill” vs. “downhill.”
  3. Step downhill: subtract a fraction (the learning rate) of each derivative from its parameter.
  4. Repeat until you reach a flat spot (derivative ≈ 0), i.e. a minimum.

Gradient descent: “roll the ball downhill, one small step at a time.”

The derivative gives us the slope and the direction to adjust our weight. We do not need to test each change on the whole network.

Question: How do we change these weights and biases to make the network better?

Answer: Shift the parameters to the left if the slope is positive. Shift them to the right if the slope is negative.

The parameters here are the inputs of the cost function (weights and biases).

If you keep repeating → you approach a local minimum of the function (ball rolling down a hill : lowest point)

Bowl

We need to reach the bottom of the bowl.

The learning rate η\eta controls the step size. Big learning rate = big steps, might overshoot the minimum. Small learning rate = small steps, stable but slow.

Gradient descent is an algorithm that finds the minimum of the cost function. It takes small steps in the direction that decreases the cost function the most.

Which direction decreases C(weights, bias) the fastest?

The gradient of a function gives you the direction of steepest increase (the direction to step to increase the function the fastest).

The negative of the gradient gives you the direction that decreases the function the fastest : WHAT WE WANT

Image3

Algorithm:

  • Compute G(Cost Function) (G is the gradient)
  • Take a small step in the opposite direction of the gradient : the -Gradient(C) direction.
  • Repeat.
python
def gradient_descent_pure_python(learning_rate=0.1, num_iterations=100):
    """
    Minimizes the function f(x) = x^2 using gradient descent.
    The derivative f'(x) = 2x.
    """
    weight = 10.0  # Initial guess for x
 
    print(f"Starting x: {weight}, f(x): {weight**2:.4f}")
 
    for i in range(num_iterations):
        gradient = 2 * weight # x^2 derivative is 2x
 
        # Update weight by moving in the negative direction of the gradient
        weight = weight - learning_rate * gradient
 
        if (i + 1) % 10 == 0 or i == 0:
            print(
                f"Iteration {i+1}: x = {weight:.4f}, f(x) = {weight**2:.4f}, "
                f"Gradient = {gradient:.4f}"
            )
 
    print(f"\nOptimization finished. Minimum found at x = {weight:.4f}")
    print(f"Minimum function value f(x) = {weight**2:.4f}")

Output

text
smol@samit ~  > python3 a.py
Starting x: 10.0, f(x): 100.0000
Iteration 1: x = 8.0000, f(x) = 64.0000, Gradient = 20.0000
Iteration 10: x = 1.0737, f(x) = 1.1529, Gradient = 2.6844
Iteration 20: x = 0.1153, f(x) = 0.0133, Gradient = 0.2882
Iteration 30: x = 0.0124, f(x) = 0.0002, Gradient = 0.0309
Iteration 40: x = 0.0013, f(x) = 0.0000, Gradient = 0.0033
Iteration 50: x = 0.0001, f(x) = 0.0000, Gradient = 0.0004
Iteration 60: x = 0.0000, f(x) = 0.0000, Gradient = 0.0000
Iteration 70: x = 0.0000, f(x) = 0.0000, Gradient = 0.0000
Iteration 80: x = 0.0000, f(x) = 0.0000, Gradient = 0.0000
Iteration 90: x = 0.0000, f(x) = 0.0000, Gradient = 0.0000
Iteration 100: x = 0.0000, f(x) = 0.0000, Gradient = 0.0000
Optimization finished. Minimum found at x = 0.0000
Minimum function value f(x) = 0.0000

The minimum of f(x)=x2f(x) = x^2 is at x = 0, f(x) = 0.

Here we only optimized the weight because it was the only parameter. Our original line equation has 2 parameters : weights and biases. We need to optimize both.

How do you differentiate a function and find its minimum with respect to 2 parameters? Partial derivatives BAM. Hell yeah.

∂C∂W(l)=δ(l)(a(l−1))T,∂C∂b(l)=δ(l)\frac{\partial C}{\partial \mathbf{W}^{(l)}} = \delta^{(l)}(a^{(l-1)})^T, \quad \frac{\partial C}{\partial \mathbf{b}^{(l)}} = \delta^{(l)} Compute gradients:∂C∂W,∂C∂b\text{Compute gradients:} \quad \frac{\partial C}{\partial W}, \quad \frac{\partial C}{\partial b} Gradient-descent update:W←W−η ∂C∂W,b←b−η ∂C∂b\text{Gradient-descent update:} \quad W \leftarrow W - \eta\,\frac{\partial C}{\partial W}, \qquad b \leftarrow b - \eta\,\frac{\partial C}{\partial b}

We use a learning rate of 0.1 or 0.01. Small steps keep us from moving too fast. With big steps, we might miss the bottom of the bowl and jump to the other side.

Each component of the negative gradient vector tells us two things:

  • The sign tells us whether to nudge the corresponding parameter up or down.
  • The relative magnitudes of the components tell us which of those changes matters more.

Backpropagation calculates the gradients (derivatives) that gradient descent needs to update the weights of a neural network.

backpropagation

The forward pass goes from input layer -> hidden layer -> output layer and finds the error. Then we "backpropagate" from output layer -> hidden layer -> input layer. On the way, we calculate the partial derivatives and update the weights and biases to minimize the error.

How does it calculate error, what do you mean? Why does this work? What is learning? Which weights and biases minimize a certain cost function?

Algorithm for computing the gradient: Don't be scared by these equations they don't mean shit for now, but it'll make sense later. If you know enough math to understand this in the first go,,,, why are you still reading this?

δL=(y^−y)⊙σ′(zL)\delta^{L} = (\hat{\mathbf{y}} - \mathbf{y}) \odot \sigma'(z^{L}) δl=((W(l+1))Tδ(l+1))⊙σ′(z(l))\delta^{l} = ((\mathbf{W}^{(l+1)})^T \delta^{(l+1)}) \odot \sigma'(z^{(l)}) ∂C∂W(l)=δ(l)(a(l−1))T\frac{\partial C}{\partial \mathbf{W}^{(l)}} = \delta^{(l)} (a^{(l-1)})^T ∂C∂b(l)=δ(l)\frac{\partial C}{\partial \mathbf{b}^{(l)}} = \delta^{(l)}

Fuck this, that's what I said to myself when I saw it

Focus on one example: Input 2. Let's say these are our activations from random weights and biases.

Activations

0 : 0.5
1 : 0.8
2 : 0.2
3 : 1.0 (white)
4 : 0.4
5 : 0.6
6 : 1.0 (white)
7 : 0.0 (black)
8 : 0.2
9 : 0.1

This is utter trash like we talked about. We want it to be like:

Activations

0 : 0.0
1 : 0.0
2 : 1.0 (white)
3 : 0.0
4 : 0.0
5 : 0.0
6 : 0.0
7 : 0.0
8 : 0.0
9 : 0.0

We want to nudge that third value up and all others down.

The size of each nudge should be proportional to how far the current value is from the target value.

For example:

  • An increase in the number 2 activation is more important than a decrease in the number 8 neuron (which is already 0.2, close to 0)

So let's take neuron 2 0.2 = σ(∑nwnan+b)\sigma\left(\sum_n w_n a_n + b\right)

What can we change:

  • Increase bias.
  • Increase weights.
  • Change activations from the previous layer.

It makes sense to increase each weight in proportion to the activation of the previous-layer neuron it comes from.

If a previous-layer neuron already has a high activation, its weight has the most effect on neuron 2. So you increase that weight the most.

We increase the weights of the neurons that contribute the most to neuron 2.

Similarly, we change the activations of the previous layer in proportion to the weights.

The biggest increases in weights (the biggest strengthening of connections) happen between the most active neurons and the neurons we want to become more active.

In practice, it's time consuming for the computer to calculate all gradients and update the weights for ALL training data. Hence we use stochastic (randomized) gradient descent, where we:

  • Shuffle the training data.
  • Randomly split it into mini batches.
  • Go through all mini batches and make these adjustments. Repeat until the loss stops decreasing.

Increase the bias of the digit-2 neuron. This increases the activation of the digit-2 neuron. Decrease the biases of all other output neurons. This decreases their activations.

Backpropagation Error Flow

Backpropagation Error Flow

time 4 math

Feel free to skip this part if you are not going to make it.

Backprop Chain Rule

Backpropagation is an algorithm for calculating the gradient of the cost function of a network.

The entries of the gradient vector are the partial derivatives of the cost function with respect to the weights and biases.

Once you know how sensitive the cost function is to the activations in the second-to-last layer, repeat the process for the weights and biases that feed into that layer.

Backpropagation uses matrix multiplication, derivatives and the chain rule.

  • Matrix multiplication computes each layer's values from the previous layer. Each weight scales its input up or down.
  • The cost function turns “learning” into “find the minimum.” Derivatives point us downhill.
  • The chain rule shows how a small tweak to any weight changes each later layer and the cost.

So what do these scary equations mean?

Consider a simple neural network → 4 neurons connected by 3 links. Hence 4 activations, 3 weights and 3 biases (one for each neuron except the first) Simple NN

Goal

  • How sensitive is the cost function to these variables?
  • Which knobs do we turn to make the cost function minimal?

We're going to focus only on the activations of the last 2 neurons.

We combine the weight, previous activation, and bias to compute the pre-activation:

z=∑iwiai+bz = \sum_i w_i a_i + b

Then the sigmoid activation function takes zz:

a=σ(z)a = \sigma(z)

Finally, we use the activation aa and the true label yy to compute the cost (e.g., with mean squared error or cross-entropy).

We compute a(L−1)a^{(L-1)} from:

  • its own weights and biases,
  • and activations from the previous layer a(L−2)a^{(L-2)},

and this pattern repeats backward through the network all the way to the input.

Each layer’s output becomes the next layer’s input, all the way to the final cost.

Image1 Image2 Image3

sensitivity of the cost to a single weight

Our goal is to measure how a tiny change (“nudge”) in one weight in the last layer, w(L)w^{(L)}, affects the loss CC.
In calculus terms we want the partial derivative:

∂C∂w(L)\frac{\partial C}{\partial w^{(L)}}

When you see ∂w(L)\partial w^{(L)}, think “a small nudge to w(L)w^{(L)}”;
when you see ∂C\partial C, think “the resulting nudge to the cost.”
Their ratio ∂C∂w(L)\tfrac{\partial C}{\partial w^{(L)}} is the instantaneous rate of change of the loss with respect to that weight.


1. chain rule decomposition

Because CC depends on w(L)w^{(L)} only through the pre-activation z(L)z^{(L)} and the activation a(L)a^{(L)}, the chain rule gives

∂C∂w(L)=∂C∂a(L)  ×  ∂a(L)∂z(L)  ×  ∂z(L)∂w(L).\frac{\partial C}{\partial w^{(L)}} = \frac{\partial C}{\partial a^{(L)}} \;\times\; \frac{\partial a^{(L)}}{\partial z^{(L)}} \;\times\; \frac{\partial z^{(L)}}{\partial w^{(L)}}.

A neat trick to check this: cancel each denominator with the next numerator, from the start. You'll get the original derivative. (This is a memory aid, not a proof.)


2. individual derivatives

  1. Pre-activation
z(L)=w(L)a(L−1)+b(L)⟹∂z(L)∂w(L)=a(L−1).z^{(L)} = w^{(L)}a^{(L-1)} + b^{(L)} \quad\Longrightarrow\quad \frac{\partial z^{(L)}}{\partial w^{(L)}} = a^{(L-1)}.
  1. Activation (sigmoid)
a(L)=σ(z(L))⟹∂a(L)∂z(L)=σ′(z(L))=σ(z(L))(1−σ(z(L))).a^{(L)} = \sigma\left(z^{(L)}\right) \quad\Longrightarrow\quad \frac{\partial a^{(L)}}{\partial z^{(L)}} = \sigma'\left(z^{(L)}\right) = \sigma\left(z^{(L)}\right)\left(1 - \sigma\left(z^{(L)}\right)\right).
  1. Loss for one example (Mean Squared Error)
C0=(a(L)−y)2⟹∂C0∂a(L)=2(a(L)−y).C_0 = \left(a^{(L)} - y\right)^2 \quad\Longrightarrow\quad \frac{\partial C_0}{\partial a^{(L)}} = 2\left(a^{(L)} - y\right).

3. combined gradient

Putting it all together,

∂C0∂w(L)=2(a(L)−y)⏟∂C0∂a(L)  ×  σ′ ⁣(z(L))⏟∂a(L)∂z(L)  ×  a(L−1)⏟∂z(L)∂w(L)  =  2 (a(L)−y) σ′ ⁣(z(L)) a(L−1).\frac{\partial C_0}{\partial w^{(L)}} = \underbrace{2\bigl(a^{(L)} - y\bigr)}_{\frac{\partial C_0}{\partial a^{(L)}}} \;\times\; \underbrace{\sigma'\!\bigl(z^{(L)}\bigr)}_{\frac{\partial a^{(L)}}{\partial z^{(L)}}} \;\times\; \underbrace{a^{(L-1)}}_{\frac{\partial z^{(L)}}{\partial w^{(L)}}} \;=\; 2\,\bigl(a^{(L)} - y\bigr)\,\sigma'\!\bigl(z^{(L)}\bigr)\,a^{(L-1)}.

This tells us how a small change in w(L)w^{(L)} for one training example will change the loss.


4. averaging over the dataset

For NN training examples, we average these per-example gradients to get the gradient of the full cost CC:

∇C=1N∑i=1N∂C(i)∂w(L).\nabla C = \frac{1}{N}\sum_{i=1}^{N} \frac{\partial C^{(i)}}{\partial w^{(L)}}.

5. update rule (gradient descent)

Finally, we update the weight by stepping opposite to the gradient:

w(L)  ←  w(L)  −  η ∂C∂w(L),w^{(L)} \;\leftarrow\; w^{(L)} \;-\;\eta\, \frac{\partial C}{\partial w^{(L)}},

where η\eta is the learning rate.
Likewise for the bias:

b(L)  ←  b(L)  −  η ∂C∂b(L).b^{(L)} \;\leftarrow\; b^{(L)} \;-\;\eta\, \frac{\partial C}{\partial b^{(L)}}.

stochastic gradient descent:

When your dataset is large, it is slow to compute the exact gradient
∇C=1N∑i=1N∇C(i)\displaystyle \nabla C = \frac{1}{N}\sum_{i=1}^N \nabla C^{(i)}
on all NN examples for each update.
Stochastic gradient descent (SGD) is faster. It estimates the true gradient with a small random mini-batch of m≪Nm\ll N examples:

∇Cbatch=1m∑i∈batch∇C(i).\nabla C_{\text{batch}} = \frac{1}{m}\sum_{i\in\text{batch}}\nabla C^{(i)}.
  1. Sample a mini-batch of mm training examples at random.
  2. Compute the average gradient ∇Cbatch\nabla C_{\text{batch}}.
θ←θ−η∇Cbatch\theta \leftarrow \theta - \eta \nabla C_{\text{batch}}

where η\eta is the learning rate.

why it works

  • Cost per update falls from O(N)O(N) to O(m)O(m).
  • Unbiased estimate: E[∇Cbatch]=∇C\mathbb{E}[\nabla C_{\text{batch}}] = \nabla C.

Think of it like political polling: poll 1,000 voters (a mini-batch) instead of the entire electorate (the full dataset). The average still points in the right direction.


partial derivative w.r.t. bias

For a neuron with pre-activation

z=W x  +  b,z = W\,x \;+\; b,

the bias bb enters linearly, so

∂z∂b  =  1    ⟹    ∂C∂b=∂C∂z ∂z∂b=∂C∂z.\frac{\partial z}{\partial b} \;=\; 1 \;\;\Longrightarrow\;\; \frac{\partial C}{\partial b} = \frac{\partial C}{\partial z}\,\frac{\partial z}{\partial b} = \frac{\partial C}{\partial z}.

the full gradient vector

We’ve seen how to compute two entries of the gradient vector for the last layer:

  1. Weight gradient
∂C∂W(L)=δ(L) (a(L−1))⊤\frac{\partial C}{\partial W^{(L)}} = \delta^{(L)}\,(a^{(L-1)})^{\top}
  1. Bias gradient
∂C∂b(L)=δ(L)\frac{\partial C}{\partial b^{(L)}} = \delta^{(L)}

where δ(L)=∂C∂z(L)\delta^{(L)} = \tfrac{\partial C}{\partial z^{(L)}}.

We propagate these errors backward through the network and multiply along the chain of dependencies. This gives every partial derivative ∂C∂w\tfrac{\partial C}{\partial w} and ∂C∂b\tfrac{\partial C}{\partial b} for every layer. Stacking them gives the gradient vector:

∇C  =  [⋮∂C∂w1∂C∂b1⋮].\nabla C \;=\; \begin{bmatrix} \vdots \\ \displaystyle \frac{\partial C}{\partial w_1} \\ \displaystyle \frac{\partial C}{\partial b_1} \\ \vdots \end{bmatrix}.

Once we have ∇C\nabla C, we perform gradient descent (or SGD)
to step downhill and minimize the loss:

θ  ←  θ  −  η ∇C.\theta \;\leftarrow\; \theta \;-\;\eta\,\nabla C.

The components of the gradient vector tell us which adjustments to make.

If for a particular configuration:

  • The partial derivative of the loss with respect to k1 is positive, an increase in k1 increases the loss.
  • Hence we decrease k1 (the opposite sign of the gradient) to decrease the loss.

How do we compute the derivative of the loss function in the first place?

The chain rule tells us how to compute the derivative of a function that is itself the input to another function. In symbols, if

h(x)=f(g(x)),h(x) = f\bigl(g(x)\bigr),

then

ddxh(x)=ddx[f(g(x))]=f′(g(x))  ⋅  g′(x).\frac{d}{dx}h(x) = \frac{d}{dx}\bigl[f\bigl(g(x)\bigr)\bigr] = f'\bigl(g(x)\bigr)\;\cdot\;g'(x).

intuition: two “machines” in series

  1. Machine 1

    • Input: xx
    • Output: g(x)g(x)
    • Local slope: g′(x)g'(x)
  2. Machine 2

    • Input: u=g(x)u = g(x)
    • Output: f(u)f(u)
    • Local slope: f′(u)f'(u)

When you feed xx into the first machine, it spits out g(x)g(x).
That becomes the input to the second machine, which outputs f(g(x))f\bigl(g(x)\bigr).

small nudge argument

  1. Nudge xx by a tiny amount Δx\Delta x.
  2. Machine 1 outputs
g(x+Δx)≈g(x)+g′(x) Δxg(x + \Delta x) \approx g(x) + g'(x)\,\Delta x

So the change in its output is

Δu≈g′(x) Δx,\Delta u \approx g'(x)\,\Delta x,

where u=g(x)u = g(x).

  1. Machine 2 then sees its input change by Δu\Delta u, so its output changes by
f(u+Δu)≈f(u)+f′(u) Δuf(u + \Delta u) \approx f(u) + f'(u)\,\Delta u
  1. Combined change in the final output:
Δh=f′(g(x)) Δu≈f′(g(x)) [g′(x) Δx]=[f′(g(x)) g′(x)] Δx\Delta h = f'\bigl(g(x)\bigr)\,\Delta u \approx f'\bigl(g(x)\bigr)\,\bigl[g'(x)\,\Delta x\bigr] = \bigl[f'\bigl(g(x)\bigr)\,g'(x)\bigr]\,\Delta x
  1. Dividing by Δx\Delta x and taking the limit Δx→0\Delta x \to 0 gives the chain rule:
ddxf(g(x))=f′(g(x))⋅g′(x)\frac{d}{dx}f\bigl(g(x)\bigr) = f'\bigl(g(x)\bigr) \cdot g'(x)

why this matters for neural networks

Backpropagation is many of these compositions chained together. Each layer’s output feeds into the next layer’s activation function.

The chain rule lets us multiply all the local derivatives together to find how the final loss changes with respect to any parameter deep in the network.

For the full chain rule derivation with worked examples and more calculus, see the math post.

Next, we calculate the derivative of the cost function with respect to the weights and bias for a simple sigmoid-activated neuron.

We want the gradient of our cost function, here the mean squared error (MSE), with respect to the weights ww and bias bb.

1. Define the building blocks:

  • Input features: XX (a vector or matrix of input values, x1,x2,…,xnx_1, x_2, \dots, x_n)
  • Weights: WW (a vector of weights, w1,w2,…,wnw_1, w_2, \dots, w_n)
  • Bias: bb (a single scalar value)
  • Activation function: sigmoid,
σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}
  • The derivative of the sigmoid function is
σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z))
  • Actual labels: YY (the true output values)

2. The forward pass

  • The linear combination (weighted sum + bias) is the input to the activation function.
z=X⋅W+bz = X \cdot W + b

In code, this is z = np.dot(features, weights) + bias. This is a sum of xiwix_i w_i for all input features, plus the bias.

  • To get the predicted output (y_hat), apply the sigmoid activation function to (z).
y^=σ(z)\hat{y} = \sigma(z)

In code, this is predictions = sigmoid(z). This is your predicted_output.

  • The cost function (mean squared error, MSE) measures how "wrong" our prediction is. For a single training example, the error is:
(y^i−yi)2(\hat{y}_i - y_i)^2

For multiple samples, we take the mean.

C=MSE=1N∑i=1N(y^i−yi)2C = \text{MSE} = \frac{1}{N} \sum_{i=1}^N (\hat{y}_i - y_i)^2

In code, this is mse = np.mean((predictions - labels) ** 2). This is your Cost.

We call the calculation of zz, y^\hat{y}, and CC the forward pass.

z(l)=W(l)a(l−1)+b(l),a(l)=σ(z(l))z^{(l)} = \mathbf{W}^{(l)} a^{(l-1)} + \mathbf{b}^{(l)}, \quad a^{(l)} = \sigma(z^{(l)})
python
# forward pass
z = np.dot(features, weights) + bias # sum(wx + b)
predictions = sigmoid(z) # apply sigmoid function to this (this is y_hat)
mse = np.mean((predictions - labels) ** 2) # take mean square error (this is C)
mse_values.append(round(mse, 4)) # add it to mean square error list

3. The backward pass

Now, we use the chain rule to find how the cost CC changes with respect to each weight wjw_j and the bias bb.
The chain rule writes a complex derivative as a product of simpler ones.

We want to find ∂C∂wj\frac{\partial C}{\partial w_j} and ∂C∂b\frac{\partial C}{\partial b}.

Let's trace the dependencies backward from (C)

C←y^←z←(W,b)C \leftarrow \hat{y} \leftarrow z \leftarrow (W, b)

First, the derivative of the Cost with respect to the Predicted Output (y^)(\hat{y})

∂C∂y^=∂∂y^(1N∑(y^i−yi)2)=1N∑2(y^i−yi)\frac{\partial C}{\partial \hat{y}} = \frac{\partial}{\partial \hat{y}} \left( \frac{1}{N} \sum (\hat{y}_i - y_i)^2 \right) = \frac{1}{N} \sum 2(\hat{y}_i - y_i)

In code, error = predictions - labels. So, ∂C∂y^\frac{\partial C}{\partial \hat{y}} is proportional to 2 * error. When we take the mean over NN samples, it becomes 2N×sum of errors\frac{2}{N} \times \text{sum of errors}

Second, the derivative of the Predicted Output (y^\hat{y}) with respect to zz:

This is the derivative of the sigmoid function.

∂y^∂z=∂∂zσ(z)=σ(z)(1−σ(z))\frac{\partial \hat{y}}{\partial z} = \frac{\partial}{\partial z} \sigma(z) = \sigma(z)(1 - \sigma(z))

In code, this is sigmoid_derivative = predictions * (1 - predictions).

Combining the first two steps to get (∂C∂z)(\frac{\partial C}{\partial z})

Using the chain rule ∂C∂z=∂C∂y^⋅∂y^∂z\frac{\partial C}{\partial z} = \frac{\partial C}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial z}

∂C∂z=(2N∑(y^i−yi))⋅σ(zi)(1−σ(zi))\frac{\partial C}{\partial z} = \left( \frac{2}{N} \sum (\hat{y}_i - y_i) \right) \cdot \sigma(z_i)(1 - \sigma(z_i))

In code, delta = error * sigmoid_derivative calculates (predictions - labels) * sigmoid_derivative for each sample. We apply the (2/len(labels)) factor later, when we average over samples. So, delta represents (y^−y)⋅σ′(z)(\hat{y} - y) \cdot \sigma'(z) for each sample.

Now, for the final gradients:

Derivative of Cost with respect to a Weight wjw_j: Using the chain rule: ∂C∂wj=∂C∂z⋅∂z∂wj\frac{\partial C}{\partial w_j} = \frac{\partial C}{\partial z} \cdot \frac{\partial z}{\partial w_j} We know that z=X⋅W+b=x1w1+x2w2+⋯+xjwj+⋯+xnwn+bz = X \cdot W + b = x_1 w_1 + x_2 w_2 + \dots + x_j w_j + \dots + x_n w_n + b

So, ∂z∂wj=xj\frac{\partial z}{\partial w_j} = x_j

Therefore

∂C∂wj=(2N∑(y^i−yi)⋅σ(zi)(1−σ(zi)))⋅xij\frac{\partial C}{\partial w_j} = \left( \frac{2}{N} \sum (\hat{y}_i - y_i) \cdot \sigma(z_i)(1 - \sigma(z_i)) \right) \cdot x_{ij}

(where (xij(x_{ij} is the jj-th feature for the ii-th sample).

In code: partial_derivative_error_wrt_weights = (2 / len(labels)) * np.dot(features.T, delta) This np.dot(features.T, delta) computes the sum

∑deltai⋅xij\sum \text{delta}_i \cdot x_{ij}

for all features, which is what the formula requires.

Derivative of Cost with respect to the Bias (b):

Using the chain rule ∂C∂b=∂C∂z⋅∂z∂b\frac{\partial C}{\partial b} = \frac{\partial C}{\partial z} \cdot \frac{\partial z}{\partial b}

We know z=X⋅W+bz = X \cdot W + b

So ∂z∂b=1\frac{\partial z}{\partial b} = 1 Therefore

∂C∂b=(2N∑(y^i−yi)⋅σ(zi)(1−σ(zi)))⋅1\frac{\partial C}{\partial b} = \left( \frac{2}{N} \sum (\hat{y}_i - y_i) \cdot \sigma(z_i)(1 - \sigma(z_i)) \right) \cdot 1 ∂C∂b=2N∑(y^i−yi)⋅σ(zi)(1−σ(zi))\frac{\partial C}{\partial b} = \frac{2}{N} \sum (\hat{y}_i - y_i) \cdot \sigma(z_i)(1 - \sigma(z_i))

In code partial_derivative_error_wrt_bias = (2 / len(labels)) * np.sum(delta) This np.sum(delta) calculates ∑deltai\sum \text{delta}_i over all samples. Multiplied by 2 / len(labels), it gives the 2N∑\frac{2}{N} \sum that the formula requires.

Calculate error at the output

δ(L)=(y^−y)⊙σ′(z(L))\delta^{(L)} = (\hat{\mathbf{y}} - \mathbf{y}) \odot \sigma'(z^{(L)})

Propagate errors backward:

Code for the Backward Pass:

python
error = predictions - labels # This is (y' - y) for each sample
sigmoid_derivative = predictions * (1 - predictions) # This is sigma'(z) for each sample
delta = error * sigmoid_derivative # This is (y' - y) * sigma'(z) for each sample
 
# Calculate the partial derivatives (gradients) of the Cost with respect to weights and bias
# partial_derivative_error_wrt_weights corresponds to dC/dW
# partial_derivative_error_wrt_bias corresponds to dC/db
partial_derivative_error_wrt_weights = (2 / len(labels)) * np.dot(features.T, delta)  # using chain rule
partial_derivative_error_wrt_bias = (2 / len(labels)) * np.sum(delta) # using chain rule
 
# update weights and bias using the calculated gradients (Gradient Descent step)
weights -= learning_rate * partial_derivative_error_wrt_weights
bias -=  learning_rate * partial_derivative_error_wrt_bias
gradients = [] # assume this is a matrix which just stores all results of dC/dw and dC/db
gradients.append((weights, bias))

We call it backward because the gradients propagate sensitivity backward, from the output layer to the input layer.

Once we have these gradients, we're going to tweak the parameters based on the loss function gradient.

Tweak the knobs a little, opposite to the gradient. updatedWeight=weight−learningRate∗[partial(Cost)/partial(weight)]updatedWeight = weight - learningRate * [partial(Cost) / partial(weight)]

After each adjustment, we redo the forward and backward passes because the parameters have changed.

This loop:

  • Forward pass
  • Backward pass
  • Nudge knobs
  • Repeat 1-3

is how modern machine learning systems train.

If you can write your fancy model as a sequence of differentiable functions, you can apply backprop to optimize the parameters.

why is it fast?

Why not brute-force the gradient? You could treat the cost as a function of the weights, C=C(w). Then estimate ∂C/∂wj by computing the cost C for two values of wj that differ by a tiny amount. Bump each weight by a tiny amount and see what happens.

1. bruteforce gradient descent

To estimate ∂C∂wj\tfrac{\partial C}{\partial w_j} by finite differences, you’d do

∂C∂wj≈C(w+ε ej)  −  C(w)ε,\frac{\partial C}{\partial w_j} \approx \frac{C\bigl(w + \varepsilon\,e_j\bigr)\;-\;C(w)}{\varepsilon},

where eje_j is the unit vector in direction jj. If you have (N) weights, that requires N+1N+1 full forward-passes through the network per training example!

2. backpropagation via the chain rule

Backprop avoids that explosion by computing all partial derivatives
∂C∂wj\tfrac{\partial C}{\partial w_j} at once with:

  1. One forward pass (compute all activations).
  2. One backward pass (propagate “error signals” and multiply local derivatives).

2.1 Small-Change Analysis

A small change Δwl,j,k\Delta w_{l,j,k} in weight wl,j,kw_{l,j,k} causes a small change in the neuron’s activation:

Δal,j≈∂al,j∂wl,j,k Δwl,j,k.\Delta a_{l,j} \approx \frac{\partial a_{l,j}}{\partial w_{l,j,k}}\, \Delta w_{l,j,k}.

That, in turn, changes the next layer’s activation:

Δal+1,q≈∂al+1,q∂al,j Δal,j.\Delta a_{l+1,q} \approx \frac{\partial a_{l+1,q}}{\partial a_{l,j}}\, \Delta a_{l,j}.

… and so on, all the way to the cost (C):

ΔC≈∂C∂wl,j,k Δwl,j,k.\Delta C \approx \frac{\partial C}{\partial w_{l,j,k}}\, \Delta w_{l,j,k}.

2.2 Chain Rule for a Single Weight

By following every path from wl,j,kw_{l,j,k} to the final cost,
and multiplying the local partials along each edge,
then summing over all such paths, you get:

∂C∂wl,j,k=∑paths p∏edges (u→v)∈p∂v∂u.\frac{\partial C}{\partial w_{l,j,k}} = \sum_{\text{paths }p} \prod_{\substack{\text{edges }(u\to v)\\\in p}} \frac{\partial v}{\partial u}.

Backpropagation is a dynamic-programming implementation of this sum-of-products in linear time O(N)O(N), rather than O(N2)O(N^2) or worse.


  • Finite differences need O(N)O(N) forward passes for NN weights → slow.
  • Backpropagation needs 1 forward pass + 1 backward pass → fast.
  • Backpropagation uses the chain rule to share and reuse intermediate derivatives.
    It computes the entire gradient vector ∇C\nabla C in one backward pass.

Michael Nielsen describes it like this in Neural Networks and Deep Learning:

"Backpropagation algorithm as providing a way of computing the sum over the rate factor for all these paths. Or, to put it slightly differently, the backpropagation algorithm is a clever way of keeping track of small perturbations to the weights (and biases) as they propagate through the network, reach the output, and then affect the cost."

coding time coding time coding time

Let's build a program that identifies numbers from handwritten images.

about the dataset

MNIST: 60,000 training images and 10,000 test images of handwritten digits. Scanned from 250 people: half Census Bureau employees, half high school students.

MNIST

Greyscale, 28x28 pixels. The test data comes from a different set of 250 people, so we know the network can generalize to handwriting it's never seen before.

What we want it to predict (Ideal Output)

Output

MNIST from scratch (using NumPy)

python
import numpy as np
"""
if we want to create a Network object with 2 neurons in the first layer, 3 neurons in the second layer, and 1 neuron in the final layer:
    net = Network([2, 3, 1])
 
net.weights[1] is a Numpy matrix storing the weights connecting the second and third layers of neurons (Python counts from 0)
"""
class Network:
    def __init__(self, sizes) -> None:
        ''' This creates a network with layers and indicates how many neurons in each layer (sizes)'''
        self.num_layers = len(sizes)
        self.sizes = sizes
        # randomly initialize the weights and bias
        self.bias = [np.random.randn(y, 1) for y in sizes[1:]]
        self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])]
 
    def sigmoid(self, z) -> float:
        ''' Activation function to convert probability in range 0 -> 1 '''
        return 1.0 / (1.0 + np.exp(-z))
        # relu : return max(0, z) 
 
    def sigmoid_derivative(self, z) -> float:
        ''' Derivative of sigmoid : we need this for calculating partial derivative of cost function '''
        return self.sigmoid(z) * (1 - self.sigmoid(z)) 
 
    def forward(self, activation) -> float:
        ''' Return output of neural network '''
        for b, w in zip(self.bias, self.weights):
            activation = self.sigmoid(np.dot(w, activation) + b) # sigmoid(wx + b) (wx = dot product if you think about how matrix works)
        return activation
 
    def SGD(self, training_data, epochs, mini_batch_size, learning_rate, test_data=None):
        """
        Train the neural network using mini-batch stochastic gradient descent.  
        The "training_data" is a list of tuples "(x, y)" representing the training inputs and the desired outputs.
        If "test_data" is provided then the network will be evaluated against the test data after each epoch, and partial progress printed out.
        epochs is just a fancy name for number of iterations.
        """
        if test_data:
            n_test = len(test_data)
        n = len(training_data) # otherwise
        for epoch in range(epochs):
            np.random.shuffle(training_data)
            mini_batches = [training_data[k : k + mini_batch_size] for k in range(0, n, mini_batch_size)]
            # for each mini_batch we apply a single step of gradient descent
            for mini_batch in mini_batches:
                self.update_mini_batch(mini_batch, learning_rate)
            
            if test_data:
                accuracy = self.evaluate(test_data)
                accuracy_percentage = (accuracy / n_test) * 100
                print( f"Epoch {epoch}: {accuracy} / {n_test}") 
            else:
                print(f"Epoch {epoch} complete") 
 
        if test_data:
            print(f"Accuracy : {accuracy_percentage:.2f}%")
            
    def update_mini_batch(self, mini_batch, learning_rate):
        ''' Update weights and biases by applying Gradient Descent to single mini batch (list of tuples (x,y) representing training inputs and their desired outputs for this mini batch) '''
        # initialize gradients to 0
        # the sum of the gradients of the loss function with respect to the biases for all examples in the mini-batch.
        sum_of_bias_gradients = [np.zeros_like(b) for b in self.bias]
        sum_of_weight_gradients = [np.zeros_like(w) for w in self.weights]
        # Calculate gradient for each example in mini batch.
        for x, y in mini_batch:
            grad_b, grad_w = self.backprop(x, y)
            # update sum of bias and weight gradients (elementwise addition for gradients)
            # the overall gradient used to update the weights and biases is the average of the gradients computed for each individual training example within that mini-batch.
            sum_of_bias_gradients = [bias_sum + gradient_bias for bias_sum, gradient_bias in zip(sum_of_bias_gradients, grad_b)]
            sum_of_weight_gradients = [weight_sum + gradient_weight for weight_sum, gradient_weight in zip(sum_of_weight_gradients, grad_w)]
        
        mini_batch_size = len(mini_batch)
        learning_rate_scaled = learning_rate / mini_batch_size
        # update weights and biases using avg gradients
        self.weights = [
            w - learning_rate_scaled * weight_sum
            for w, weight_sum in zip(self.weights, sum_of_weight_gradients)
        ]
 
        self.bias = [
            b - learning_rate_scaled * bias_sum
            for b, bias_sum in zip(self.bias, sum_of_bias_gradients)
        ]
 
    def backprop(self, x, y):
        """
        Calculates the gradient for the cost function C_x
        for a single training example (x, y) using backpropagation.
 
        Args:
            x (np.ndarray): The input feature vector.
            y (np.ndarray): The true label/target output vector.
 
        Returns:
            tuple[list[np.ndarray], list[np.ndarray]]: A tuple containing
            (grad_b, grad_w), which are layer-by-layer lists of numpy
            arrays representing the gradients for biases and weights,
            respectively.
        """
        grad_b, grad_w = [np.zeros_like(b) for b in self.bias], [np.zeros(w.shape) for w in self.weights]
        # forward pass
        # input layer activation and list to store all activations (layer by layer)
        activation = x
        activations = [x]
        all_z = [] # list to store all zs = (wx + b) and activation is basically sigmoid(z)
        for b, w in zip(self.bias, self.weights):
            z = np.dot(w, activation) + b
            all_z.append(z)
            activation = self.sigmoid(z)
            activations.append(activation)
 
        # backward pass
        # activations[-1] is the output layer's activation (by output layer I mean last layer)
        # all_z[-1] is the weighted input for the output layer
        error = self.cost_derivative(activations[-1], y) * self.sigmoid_derivative(all_z[-1])
        # update last layers
        grad_b[-1] = error
        grad_w[-1] = np.dot(error, activations[-2].T) # a^(L-2) * error = partial derivative of cost wrt weight of last layer
 
        # Iterate backward through the layers (from second-to-last to input)
        # We iterate in reverse order of layers (from output towards input).
        # Layer 1 is the first hidden layer (weights[0], biases[0]).
        # Layer L-1 is the last hidden layer (weights[-2], biases[-2]).
        for layer_idx in reversed(range(self.num_layers - 1)):
            # skip last layer (we handled that above)
            if layer_idx == self.num_layers - 2: 
                continue 
            z = all_z[layer_idx]
            sd = self.sigmoid_derivative(z)
            # Error propagation: delta for current layer from delta of next layer
            error = np.dot(self.weights[layer_idx + 1].T, error) * sd
 
            # Gradients for current layer's biases and weights
            grad_b[layer_idx] = error
            grad_w[layer_idx] = np.dot(error, activations[layer_idx].T)
 
        return grad_b, grad_w
 
    
    def cost_derivative(self, output_activations, y):
        ''' Return prediction - actual '''
        return output_activations - y
 
 
    def evaluate(self, test_data):
        ''' Return the number of test inputs for which the network outputs correct result '''
        test_results = [
                        (np.argmax(self.forward(x)), y) for (x, y) in test_data
                        ]
        return sum(int(x == y) for (x, y) in test_results)
 
training_data, validation_data, testing_data = mnist_loader.load_data_wrapper()
 
# 784 input image pixels, 30 hidden neurons, 10 output neurons consisting of probability of images
net = network.Network([784, 30, 10])
 
# use stochastic gradient descent to learn from the MNIST training_data over 30 epochs, with a mini-batch size of 10, and a learning rate of η = 0.01
net.SGD(training_data, 30, 10, 0.01, test_data=testing_data)
 
# Predicting new image
def preprocess_image(image_path):
    """
    Loads an image, converts to grayscale, resizes to 28x28,
    normalizes pixels, and reshapes to (784, 1) numpy array.
    """
    try:
        img = Image.open(image_path).convert('L') # grayscale
        img = img.resize((28, 28)) 
        img_array = np.array(img) 
 
        # MNIST pixels are 0 (black) to 255 (white).
        # Flatten and transpose to (784, 1) column vector
        img_vector = np.reshape(img_array, (784, 1)) / 255.0
        return img_vector
 
    except FileNotFoundError:
        print(f"Error: Image file not found at {image_path}")
        return None
    except Exception as e:
        print(f"Error processing image {image_path}: {e}")
        return None
 
image_path = Path(__file__).parent / "data" / "sample_digit.jpg"
processed_image = preprocess_image(image_path)
if processed_image is not None:
    output_activation = net.forward(processed_image)
    prediction = np.argmax(output_activation) # idx of neuron with highest activation
    print("\nNetwork Output Activations (confidence for each digit 0-9):")
    for i, val in enumerate(output_activation.flatten()):
            print(f"  Digit {i}: {val * 100:.2f}%")
    print(f"\nPredicted digit: {prediction}")
else:
    print("Could not make a prediction due to image processing error.")
 
 

We test it on this sample image:

9

Output

text
Epoch 0: 2718 / 10000
Epoch 1: 3465 / 10000
Epoch 2: 3928 / 10000
Epoch 3: 4300 / 10000
Epoch 4: 4650 / 10000
Epoch 5: 5049 / 10000
Epoch 6: 5531 / 10000
Epoch 7: 5907 / 10000
Epoch 8: 6255 / 10000
Epoch 9: 6504 / 10000
Epoch 10: 6704 / 10000
Epoch 11: 6888 / 10000
Epoch 12: 7043 / 10000
Epoch 13: 7165 / 10000
Epoch 14: 7266 / 10000
Epoch 15: 7358 / 10000
Epoch 16: 7441 / 10000
Epoch 17: 7508 / 10000
Epoch 18: 7583 / 10000
Epoch 19: 7661 / 10000
Epoch 20: 7722 / 10000
Epoch 21: 7793 / 10000
Epoch 22: 7830 / 10000
Epoch 23: 7878 / 10000
Epoch 24: 7914 / 10000
Epoch 25: 7957 / 10000
Epoch 26: 7991 / 10000
Epoch 27: 8052 / 10000
Epoch 28: 8073 / 10000
Epoch 29: 8119 / 10000
Accuracy : 81.19% (It means it predicted 8119 images correctly out of 10000)
 
Network Output Activations (probability for each digit 0-9):
  Digit 0: 0.21%
  Digit 1: 0.08%
  Digit 2: 0.06%
  Digit 3: 0.53%
  Digit 4: 17.36%
  Digit 5: 2.49%
  Digit 6: 2.85%
  Digit 7: 0.12%
  Digit 8: 48.34%
  Digit 9: 70.89% # highest
 
Predicted digit: 9 # HELL YEAH

This is why PyTorch/TensorFlow exist. They do this calculus for you (automatic differentiation).

basic model in libraries like PyTorch/TensorFlow

python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
 
# Define a transform to normalize the data
transform = transforms.Compose([
    transforms.ToTensor(), # Converts image to tensor and scales to [0, 1]
    transforms.Normalize((0.1307,), (0.3081,)) # Standardize with MNIST's mean and std
])
 
# Download and load the training, testing data
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
 
# Load data
train_loader = DataLoader(dataset=train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=1000, shuffle=False)
 
class PyTorchNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.inp_to_hidden = nn.Linear(784, 128) # inp to hidden layer
        self.relu = nn.ReLU() # activation function
        self.hidden_to_pred = nn.Linear(128, 10) # hidden to output layer
 
    # Takes input
    def forward(self, x):
        x = self.inp_to_hidden(x)
        x = self.relu(x)
        x = self.hidden_to_pred(x)
        return x 
 
model = PyTorchNet()
loss = nn.CrossEntropyLoss() # target - pred 
 
optimizer = optim.Adam(model.parameters(), lr=0.01) # weights = (weights - learning_rate) * derivative
 
epochs = 2000
for epoch in range(epochs):
    for xb, yb in train_loader:
        optimizer.zero_grad() # reset weights to 0 after each batch so that they are updated correctly
        pred = model(xb) # calculate prediction
        final_loss = loss(pred, yb) # loss of prediction
        final_loss.backward() # apply backpropagation to this 
        optimizer.step() # update weights correctly
    if epoch % 500 == 0: # every 500th iteration : print loss
        print(f"Epoch {epoch}, Loss : {final_loss.item():.4f}")
 
# prediction
with torch.no_grad():
    pred = model(features)
    probs = torch.softmax(pred, dim=1)
    prediction = torch.argmax(probs, dim=1) # take the highest probability (example : correct digit in our MNIST example)
    print("\nPredicted class probabilities:\n", probs) # probability of each class (example : 0 - 9 all digit probabilities)
    print("Predicted classes:", prediction) # predicted outputs
    print("True classes:", targets) # actual outputs

MNIST from MiniTorch (custom implementation of PyTorch)

MiniTorch

python
import numpy as np
from minitorch.tensor import Tensor
from minitorch.layers import Linear, ReLU
from minitorch.loss import cross_entropy_loss
from minitorch.optim import SGD, Adam
 
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
 
def run_mnist_example():
    print("Fetching MNIST data...")
    mnist = fetch_openml('mnist_784', version=1)
    X = mnist.data.astype(np.float32) / 255.0
    y = mnist.target.astype(np.int64)
    # converting data to usable data (between 0 to 1 etc...)
    X_train_all, X_test_all, y_train_all, y_test_all = train_test_split(
        X, y, test_size=0.2, random_state=42
    )
    X_train = X_train_all[:1000]
    y_train = y_train_all[:1000]
    X_test = X_test_all[:200]
    y_test = y_test_all[:200]
 
    def one_hot(labels, num_classes=10):
        oh = np.zeros((labels.shape[0], num_classes), dtype=np.float32)
        oh[np.arange(labels.shape[0]), labels] = 1.0
        return oh
 
    y_train_oh = one_hot(y_train, 10)
    y_test_oh = one_hot(y_test, 10)
 
    X_t = Tensor(X_train, requires_grad=False)
    y_t = Tensor(y_train_oh, requires_grad=False)
 
    # defining layers (wx + b) and activation functions
    layer1 = Linear(784, 128)
    relu = ReLU()
    layer2 = Linear(128, 10)
 
    params = layer1.parameters() + layer2.parameters()
    opt = SGD(params, lr=0.01, momentum=0.9)
 
    epochs = 10
    batch_size = 100
    num_batches = X_train.shape[0] // batch_size
 
    print("Training")
 
    for epoch in range(epochs):
        epoch_loss = 0.0
        for i in range(num_batches):
            start = i * batch_size
            end = start + batch_size
            xb = Tensor(X_train[start:end], requires_grad=False)
            yb = Tensor(y_train_oh[start:end], requires_grad=False)
            # forward pass
            out1 = layer1(xb)
            act1 = relu(out1)
            logits = layer2(act1)
            loss = cross_entropy_loss(logits, yb) # calculate loss
            # backward pass
            # we do .zero_grad() to reset all the gradients since we don't want gradients of previous layer to affect this new layer
            opt.zero_grad()
            loss.backward()
            opt.step()
 
            epoch_loss += loss.data
 
        avg_loss = epoch_loss / num_batches
        print(f"Epoch {epoch+1}/{epochs}, Loss: {avg_loss:.4f}")
 
    X_test_t = Tensor(X_test, requires_grad=False)
    out1_test = layer1(X_test_t)
    act1_test = relu(out1_test)
    logits_test = layer2(act1_test)
    preds = np.argmax(logits_test.data, axis=1)
    accuracy = np.mean(preds == y_test) # checking if what we predicted = real output
    print(f"Test Accuracy: {accuracy * 100:.2f}%")
 
if __name__ == "__main__":
    run_mnist_example()

Output

output
(.venv) smol@samit ~/fun/minitorch git:(master) > python3 mnist_example.py 
Fetching MNIST data...
Training
Epoch 1/10, Loss: 71.2395
Epoch 2/10, Loss: 24.0194
Epoch 3/10, Loss: 11.0858
Epoch 4/10, Loss: 6.6417
Epoch 5/10, Loss: 4.4537
Epoch 6/10, Loss: 3.4053
Epoch 7/10, Loss: 2.5522
Epoch 8/10, Loss: 1.8609
Epoch 9/10, Loss: 1.4868
Epoch 10/10, Loss: 1.0654
Test Accuracy: 78.50% # I know this sucks, can improve it via CNN, but it works.

Output

MiniTorch/PyTorch/TensorFlow follow the same pattern. They compute gradients with the chain rule and use them to update the weights. (MiniTorch does this on NumPy arrays. PyTorch and TensorFlow use their own tensor libraries.)

For better results, use a CNN (Convolutional Neural Network). A CNN has multiple stages of feature extraction before classification. Video for more.

At a quick glance:

CNN

  • Input: 28 * 28 pixel image.

  • Convolution layer: slides a filter (3x3 matrix) over this image and multiplies at each position. The result is a new matrix. The network learns filter values that detect the underlying patterns of the image (in this case, the strokes)

*A 3x3 kernel slides across the input image, computing a dot product at each position to produce the feature map.*
  • Max pooling: keeps the largest value in each small window. This reduces the size of the image (14 * 14 now)

  • Another convolution layer and another max pooling layer identify more patterns. At the end, we have 64 images of 7 * 7. We flatten them into a single array of 7 * 7 * 64 = 3136 numbers

  • After flattening, a dense layer outputs 10 numbers (0 to 9). The number with the highest activation / probability is the prediction (what number our image is)

loss vs accuracy graph:

AccuracyLoss

Loss goes down, accuracy goes up over time.

Neural networks use chain rule calculus and matrix multiplications to learn the right parameters (weights and biases).

problems with gradient descent

vanishing gradient problem

What happens when you backprop through a lot of layers? You're using sigmoid (0 to 1) or tanh (-1 to 1) to squash numbers, then multiplying their derivatives together with the chain rule.

If you have A LOT of layers, the gradient is almost 0 when it reaches the early weights. They barely learn.

Sigmoid derivatives are already small (at most 0.25). Multiply many small numbers together during backprop (0.25×0.25×0.25…0.25 \times 0.25 \times 0.25 \dots) and the result vanishes fast.

Early layers get an almost zero gradient signal. Network learns nothing. Cool.

*Gradients shrink exponentially through layers with sigmoid activation. ReLU and residual connections solve this by keeping gradients strong.*

dead neuron problem

If the weighted sum going into a ReLU neuron is negative for every training input, ReLU always outputs 0 (f(a)=max(0,a)f(a) = max(0, a)). Output is 0 means derivative is 0. Derivative is 0 means gradient is 0. Gradient is 0 means weights never update.

The neuron is dead. Permanently. Always outputs 0, never learns, never contributes. Sitting there taking up space.

Fix: Leaky ReLU, which never fully zeroes out.

f(x)={xif x>0αxif x≤0f(x) = \begin{cases} x & \text{if } x > 0 \\ \alpha x & \text{if } x \leq 0 \end{cases}

Where:

  • xx: Input to the activation function.
  • α\alpha: A small positive constant (e.g., 0.010.01) that determines the slope for negative input values.

conclusion

The same machinery runs an LLM like ChatGPT. Its output is a probability distribution over all tokens (word pieces) in its vocabulary.

LLMs have billions of parameters. They start random, and training on text refines them. Backpropagation tweaks all of them so the model becomes a little more likely to pick the right next word instead of a wrong one.

Example: I am going to the bank to deposit some _

Probabilities : money, cash, blood, ashes, etc... (Actual last word here is money)

A good video on this: LLMs explained

Image classification and text generation (GPT) use these same ideas at the core.

Transformers and attention also learn weights that minimize a loss.

The code for all of this is here → MNIST

references

reply by email

related