Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Neural Networks: Theory & Fundamentals

Open in Colab Open in Kaggle

Neural Networks: Theory & Fundamentals

From affine neurons to a complete NumPy backpropagation implementation

This notebook follows the lecture notation exactly: a mini-batch X∈RB×D\mathbf{X}\in\mathbb{R}^{B\times D} passes through a hidden layer of width HH and produces KK class probabilities.

Learning Objectives

By the end of this notebook, you will be able to:

  1. Trace tensor shapes through an MLP forward pass

  2. Explain why nonlinear hidden features solve problems that a linear model cannot

  3. Implement stable softmax and cross-entropy

  4. Derive and verify backpropagation with finite differences

  5. Train a two-layer neural network using only NumPy

  6. Diagnose the effects of learning rate and regularization from training curves

1. Setup and Locked Notation

We use:

  • BB: mini-batch size

  • DD: number of input features

  • HH: hidden width

  • KK: number of output classes

  • X:(B,D)\mathbf{X}:(B,D), W(1):(D,H)\mathbf{W}^{(1)}:(D,H), W(2):(H,K)\mathbf{W}^{(2)}:(H,K)

Matplotlib is building the font cache; this may take a moment.
Imports complete; random state = 42
 X: shape=(4, 3)
Z1: shape=(4, 5)
A1: shape=(4, 5)
Z2: shape=(4, 2)
 P: shape=(4, 2)
Probability row sums: [1. 1. 1. 1.]

The inner dimensions of every matrix product must agree. Bias vectors broadcast across the batch dimension. Softmax preserves the (B,K)(B,K) shape and normalizes each row.

2. Activations Create Nonlinear Features

Stacking affine transformations without an activation still produces one affine transformation. An activation changes the function class by bending the representation between layers.

<Figure size 1100x400 with 2 Axes>

A concrete representation: XOR

For binary inputs, two ReLU hidden features solve XOR exactly:

h1=ReLU⁡(x1+x2),h2=ReLU⁡(x1+x2−1),h_1=\operatorname{ReLU}(x_1+x_2),\qquad h_2=\operatorname{ReLU}(x_1+x_2-1),
y^=h1−2h2.\hat y=h_1-2h_2.

The hidden layer changes the representation so that a linear output can solve the transformed problem.

[[0. 0. 0. 0. 0.]
 [0. 1. 1. 0. 1.]
 [1. 0. 1. 0. 1.]
 [1. 1. 2. 1. 0.]]

3. Empirical Checkpoint: Linear Model vs MLP

The two-moons dataset is deliberately nonlinear. Both models receive the same standardized features; only their representational capacity differs.

Logistic regression test accuracy: 0.861
MLP test accuracy:                 0.894
<Figure size 1200x460 with 2 Axes>

4. Stable Softmax and Cross-Entropy

For one-hot targets Y\mathbf{Y}, the averaged cross-entropy is

L=−1B∑i=1B∑k=1Kyiklog⁡(pik+ε).\mathcal{L}=-\frac{1}{B}\sum_{i=1}^{B}\sum_{k=1}^{K}y_{ik}\log(p_{ik}+\varepsilon).

Subtracting each row’s maximum before exponentiation avoids overflow without changing softmax probabilities.

Stable probabilities:
 [[0.24472847 0.66524096 0.09003057]
 [0.25949646 0.70538451 0.03511903]]
Row sums: [1. 1.]
Cross-entropy: 0.378309090604823

5. Backpropagation in Matrix Form

For a ReLU hidden layer and softmax output:

G(2)=(P−Y)/B,\mathbf{G}^{(2)}=(\mathbf{P}-\mathbf{Y})/B,
∇W(2)L=A(1)⊤G(2),\nabla_{\mathbf{W}^{(2)}}\mathcal{L}=\mathbf{A}^{(1)\top}\mathbf{G}^{(2)},
G(1)=(G(2)W(2)⊤)⊙1[Z(1)>0],\mathbf{G}^{(1)}=(\mathbf{G}^{(2)}\mathbf{W}^{(2)\top})\odot\mathbf{1}[\mathbf{Z}^{(1)}>0],
∇W(1)L=X⊤G(1).\nabla_{\mathbf{W}^{(1)}}\mathcal{L}=\mathbf{X}^{\top}\mathbf{G}^{(1)}.

Bias gradients sum the corresponding G\mathbf{G} over the batch axis.

W1: parameter (3, 5), gradient (3, 5)
b1: parameter (5,), gradient (5,)
W2: parameter (5, 2), gradient (5, 2)
b2: parameter (2,), gradient (2,)

Gradient checking

Backpropagation is easy to implement incorrectly. A centered finite difference provides an independent numerical check:

gjnum=L(θj+ϵ)−L(θj−ϵ)2ϵ.g_j^{num}=\frac{\mathcal{L}(\theta_j+\epsilon)-\mathcal{L}(\theta_j-\epsilon)}{2\epsilon}.
Relative gradient error: 4.59e-11

6. A Complete NumPy MLP

The implementation below adds He initialization, mini-batch updates, L2L_2 regularization, deterministic shuffling, and training-history capture. Frameworks automate these pieces, but the underlying operations are the same.

Final training accuracy: 0.957
Test accuracy:           0.961
Parameter count: 82
<Figure size 1200x450 with 2 Axes>

7. Learning-Rate Experiment

Everything except the learning rate is held fixed. Compare both convergence speed and stability; the final loss alone does not tell the whole story.

<Figure size 800x450 with 1 Axes>
η=0.005 final loss=0.2816, test accuracy=0.889
η=0.05  final loss=0.1455, test accuracy=0.950
η=0.5   final loss=0.1294, test accuracy=0.961

8. Validation Curves and Early Stopping

The scikit-learn MLP reserved part of the training data for validation. Early stopping keeps training from continuing after validation performance stops improving.

<Figure size 1100x400 with 2 Axes>
Stopped after 93 iterations; best validation score = 0.881

9. Summary

  • A hidden activation prevents stacked affine layers from collapsing into one linear model.

  • Stable softmax and cross-entropy turn logits into a well-behaved multiclass objective.

  • Backpropagation is the chain rule applied efficiently in reverse.

  • Gradient checking validates the implementation before expensive training.

  • He initialization, standardized inputs, learning rate, and regularization all affect trainability.

  • Curves and error patterns are evidence; defaults are only starting points.

Exercises

  1. Replace ReLU with tanh in NumPyMLP; update both the forward and backward functions.

  2. Add momentum to the optimizer and compare convergence at the three learning rates.

  3. Sweep hidden width over H∈{2,4,16,64}H\in\{2,4,16,64\} and plot train/test accuracy.

  4. Make the two-moons noise level larger. Which intervention helps: width, regularization, or more data?

References