v9.1.1
Menu

Chapter 9: Neural Networks

Week 17-18

Build the foundation of modern deep learning from first principles. Understand how perceptrons combine into multi-layer networks, how activation functions enable non-linear learning, how backpropagation efficiently computes gradients, and how optimizers navigate the loss landscape.

Topics
4
Demos
4
Min read
34

Chapter Overview

Neural networks are universal function approximators—with enough neurons, they can learn to represent any continuous function. This remarkable capability, combined with efficient training via backpropagation, sparked the deep learning revolution.

The basic unit is the perceptron: a weighted sum of inputs passed through a non-linear activation function. Individual perceptrons can only learn linear boundaries, but stacking them into layers creates Multi-Layer Perceptrons (MLPs) that learn arbitrarily complex patterns.

The key insight that made training deep networks practical is backpropagation: by applying the chain rule of calculus, we can efficiently compute how the loss changes with respect to every weight in the network. This transforms learning from an intractable search problem into gradient descent optimization.

Modern neural networks wouldn't work without careful engineering: activation functions prevent vanishing gradients, weight initialization ensures healthy signal flow, and adaptive optimizers like Adam automatically tune learning rates per parameter.

Understanding these fundamentals is essential before moving to specialized architectures like CNNs, RNNs, and Transformers. The same principles—forward passes, loss functions, gradients, and optimization—apply throughout deep learning.

This chapter covers:

  • Perceptrons & MLPs: From single neurons to deep multi-layer networks with universal approximation capability
  • Activation Functions: Non-linear functions that enable learning complex patterns and their properties
  • Backpropagation: The algorithm that makes deep learning tractable by efficiently computing gradients
  • Optimizers: Methods for navigating loss landscapes, from basic SGD to adaptive algorithms like Adam

Chapter Roadmap

Click any topic to jump in

Interactive demo
1
Perceptrons & MLPs

Single neurons to multi-layer networks — weighted sums, activation functions, and the universal approximation theorem.

PerceptronMulti-Layer PerceptronHidden LayersWeight Initialization
Enabling non-linearity and learning

Activation and gradient computation

2
Activation Functions

Non-linear functions that enable learning complex patterns — ReLU, sigmoid, softmax, and the vanishing gradient problem.

ReLU (Rectified Linear Unit)SigmoidSoftmaxLeaky ReLU
3
Backpropagation

The chain rule applied to neural networks — efficiently computing gradients from output to input for weight updates.

Chain RuleForward PassBackward PassGradient Descent Update
Training deep networks efficiently
4
Optimizers

Navigating loss landscapes with SGD, momentum, and Adam — adaptive learning rates and convergence strategies.

SGD (Stochastic Gradient Descent)MomentumAdamLearning Rate Schedules

Topics

4 topics in this chapter

The previous chapter, Clustering, found structure without labels. This chapter returns to supervised learning with a harder question. Every model so far, from logistic regression to SVMs, needed us to supply the right features or the right kernel. What if the raw inputs are pixels or audio samples, and nobody knows which combinations of them matter? Can a model learn its own features from data? This chapter, Neural Networks, answers yes by stacking many simple units and training them all at once.

This topic builds the basic unit and the first network. We start with the perceptron, a weighted sum plus a threshold, and see both what it can learn (any linearly separable rule, such as AND) and what it cannot (XOR). Stacking perceptrons into a multi-layer perceptron fixes that, and hidden layers learn intermediate features. The topic closes with weight initialization, the detail that decides whether a deep stack trains at all. The next topics cover activation functions, backpropagation, and optimizers.

Definition

A perceptron computes y=f(wTx+b)y = f(\mathbf{w}^T\mathbf{x} + b): a weighted sum of inputs plus a bias, passed through an activation function ff. A multi-layer perceptron (MLP) composes fully connected layers of such units, hl=f(Wlhl−1+bl)\mathbf{h}_l = f(W_l \mathbf{h}_{l-1} + \mathbf{b}_l), so hidden layers compute learned features that the output layer combines into a prediction.

In this topic

  1. 1Perceptron
  2. 2Multi-Layer Perceptron
  3. 3Hidden Layers
  4. 4Weight Initialization
1 of 4
Perceptron

y=f(∑iwixi+b)=f(wTx+b)y = f(\sum_{i} w_i x_i + b) = f(\mathbf{w}^T \mathbf{x} + b)

A perceptron takes inputs xix_i, multiplies each by a weight wiw_i, adds a bias bb, and passes the sum z=wTx+bz = \mathbf{w}^T\mathbf{x} + b through an activation ff. With a step function, it outputs 1 when z≥0z \geq 0 and 0 otherwise. Geometrically, z=0z = 0 is a hyperplane with normal vector w\mathbf{w}, so a single perceptron is a linear classifier, like logistic regression from earlier chapters. Rosenblatt's learning rule nudges the weights toward each misclassified point and is guaranteed to converge when the classes are linearly separable. The failure mode is the converse: no single perceptron can learn XOR, whose classes no line separates.

Mathematical Intuition

A perceptron computes y=f(wTx+b)y = f(\mathbf{w}^T \mathbf{x} + b), which geometrically defines a hyperplane in Rn\mathbb{R}^n that separates two classes. The weight vector w\mathbf{w} is the normal to this hyperplane, and the bias bb shifts it by b/∥w∥b / \|\mathbf{w}\| from the origin. The perceptron convergence theorem guarantees convergence in at most (R/γ)2(R / \gamma)^2 updates, where RR is the data radius and γ\gamma is the margin — but only if the data is linearly separable.

