---
title: Neural networks
heading: Feedforward networks as adaptive basis functions, hidden units and their activation functions, a forward pass by hand, softmax outputs for several classes, how ReLU units build piecewise-linear functions and solve XOR, and counting parameters and operations
eyebrow: S14 · Lesson 24 · Neural networks
xp: 50
---

::: hook
The linear models of lessons 9 to 17 use fixed basis functions, and lesson 9 showed how fast a fixed basis grows with the input dimension. A neural network lets the data choose its basis: each hidden unit is a basis function with its own adjustable weights, and the output combines them. With enough hidden units, a single hidden layer can approximate any continuous function, and in practice deeper networks do it with far fewer units. The price is that the error is no longer a quadratic in the weights, which is lessons 25 and 26's problem.
:::

::: play
- A one-input network with three ReLU hidden units, $\text{ReLU}(a) = \max(0, a)$, combined with output weights 1, −2 and 1, builds a "hat" bump of height h centered at c with half-width w.
- Each hidden unit contributes a hinge. Sums of hinges are piecewise-linear functions, and sums of bumps can approximate any curve.
- That's the idea behind the universal approximation theorem, made concrete.
:::

```sim plot
view: graph
x: x = -4..4
y: y = -0.5..3
slider: c = -2..2 step 0.1 = 0
slider: w = 0.2..3 step 0.1 = 1
slider: h = 0.5..2.5 step 0.1 = 2
plot: h/w*((x - c + w + abs(x - c + w))/2 - (x - c + abs(x - c)) + (x - c - w + abs(x - c - w))/2) | samples: 600 | label: network output
plot: h/w*(x - c + w + abs(x - c + w))/2 | samples: 600 | dashed | color: ch3 | label: first hidden unit
readout: bump area = h*w | digits: 3
```

::: predict
## A network computes $h_1 = \text{ReLU}(x_1 + x_2)$, $h_2 = \text{ReLU}(x_1 + x_2 - 1)$ and $y = h_1 - 2h_2$ for binary inputs. What function is y?

- [ ] AND
- [ ] OR
- [x] XOR
- [ ] NAND

::: reveal
(0, 0) gives 0 − 0 = 0; (1, 0) and (0, 1) give 1 − 0 = 1; (1, 1) gives 2 − 2 = 0. That's XOR, which no single linear threshold can compute. The hidden layer remaps the inputs so a linear output can separate them.
:::
:::

::: nameit
## The two-layer network

$$y_k(\mathbf{x}) = f\left(\sum_{j=1}^Hw^{(2)}_{kj}\,h\left(\sum_{i=1}^Dw^{(1)}_{ji}x_i + b^{(1)}_j\right) + b^{(2)}_k\right)$$

The **hidden units** $z_j = h(a_j)$ apply a nonlinear **activation**: the logistic sigmoid, tanh, or the **ReLU** max(0, a), now the default because its gradient doesn't fade for large inputs. Without a nonlinearity, layers collapse to one linear map.

## Output units

The output activation f matches the task: identity for regression (with squared error), sigmoid for two classes, and for K classes the **softmax**

$$y_k = \frac{e^{a_k}}{\sum_je^{a_j}}$$

with the cross-entropy loss of lesson 4.

## Size and cost

A D–H–K network has $(D + 1)H + (H + 1)K$ parameters, and a forward pass costs about $DH + HK$ multiply-accumulates. A one-input ReLU layer of H units produces at most H + 1 linear pieces; stacking layers multiplies the pieces, which is one reason depth helps.

## Universal approximation

A network with one hidden layer and enough units can approximate any continuous function on a bounded region to any accuracy. The theorem says nothing about how many units are needed or how to find the weights.
:::

::: example
## A network has one input, two tanh hidden units with weights and biases (0.5, 0) and (−1, 0.5), and a linear output with weights 2 and −1 and no bias. What's its output at x = 1?

::: solution
1. **Hidden units.**
   $$\begin{aligned} z_1 &= \tanh(0.5) \\ &= 0.4621 \\ z_2 &= \tanh(-1 + 0.5) \\ &= -0.4621 \end{aligned}$$
2. **Output.**
   $$\begin{aligned} y &= 2 \times 0.4621 \\ &\quad - 1 \times (-0.4621) \\ &= 1.386 \end{aligned}$$

**Answer:** the output at x = 1 is 1.386.
:::
:::

::: example
## A digit classifier is a 784–100–10 network with a softmax output. Count its parameters and multiply-accumulates, and find the probabilities for output activations 2, 1 and 0.1 in a three-class version.

::: solution
1. **Parameters.**
   $$\begin{aligned} &(784 + 1) \times 100 \\ &\quad + (100 + 1) \times 10 \\ &= 79{,}510 \end{aligned}$$
2. **Multiply-accumulates.**
   $$\begin{aligned} &784 \times 100 + 100 \times 10 \\ &= 79{,}400 \end{aligned}$$
3. **Softmax.** Exponentials normalized to sum to 1:
   $$\begin{aligned} &\text{softmax}(2, 1, 0.1) \\ &= (0.659, 0.242, 0.099) \end{aligned}$$

**Answer:** the network has 79,510 parameters and takes 79,400 multiply-accumulates; the probabilities are 0.659, 0.242 and 0.099.
:::
:::

::: example
## A 784–1000–1000–10 network is trained on 60,000 images for 10 epochs. How many parameters does it have, how much memory do they take in 32-bit floats, and roughly how much arithmetic does training take?

::: solution
1. **Parameters.**
   $$\begin{aligned} &785 \times 1000 + 1001 \times 1000 \\ &\quad + 1001 \times 10 \\ &= 1{,}796{,}010 \end{aligned}$$
2. **Memory.** That's 7.2 MB in 32-bit floats (Adam's two running averages triple that).
3. **Cost per example.** Training costs about 6 floating-point operations per parameter per example: 2 for the forward pass's multiply and add, 4 for the backward pass's two products.
4. **Total arithmetic.** Over $6 \times 10^5$ examples (60,000 images for 10 epochs):
   $$\begin{aligned} &6 \times 1.8 \times 10^6 \times 6 \times 10^5 \\ &= 6.5 \times 10^{12}\ \text{operations} \end{aligned}$$
   a few seconds on a GPU and about an hour on one CPU core.

**Answer:** 1,796,010 parameters, 7.2 MB in 32-bit floats, and about $6.5 \times 10^{12}$ operations to train.
:::
:::

::: check
given: D = 4 | 64 | 784; H = 16 | 128; K = 1 | 10
answer: (D + 1)*H + (H + 1)*K
tolerance: 0.5%

## How many parameters does a {D}–{H}–{K} network with biases have?

::: right
Right. $(D + 1)H + (H + 1)K$ = {answer}, counting a bias for every hidden and output unit.
:::

::: misses
- [any] Not yet. Weights plus biases in both layers.
:::
:::

::: check
given: D = 32 | 256; H = 64 | 512; K = 10 | 100; B = 8 | 32
answer: B*(D*H + H*K)
tolerance: 0.5%

## How many multiply-accumulates does a {D}–{H}–{K} network need for a batch of {B} inputs?

::: right
Right. $B(DH + HK)$ = {answer}.
:::

::: misses
- [D*H + H*K] That's one input; multiply by the batch.
- [any] Not yet. One per weight per input.
:::
:::

::: check
given: u = 0.3 | 1 | -0.5; v = -1 | 0.8; a = 1.5 | 2; b = -1 | 0.5; x = 0.5 | 2
answer: a*tanh(u*x) + b*tanh(v*x)
tolerance: 0.5%

## A one-input network has two tanh hidden units with weights {u} and {v} (no biases) and output weights {a} and {b}. What's its output at x = {x}?

::: right
Right. $a\tanh(ux) + b\tanh(vx)$ = {answer}.
:::

::: misses
- [any] Not yet. Hidden activations, then the weighted sum.
:::
:::

::: check
given: a = 1 | 3; b = 0 | 2; c = -0.5 | 0.5
answer: exp(a)/(exp(a) + exp(b) + exp(c))
tolerance: 0.5%

## A three-class softmax has activations {a}, {b} and {c}. What probability does it give the first class?