Example:

Perceptron with w=[2, -1], b=0.5, x=[3, 2]. Using step function f(z)=1 if z≥0, else 0. Output?

2 of 4
Multi-Layer Perceptron

A multi-layer perceptron stacks layers: an input layer, one or more hidden layers, and an output layer. Each layer is fully connected to the next, computing hl=f(Wlhl−1+bl)\mathbf{h}_l = f(W_l \mathbf{h}_{l-1} + \mathbf{b}_l), where WlW_l has one row per unit in layer ll and one column per unit in layer l−1l-1. A layer with ninn_{in} inputs and noutn_{out} outputs therefore has ninnoutn_{in} n_{out} weights and noutn_{out} biases. Hidden units let the network combine simple decision boundaries into complex ones, which solves XOR. The universal approximation theorem says one wide enough hidden layer can approximate any continuous function, but it says nothing about how many units that takes or how to train them.

Mathematical Intuition

An MLP with LL layers computes the composition fL∘fL−1∘⋯∘f1(x)f_L \circ f_{L-1} \circ \cdots \circ f_1(\mathbf{x}), where each fi(h)=σ(Wih+bi)f_i(\mathbf{h}) = \sigma(W_i \mathbf{h} + \mathbf{b}_i). The universal approximation theorem states that a single hidden layer with enough neurons can approximate any continuous function on a compact set to within any ϵ\epsilon, but the number of neurons may need to be exponentially large. Depth helps: Telgarsky (2016) constructs functions computed by networks with Θ(k3)\Theta(k^3) layers of constant width that any network with only O(k)O(k) layers can approximate only with Ω(2k)\Omega(2^k) units.

Example:

MLP: 4 inputs, hidden layer with 8 neurons, output layer with 3 neurons. How many weights (excluding biases)?

3 of 4
Hidden Layers

Hidden layers learn intermediate representations that are not in the data. Each layer applies an affine map followed by a nonlinearity, so later layers build features out of earlier ones: in an image model, edges, then textures, then parts. Without the nonlinearity, any stack of layers collapses to a single linear map, adding nothing. Depth is efficient: some functions computable by a deep, narrow network need exponentially many units in a shallow one. Yet very deep plain networks are hard to train because gradients shrink or grow through many layers, which is why initialization, ReLU, normalization, and residual connections matter. Width and depth are hyperparameters, chosen on validation data.

Mathematical Intuition

Each hidden layer applies an affine transformation followed by a pointwise non-linearity, mapping Rdl−1→Rdl\mathbb{R}^{d_{l-1}} \to \mathbb{R}^{d_l}. The composition of LL such layers can represent functions with O(2L)O(2^L) linear regions — exponentially more expressive than a single layer. This is why deeper networks can learn more complex decision boundaries with fewer total parameters.

Example:

For classifying MNIST digits (28×28 images, 10 classes), suggest a simple MLP architecture.

4 of 4
Weight Initialization

Weights must start random, because identical weights receive identical gradients and units never differentiate. The scale matters as much as the randomness. Each layer multiplies the signal's variance by roughly ninVar(w)n_{in}\mathrm{Var}(w), where ninn_{in} is the fan-in, the number of inputs to a unit. If that factor is below 1, activations shrink toward zero layer after layer; if it is above 1, they explode. Xavier (Glorot) initialization sets Var(w)\mathrm{Var}(w) near 1/nin1/n_{in} for tanh and sigmoid layers. He initialization uses 2/nin2/n_{in} for ReLU, doubling the variance because ReLU zeroes half its inputs. Biases usually start at zero.

Mathematical Intuition

He initialization draws weights from N(0,2/nin)\mathcal{N}(0, 2/n_{\text{in}}), a variance of 2/nin2/n_{\text{in}} and so a standard deviation of 2/nin\sqrt{2/n_{\text{in}}}. It comes from requiring the variance of pre-activations to stay constant across layers: Var(zl)=nin Var(w) E[hl−12]\text{Var}(z_l) = n_{\text{in}}\,\text{Var}(w)\,\mathbb{E}[h_{l-1}^2], and ReLU zeroes half its inputs, so the factor of 2 compensates. Xavier initialization uses variance 1/nin1/n_{\text{in}} (or 2/(nin+nout)2/(n_{\text{in}} + n_{\text{out}})) for tanh and sigmoid. Poor scale makes signals vanish or explode exponentially in depth.

Example:

Layer has 512 inputs. Using He initialization for ReLU, what's the weight standard deviation?

Theory Exercise

Problem:

A single perceptron cannot learn the XOR function. Why not, and how does adding a hidden layer fix this?

Hints:
  • What kind of decision boundary can a single perceptron produce?
  • Plot the XOR truth table — are the classes linearly separable?
  • What can a hidden layer build that a single neuron cannot?

Coding Exercise

Problem:

Build a small MLP in PyTorch (2→8→1 with ReLU) and train it to learn the XOR function, demonstrating that a hidden layer succeeds where a single linear unit fails.

Hints:
  • XOR inputs are the 4 corners [[0,0],[0,1],[1,0],[1,1]] with targets [0,1,1,0]
  • Use nn.Sequential(nn.Linear(2,8), nn.ReLU(), nn.Linear(8,1)) and BCEWithLogitsLoss
  • Train for a few hundred steps with Adam, then threshold the sigmoid outputs at 0.5