::: right
Right. $e^{a_1}/\sum e^{a_j}$ = {answer}.
:::

::: misses
- [a/(a + b + c)] Exponentiate before normalizing.
- [any] Not yet. Softmax.
:::
:::

::: check
given: H = 3 | 10 | 50
answer: H + 1
tolerance: 0.5%

## A one-input network has a single hidden layer of {H} ReLU units and a linear output. At most how many linear pieces can its output have?

::: right
Right. Each unit adds one kink: {answer} pieces.
:::

::: misses
- [2^H] That's the growth from depth, not from one layer's width.
- [any] Not yet. Count the kinks.
:::
:::

::: check
given: a = -2 | 0 | 1.5
answer: 1/(1 + exp(-a))*(1 - 1/(1 + exp(-a)))
tolerance: 0.5%

## What's the derivative of the logistic sigmoid at a = {a}?

::: right
Right. $\sigma(1 - \sigma)$ = {answer}, at most 0.25.
:::

::: misses
- [1/(1 + exp(-a))] That's the sigmoid itself.
- [any] Not yet. $\sigma'(a) = \sigma(a)(1 - \sigma(a))$.
:::
:::

::: check
kind: parts
given: P = 1 | 25 | 100; N = 0.05 | 1; E = 3 | 20; F = 10 | 100; u = 0.3 | 0.5

## A {P}-million-parameter network trains for {E} epochs on {N} million examples, on hardware sustaining {u} of its {F} TFLOP/s peak.

::: part
answer: 6*P*1e6*N*1e6*E
unit: FLOP
tolerance: 0.5%

### About how much arithmetic does training take?

::: misses
- [2*P*1e6*N*1e6*E] That's only the forward pass; the backward pass costs twice as much.
- [any] About 6 operations per parameter per example.
:::
:::

::: part
answer: 6*P*1e6*N*1e6*E/(u*F*1e12)/3600
unit: h
tolerance: 0.5%

### How long does it take?

::: misses
- [6*P*1e6*N*1e6*E/(F*1e12)/3600] Use the sustained rate, not the peak.
- [any] Operations over the sustained rate.
:::
:::
:::

::: check
kind: derivation
vars: D = 1..1000, H = 1..1000, K = 1..100

## A network has D inputs, two hidden layers of H units each, and K outputs, all fully connected with biases.

::: step
answer: (D + 1)*H + (H + 1)*H + (H + 1)*K

### How many parameters does it have?
:::

::: step
answer: D*H + H^2 + H*K

### How many multiply-accumulates does one input take?
:::

::: right
Right. The hidden-to-hidden layer's H² term dominates once H is large.
:::
:::

::: explain
## Why does a network need nonlinear hidden units, and what do they buy compared with a fixed basis?

::: model
Without a nonlinearity, each layer is a matrix multiplication, and a product of matrices is just another matrix, so any depth of linear layers computes only a linear function of the input. A nonlinear activation lets the hidden layer remap the input into features in which the task becomes linear, as the XOR network shows. Compared with a fixed basis such as polynomials, whose size explodes with input dimension, the hidden units' weights are learned, so the network places its basis functions where the data need them and uses far fewer of them for high-dimensional inputs.
:::
:::

::: practice

::: check
given: D = 2 | 2000; H = 4 | 1000; K = 1 | 50
answer: (D + 1)*H + (H + 1)*K
tolerance: 0.5%

## Parameters of a {D}–{H}–{K} network?

::: misses
- [any] $(D + 1)H + (H + 1)K$.
:::
:::

::: check
given: a = -2 | 4; b = -3 | 3; c = -1 | 2
answer: exp(a)/(exp(a) + exp(b) + exp(c))
tolerance: 0.5%

## Softmax of the first of ({a}, {b}, {c})?

::: misses
- [any] $e^{a_1}/\sum e^{a_j}$.
:::
:::

::: check
given: a = -6 | -3 | -1 | 0 | 1 | 3 | 6
answer: 1/(1 + exp(-a))*(1 - 1/(1 + exp(-a)))
tolerance: 0.5%

## σ′({a})?

::: misses
- [any] $\sigma(1 - \sigma)$.
:::
:::
:::
