Summative assessment

  • The summative assignment is now released.
  • Part A deadline: 8 December.
  • Part B deadline: 9 December.

Recap: the familiar linear score

A linear score can make a curved boundary after changing featuresThe circular notebook data is shown twice. A straight boundary uses original measurements. A quadratic feature map produces a curved boundary. −1.0 −0.5 0.0 0.5 1.0 x₁ −1.0 −0.5 0.0 0.5 1.0 x₂ Original measurements −1.0 −0.5 0.0 0.5 1.0 x₁ −1.0 −0.5 0.0 0.5 1.0 x₂ Quadratic features

The fitting method still combines features with weights. Changing the features changes the boundaries we can represent.

What did we change?

Input tableColumns
Original measurementsx₁, x₂
Quadratic features1, x₁, x₂, x₁², x₂², x₁x₂

\[ z=w_0+w_1x_1+w_2x_2+w_3x_1^2+w_4x_2^2+w_5x_1x_2 \]

Each added column has a weight. We choose the feature map; fitting learns the coefficients.

Feature values determine the score

A worked circular decision ruleThe illustrative score is two minus four times the squared radius. The score is zero on the circle of radius square root of one half. −1.0 −0.5 0.0 0.5 1.0 Original feature x₁ −1.0 −0.5 0.0 0.5 1.0 Original feature x₂ A B C

\[ z=2-4(x_1^2+x_2^2) \]

Pointx₁² + x₂²Score z
A: (0.4, 0.3)0.25+1
B: (0.8, 0.6)1−2
C: (0.5, 0.5)0.50
This is the same hand-chosen score as last lecture. A is on the label-1 side; B is on the label-0 side; C is exactly on the boundary.

We can score locations between the examples

A worked circular decision ruleThe illustrative score is two minus four times the squared radius. The score is zero on the circle of radius square root of one half. −1.0 −0.5 0.0 0.5 1.0 Original feature x₁ −1.0 −0.5 0.0 0.5 1.0 Original feature x₂

Evaluate the same score on a grid. Each location supplies its own feature values.

Filling the grid reveals the regions

A worked circular decision ruleThe illustrative score is two minus four times the squared radius. The score is zero on the circle of radius square root of one half. −1.0 −0.5 0.0 0.5 1.0 Original feature x₁ −1.0 −0.5 0.0 0.5 1.0 Original feature x₂ Class 0 Class 1

The boundary joins locations with score zero. A curved boundary appears in the original coordinates.

The same idea with more polynomial terms

A curved boundary using cubic input featuresLogistic regression on all polynomial terms up to degree three follows the curved gap between the two groups. −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 Measurement 1 −0.5 0.0 0.5 1.0 Measurement 2 Class 0 Class 1

Terms up to degree 3 let a weighted score follow this more complicated gap.

The part reaches the clear leaf

Prediction tree for part inspectionThe path for temperature 8 and vibration 4 follows no at the first split and yes at the second split to a clear leaf.YesNoYesNoTemperature ≤ 6?ClearVibration ≤ 5?ClearDefect

Temperature 8 sends this part right. Vibration 4 then sends it to the clear leaf.

Recall the hand-written rule: temperature at most 6 gives clear. Otherwise vibration at most 5 gives clear; the remaining branch gives defect.

The rule on the measured parts

The result after two splitsParts with temperature above six and vibration above five fall into the blue defect region. 0 2 4 6 8 10 Temperature (scaled) 0 2 4 6 8 10 Vibration (scaled) Clear Defect

The questions divide the measurement plane into regions. This small rule classifies all 16 displayed parts correctly.

Trees learnt their own questions

Two candidate first splitsCandidate A uses temperature 6. Candidate B uses vibration 5. 0 2 4 6 8 10 Temperature (scaled) 0 2 4 6 8 10 Vibration (scaled) A B Clear Defect

Training tries candidate questions and favours splits that separate the labels. The thresholds can come from data.

A forest combined several trees

Three trees with different training samplesThree fitted trees produce different boundaries. For the same marked point P, the defect probabilities are zero, one and one. −2 0 2 Horizontal offset −2 0 2 Vertical offset Tree 1 P −2 0 2 Horizontal offset Tree 2 P −2 0 2 Horizontal offset Tree 3 P

On the alignment example, different training samples gave different trees. The forest combined their predictions.

The figure is the same three-tree example from last lecture. The marked location has defect probabilities 0, 1 and 1 in the individual trees; their mean is 2/3. Today a neural network will combine learned feature values rather than tree votes.

Neural networks

Feedforward models and learned features

Today we will cover

  • Combine sigmoid units into a network.
  • Follow the loss backwards to every layer.
  • Build more flexible functions with hidden layers.
  • Understand scaling and practical architecture choices.

One line through the Iris measurements

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) Versicolor Virginica

Petal length and width overlap for these two species. Logistic regression makes one straight decision boundary.

Same 100 versicolor and virginica flowers as the logistic-regression lecture. The line uses that lecture’s fitted coefficients.

Logistic regression is one unit

A feedforward networkThe successive layer widths are [2, 1]. Each unit connects to all units in the following layer.x1x2Input features2 measurementspSigmoid unit1 unit

\[ z=w_lx_l+w_wx_w+b,\qquad p=\sigma(z) \]

A weighted sum followed by a sigmoid gives the probability of virginica.

What if we use three sigmoid units?

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) h1 = 0.5 h2 = 0.5 h3 = 0.5 Versicolor Virginica

Each unit has its own weights and bias, so each has its own straight half-activation line.

These are the three first-layer units of the actual small fitted network used in all subsequent Iris figures. They are not three independently fitted classifiers. A hidden activation lies between 0 and 1 but need not be a calibrated class probability.

Three units become a hidden layer

A sigmoid feedforward networkThere are 1 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Inputsxₗx_wFixed dataHidden layerh₁σh₂σh₃σSigmoid featuresW, b

\[ h_j=\sigma(W_{jl}x_l+W_{jw}x_w+b_j) \]

The next layer combines three learned feature values. We scale the two inputs, as before.

Inputs use the same scaling as the logistic-regression lecture: subtract its training means (4.8733 cm, 1.6667 cm) and divide by its training standard deviations (0.8689 cm, 0.4467 cm). The axes on the scatterplots remain in centimetres.

The first hidden feature

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) Versicolor Virginica 0.0 0.5 1.0 Hidden activation h1

Colour shows h₁ from low to high. The straight line marks h₁ = 0.5.

The second hidden feature

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) Versicolor Virginica 0.0 0.5 1.0 Hidden activation h2

Its weights point in a different direction. The same flower supplies a different feature value.

The third hidden feature

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) Versicolor Virginica 0.0 0.5 1.0 Hidden activation h3

The model now has three smooth responses to combine, rather than only the two original measurements.

The three responses combined

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) Versicolor Virginica

Together, the three units can make a curved boundary.

This is the same fitted network and decision boundary as the later Before the update slide, without the ring or probability annotation. It combines all three hidden activations; it does not join pieces of their half-activation lines.

Combine the three hidden outputs

\[ z=v_1h_1+v_2h_2+v_3h_3+c \]

\[ p=\sigma(z)=\sigma(v_1h_1+v_2h_2+v_3h_3+c) \]

This is another weighted sum and sigmoid. Its inputs are the hidden features.

A forest combined tree predictions. Here the combination itself has weights that training can learn.

The same loss trains both sets of weights

A sigmoid feedforward networkThere are 1 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layerh₁σh₂σh₃σSigmoid featuresProbabilitypσp(virginica)W, bv, c

\[ \ell=-y\ln p-(1-y)\ln(1-p) \]

The loss depends on the output weights and on the weights inside each hidden feature.

Follow one flower forwards

For a virginica flower: length 5 cm, width 1.5 cm, so y = 1.

CalculationValue
Scaled inputsxₗ = 0.146, x_w = -0.373
Three hidden activationsh1 = 0.367, h2 = 0.439, h3 = 0.006
Output probabilityp = 0.379
Cross-entropy loss−ln(p) = 0.969
This calculation uses the same full-precision parameters as every small-network Iris boundary. The hidden inputs use the centring and scaling stated on the hidden-layer slide.

Start at the output

A sigmoid feedforward networkThere are 1 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layerh₁σh₂σh₃σSigmoid featuresProbabilitypσp(virginica)W, bv, c

\[ \frac{\partial\ell}{\partial z}=p-y \]

For this flower, p − y = -0.621. The model should raise its final score.

Back to the hidden features

A sigmoid feedforward networkThere are 1 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layerh₁σh₂σh₃σSigmoid featuresProbabilitypσp(virginica)W, bv, c

\[ \frac{\partial\ell}{\partial a_j}=(p-y)v_jh_j(1-h_j) \]

Each hidden unit receives a signal through its output weight, multiplied by its own sigmoid slope.

a_j is the input score of hidden unit j, before its sigmoid. Also ∂ℓ/∂v_j=(p−y)h_j and ∂ℓ/∂c=p−y. Blue arrows describe gradient calculation, not a second prediction.

Reach the input weights

A sigmoid feedforward networkThere are 1 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layerh₁σh₂σh₃σSigmoid featuresProbabilitypσp(virginica)W, bv, c

\[ \frac{\partial\ell}{\partial W_{jl}}=\frac{\partial\ell}{\partial a_j}x_l,\qquad \frac{\partial\ell}{\partial W_{jw}}=\frac{\partial\ell}{\partial a_j}x_w \]

The gradient reaches both sets of weights. The measured petal length and width stay fixed.

Change the parameters using those gradients

\[ \theta_{\mathrm{new}}=\theta-\eta\frac{\partial\ell}{\partial\theta} \]

One parameterBeforeGradientAfter
Output weight v₁-6.107-0.228-6.061
Hidden length weight W₁ₗ-7.3500.128-7.375
Hidden width weight W₁w0.870-0.3290.936

Learning rate η = 0.2. The same step updates all weights and biases.

A single-example gradient descent step is used for transparency. Biases update too. During normal training a batch loss usually supplies the gradients. Analytic gradients were checked against central finite differences.

Before the update

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) p = 0.38 Versicolor Virginica

The ringed virginica flower receives p = 0.38. Its loss is 0.97.

Run the changed network forwards again

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) p = 0.61 Versicolor Virginica

The same flower now receives p = 0.61. Its loss falls to 0.49.

The dashed boundary is before the step. This step helps the selected flower; it need not help every other flower. A batch averages contributions across examples.

The three features make one curved boundary

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) h1 = 0.5 h2 = 0.5 h3 = 0.5 Versicolor Virginica

Dashed lines belong to the hidden units. The solid boundary is where their combined output gives p = 0.5.

This returns to the small fitted network before the isolated worked update. Every plot with this title uses the same three units shown at the start.

One model, with features learned from data

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) Versicolor Virginica

The final boundary can curve even though each first-layer half-activation line is straight.

This is a nonlinear weighted combination, not pieces of three decision lines joined together. Smooth sigmoid values can bend the final level set.

What if we add many more units and layers?

A wider and deeper sigmoid networkThe widths are two inputs, sixteen, sixteen and eight hidden units, then one binary output.Inputs2Hidden 116Hidden 216Hidden 38Output1

More learned intermediate features give the model more ways to vary its response.

A much more flexible Iris boundary

Iris measurements and the network responseThe same one hundred versicolor and virginica flowers are shown in petal-length and petal-width coordinates. Lines for hidden units mark activation one half. The combined boundary is where the final predicted virginica probability is one half. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 Petal width (cm) Versicolor Virginica

This 2 → 16 → 16 → 8 → 1 sigmoid network makes intricate regions. Check whether those details help new flowers using held-out data.

Capacity illustration: this model was fitted to all 100 displayed flowers with a budget of up to 2,800 L-BFGS iterations. It classifies 99/100 displayed observations correctly. This is training fit, not a held-out performance claim. Exact duplicate measurements with different species occur in these two features.

Return to XOR

Sigmoid units solve XORTwo sigmoid hidden units respond to different thresholds on the input sum. Their weighted combination assigns high probability to the two off-diagonal corners. 0.00 0.25 0.50 0.75 1.00 Input x₁ −0.2 0.0 0.2 0.4 0.6 0.8 1.0 1.2 Input x₂

A single straight line cannot separate these labels. Can two hidden sigmoid units help?

One hidden unit responds after the first corner

Sigmoid units solve XORTwo sigmoid hidden units respond to different thresholds on the input sum. Their weighted combination assigns high probability to the two off-diagonal corners. 0.00 0.25 0.50 0.75 1.00 Input x₁ −0.2 0.0 0.2 0.4 0.6 0.8 1.0 1.2 Input x₂

\[ h_1=\sigma(10(x_1+x_2-0.5)) \]

Another responds near the far corner

Sigmoid units solve XORTwo sigmoid hidden units respond to different thresholds on the input sum. Their weighted combination assigns high probability to the two off-diagonal corners. 0.00 0.25 0.50 0.75 1.00 Input x₁ −0.2 0.0 0.2 0.4 0.6 0.8 1.0 1.2 Input x₂

\[ h_2=\sigma(10(x_1+x_2-1.5)) \]

Their difference picks out the middle band

Sigmoid units solve XORTwo sigmoid hidden units respond to different thresholds on the input sum. Their weighted combination assigns high probability to the two off-diagonal corners. 0.00 0.25 0.50 0.75 1.00 Input x₁ −0.2 0.0 0.2 0.4 0.6 0.8 1.0 1.2 Input x₂

\[ p=\sigma(10h_1-10h_2-5) \]

These weights are chosen by hand to demonstrate representation. Sigmoid never gives exactly 0 or 1 at finite inputs. The plotted predictions, rather than a claim of exact binary activations, are used in the worked table.

Work through the input (1, 0)

\[ x_1+x_2=1 \]

\[ h_1=\sigma(5)\approx0.993,\qquad h_2=\sigma(-5)\approx0.007 \]

The first hidden unit is strongly active; the second is barely active.

The output recognises the positive corner

\[ z=10(0.993)-10(0.007)-5\approx4.87 \]

\[ p=\sigma(4.87)\approx0.992 \]

The two original inputs have become useful intermediate features.

All four XOR predictions

InputHidden h₁Hidden h₂Output pLabel
(0, 0)0.0070.0000.0070
(1, 0)0.9930.0070.9921
(0, 1)0.9930.0070.9921
(1, 1)1.0000.9930.0070

Thresholding the final probability at 0.5 gives all four labels correctly.

Learn a tolerance region

A sigmoid network learns a tolerance regionThe same two-input, eight-hidden-unit network after 0 gradient updates. Colours show the final probability and the line shows probability one half. −1.0 −0.5 0.0 0.5 1.0 Horizontal alignment error −1.0 −0.5 0.0 0.5 1.0 Vertical alignment error Outside tolerance Within tolerance

Recall the laser-alignment scenario. The blue parts are within tolerance. Start a 2 → 8 → 1 sigmoid network with random weights.

After 100 updates

A sigmoid network learns a tolerance regionThe same two-input, eight-hidden-unit network after 100 gradient updates. Colours show the final probability and the line shows probability one half. −1.0 −0.5 0.0 0.5 1.0 Horizontal alignment error −1.0 −0.5 0.0 0.5 1.0 Vertical alignment error Outside tolerance Within tolerance

The same loss updates the output combination and the hidden responses.

After 1,200 updates

A sigmoid network learns a tolerance regionThe same two-input, eight-hidden-unit network after 1200 gradient updates. Colours show the final probability and the line shows probability one half. −1.0 −0.5 0.0 0.5 1.0 Horizontal alignment error −1.0 −0.5 0.0 0.5 1.0 Vertical alignment error Outside tolerance Within tolerance

The learned features now combine to enclose the central region.

These are actual frames of a full-batch Adam run with sigmoid hidden units and learning rate 0.025. The model classifies 120/120 training examples and 40/40 fixed held-out examples correctly at the last frame. The plotted points are training examples.

Look inside one learned hidden unit

Learned sigmoid feature responsesEach first-layer hidden unit still has a straight half-activation line. Combining several feature values makes the curved final boundary. −1 0 1 −1 0 1 Hidden feature h1

One unit alone still has a straight half-activation line.

Several learned features shape the output

Learned sigmoid feature responsesEach first-layer hidden unit still has a straight half-activation line. Combining several feature values makes the curved final boundary. −1 0 1 −1 0 1 Hidden feature h1 −1 0 1 −1 0 1 Hidden feature h2 −1 0 1 −1 0 1 Hidden feature h3 −1 0 1 −1 0 1 Hidden feature h4

The output combines all eight feature values. These are four of the learned responses.

Add another hidden layer

A sigmoid feedforward networkThere are 2 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Inputsxₗx_wFixed dataHidden layer 1h₁σh₂σh₃σSigmoid featuresHidden layer 2r₁σr₂σr₃σSigmoid featuresW, bU, d

The new units receive the first layer’s feature values. Their inputs are already learned transformations.

Repeat the same weighted-sum-and-sigmoid calculation

\[ h_j=\sigma(W_{jl}x_l+W_{jw}x_w+b_j) \]

\[ r_k=\sigma(U_{k1}h_1+U_{k2}h_2+U_{k3}h_3+d_k) \]

\[ p=\sigma(v_1r_1+v_2r_2+v_3r_3+c) \]

Each layer uses the outputs of the layer before it.

The same loss trains all three sets of weights

A sigmoid feedforward networkThere are 2 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layer 1h₁σh₂σh₃σSigmoid featuresHidden layer 2r₁σr₂σr₃σSigmoid featuresProbabilitypσp(virginica)W, bU, dv, c

\[ \ell=-y\ln p-(1-y)\ln(1-p) \]

We have extended the chain of dependencies.

Run a forward pass

A sigmoid feedforward networkThere are 2 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layer 1h₁σh₂σh₃σSigmoid featuresHidden layer 2r₁σr₂σr₃σSigmoid featuresProbabilitypσp(virginica)W, bU, dv, c

Measurements → first hidden features → second hidden features → probability → loss.

Start at the output

A sigmoid feedforward networkThere are 2 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layer 1h₁σh₂σh₃σSigmoid featuresHidden layer 2r₁σr₂σr₃σSigmoid featuresProbabilitypσp(virginica)W, bU, dv, c

\[ \frac{\partial\ell}{\partial z}=p-y \]

The calculation at the far right is exactly the same as before.

Back to the second hidden layer

A sigmoid feedforward networkThere are 2 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layer 1h₁σh₂σh₃σSigmoid featuresHidden layer 2r₁σr₂σr₃σSigmoid featuresProbabilitypσp(virginica)W, bU, dv, c

\[ \frac{\partial\ell}{\partial a_k^{(2)}}=(p-y)v_kr_k(1-r_k) \]

Use the output weight and this unit’s sigmoid slope.

Back to the first hidden layer

A sigmoid feedforward networkThere are 2 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layer 1h₁σh₂σh₃σSigmoid featuresHidden layer 2r₁σr₂σr₃σSigmoid featuresProbabilitypσp(virginica)W, bU, dv, c

\[ \frac{\partial\ell}{\partial a_j^{(1)}}=h_j(1-h_j)\sum_k U_{kj}\frac{\partial\ell}{\partial a_k^{(2)}} \]

Add the gradient contributions from every later unit.

a_j^(1) and a_k^(2) denote the pre-sigmoid input scores in the two hidden layers. The diagram repeats the shallow-network backward sequence with one extra stage.

Reach the input weights

A sigmoid feedforward networkThere are 2 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layer 1h₁σh₂σh₃σSigmoid featuresHidden layer 2r₁σr₂σr₃σSigmoid featuresProbabilitypσp(virginica)W, bU, dv, c

\[ \frac{\partial\ell}{\partial W_{jl}}=\frac{\partial\ell}{\partial a_j^{(1)}}x_l \]

The petal measurements still stay fixed. The longer chain gives gradients for the earlier weights.

The optimiser updates every layer

ParametersWhat changes?
First hidden weights and biasesFeatures of the measurements
Second hidden weights and biasesFeatures of the first features
Output weights and biasHow the final features combine

\[ \boldsymbol{\theta}_{\mathrm{new}}=\boldsymbol{\theta}-\eta\nabla_{\boldsymbol{\theta}}J \]

The gradient of a batch cost averages the example contributions before the update.

The sigmoid can pass back a very small slope

Sigmoid outputs and their slopesThe sigmoid is steepest at zero with slope one quarter. Large positive or negative input scores have slopes close to zero. −8 −6 −4 −2 0 2 4 6 8 Input score a 0.0 0.2 0.4 0.6 0.8 1.0 Sigmoid output −8 −6 −4 −2 0 2 4 6 8 Input score a 0.00 0.05 0.10 0.15 0.20 0.25 Local slope

\[ \sigma\prime(a)=\sigma(a)(1-\sigma(a)) \]

At large positive or negative scores, changing the score barely changes the hidden output.

For the sigmoid output combined with binary cross-entropy, the derivative with respect to the final score simplifies to p−y. The small-slope issue here concerns sigmoid units inside the hidden layers.

Small hidden slopes can multiply through the network

Repeated small local slopes shrink a signalThis illustrative chain multiplies only sigmoid slopes of one quarter. Actual backpropagation also includes the learned weight factors and sums over paths. 0 1 2 3 4 5 6 7 8 Number of hidden sigmoid slopes multiplied 1 0 − 5 1 0 − 4 1 0 − 3 1 0 − 2 1 0 − 1 1 0 0 Product of these slopes 0.25 0.015625 0.000244141

Repeated small factors can make early-layer gradients tiny. Those layers can then learn slowly.

The plot isolates a product of sigmoid slopes equal to 1/4. Actual derivatives also multiply weight factors and add paths; this plot is an illustration, not a general upper bound on a network gradient. Large weights can also cause gradients to grow.

A ReLU supplies a different response

How a unit transforms its inputChanging the weights and bias changes the feature calculated by the unit. −4 −3 −2 −1 0 1 2 3 4 Input to the unit 0 1 2 3 4 Unit output input −2 input 3

\[ \mathrm{ReLU}(a)=\max(0,a) \]

What does it output at −2 and at 3?

Reading the ReLU

Input scoreOutputLocal slope
−200
331

On its positive side, ReLU passes the slope through without a sigmoid factor.

ReLU is not differentiable exactly at zero. Software uses a chosen subgradient there, commonly zero. A unit that stays on the negative side can stop learning from those examples.

The bias moves the bend

How a unit transforms its inputChanging the weights and bias changes the feature calculated by the unit. −4 −3 −2 −1 0 1 2 3 4 Input to the unit 0 1 2 3 4 Unit output bias = -1 bias = +0 bias = +1

Learning the bias learns where this hidden feature starts responding.

The weight changes the slope

How a unit transforms its inputChanging the weights and bias changes the feature calculated by the unit. −4 −3 −2 −1 0 1 2 3 4 Input to the unit 0 1 2 3 4 5 6 Unit output input weight = 0.5 input weight = 2 input weight = -1

Learning input weights changes the strength and direction of the response.

Can extra layers create a curve on their own?

Two layers without an activationAn input x passes through h equals two x minus three, then through z equals four h plus one. There is no nonlinear activation between the two weighted sums.InputxFirst weighted sumh = 2x − 3Second weighted sumz = 4h + 1No activation function between the two calculations

Suppose we remove the activations. Can these two weighted sums produce a curved response?

Audience question. Invite an intuitive prediction or substitution of h into z before moving down to the answer.

Two weighted sums still give a straight line

\[ h=2x-3,\qquad z=4h+1 \]

\[ z=4(2x-3)+1=8x-11 \]

Without a nonlinear activation, these two layers collapse into a single straight-line calculation.

A nonlinear activation changes what we can represent

How a unit transforms its inputChanging the weights and bias changes the feature calculated by the unit. −4 −3 −2 −1 0 1 2 3 4 Input x −40 −30 −20 −10 0 10 20 Final output Two affine layers ReLU between the layers

The bend remains after combining the layers. Stacking linear calculations alone cannot create it.

Choose a hidden activation

Three possible hidden activation functionsSigmoid has outputs between zero and one, tanh between minus one and one, and ReLU equals zero for negative input scores and equals its input for positive scores. −4 −2 0 2 4 Input score a 0.0 0.2 0.4 0.6 0.8 1.0 Sigmoid −4 −2 0 2 4 Input score a −1.0 −0.5 0.0 0.5 1.0 tanh −4 −2 0 2 4 Input score a 0 1 2 3 4 ReLU

Sigmoid, tanh and ReLU change both the functions we can represent and the gradients used in training.

The output activation still follows the prediction task.

Several units can supply different bends

Three hidden ReLU featuresOne feature rises across the interval. Another starts to rise at one quarter, and the third at three quarters. 0.0 0.2 0.4 0.6 0.8 1.0 Input x 0.0 0.2 0.4 0.6 0.8 1.0 Hidden output h₁ = ReLU(x) h₂ = ReLU(x − 0.25) h₃ = ReLU(x − 0.75)

These ReLU units start responding at different input values.

Combine the bends into a more complex function

The weighted hidden outputs form a responseThe model is piecewise linear with changes of slope at one quarter and three quarters. 0.0 0.2 0.4 0.6 0.8 1.0 Input x 0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 Model output Smooth target response Three hidden units

\[ \hat y=0.5+2.8h_1-4.8h_2+4.8h_3 \]

This is a hand-chosen construction, with h1=ReLU(x), h2=ReLU(x−0.25) and h3=ReLU(x−0.75). It demonstrates what the architecture can represent, rather than a training trajectory.

A network for this numerical response

A feedforward networkThe successive layer widths are [1, 3, 1]. Each unit connects to all units in the following layer.x1Inputs1 measurementh1h2h3Hidden layer3 unitsŷOutput1 unit

One input, three hidden units and a linear output. We predict a number, so the final layer need not be a sigmoid.

More units follow more of the curve

A finer piecewise-linear approximation8 straight segments follow the same smooth function more closely. The maximum absolute error on a dense grid is 0.0422. 0.0 0.2 0.4 0.6 0.8 1.0 Input x 0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 Model output Smooth target response 8 straight segments

Extra changes of slope let the response follow finer detail.

A finer approximation

A finer piecewise-linear approximation16 straight segments follow the same smooth function more closely. The maximum absolute error on a dense grid is 0.0113. 0.0 0.2 0.4 0.6 0.8 1.0 Input x 0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 Model output Smooth target response 16 straight segments

Simple units can combine to represent a complicated function.

Both plots use piecewise-linear interpolation at equally spaced knots on the same smooth target. The coefficients are constructed by hand. Any such one-dimensional linear spline has a ReLU-network representation.

Fitting the observed interval is only part of the task

A feedforward regression modelThe fitted network has twelve ReLU hidden units and a linear output. Outside the observed input range its response follows its learned straight segments. −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 1.25 1.50 Input x −0.5 0.0 0.5 1.0 1.5 2.0 2.5 Response Training input range Underlying response Learned network Training readings

A flexible network may fit the observed range well and still behave poorly beyond it.

Same illustrative regression fit as the previous draft. The plot distinguishes the training input range from extrapolation. It is not a theorem about all neural networks.

Width supplies parallel features; depth composes them

ChangeWhat it offers
More units in a layerMore feature responses at the same stage
More hidden layersFurther transformations of learned features

The useful choice depends on the pattern and the data.

A first layer can measure departures from a target

Two ReLUs encode departure in either directionAdding the positive and negative parts of a coordinate gives its absolute value. −1.0 −0.5 0.0 0.5 1.0 Coordinate x 0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 Departure feature ReLU(x) ReLU(−x) Their sum = |x|

\[ |x_1|=\mathrm{ReLU}(x_1)+\mathrm{ReLU}(-x_1) \]

For the alignment example, combine positive and negative departures in each coordinate.

A later layer can combine them into a local response

A second layer combines simpler features into a local responseFour first-layer ReLU units encode positive and negative departures in two coordinates. A second-layer unit computes max of zero and one minus the sum, producing a diamond-shaped local response. −1 0 1 Input x₁ −1.0 −0.5 0.0 0.5 1.0 Input x₂ 0.0000 0.1818 0.3636 0.5455 0.7273 0.9091 Second-layer activation

\[ h=\mathrm{ReLU}(1-|x_1|-|x_2|) \]

The second stage makes a local feature from the first stage’s features.

This constructed ReLU response has diamond-shaped support. The illustration demonstrates composition and does not claim it is the fitted circle classifier.

Why did neural networks become so successful?

Learned features can be scaled to much larger problems.

From Iris to a large recommendation dataset

From flower measurements to large event datasetsIris has 150 flowers. Spotify released a million-playlist research dataset. A separate illustrative service estimate assumes a billion interaction events per day; it is not a claim about Spotify internal data.Iris150 flowersPublic Spotify MPD1,000,000 playlistsService estimate10⁹ events / dayOur binary example: 100Released for research in 2018Assumptions shown nextDifferent records and tasks. This compares scale, not difficulty.

Iris is a small teaching dataset. Real recommendation tasks can draw on enormous collections of interactions.

Spotify Million Playlist Dataset, released for research in 2018.

The public Spotify research dataset contains one million playlists. Playlist records, flower records and interaction events are different units: the comparison is order of magnitude, not a benchmark or a claim about task difficulty. The large-service number is hypothetical and unpacked on the next slide.

An order-of-magnitude estimate

Imagine a music service with 100 million active listeners, each producing 10 recorded interactions a day.

\[ 10^8\ \mathrm{listeners}\times10\ \mathrm{events/day}=10^9\ \mathrm{events/day} \]

\[ 365\times10^9\approx3.7\times10^{11}\ \mathrm{events/year} \]

Illustrative assumptions. This estimates a hypothetical service, rather than Spotify’s internal dataset.

Repeated actions from one listener are correlated. A billion rows is not a billion independent people or equally useful examples. This comparison motivates scalable learning; it does not assert that every logged event is a training label.

The inputs can contain much richer information

For a candidate trackPossible input information
ListenerRecent listening and longer-term preferences
TrackAudio properties and learned track features
ContextTime, device and the surrounding playlist

For example, predict the chance that this listener skips this track.

This is an illustrative recommendation task, not a description of Spotify’s production architecture. Later architectures and embeddings can supply learned inputs to a dense prediction network.

The same learned weights process a whole batch

\[ \mathbf{H}=\sigma(\mathbf{X}\mathbf{W}+\mathbf{b}) \]

ObjectMeaning
Rows of XDifferent examples in one batch
WOne shared set of layer weights
Rows of HTheir hidden feature values

These large matrix calculations can use parallel hardware efficiently.

The bias broadcasts over rows; sigmoid is applied elementwise here. Other hidden activations use the same dense matrix multiplication. Batches do not create separate weights for each example.

Data, capacity and computation can grow together

Data capacity and computation grow togetherScaling means coordinating useful data, model capacity and computational resources, while checking whether predictions improve on held-out examples.More useful dataBroader experienceMore model capacityMore patterns representedMore computationTrain the larger modelImprove them together, then measure held-out performanceMore parameters alone do not guarantee a better prediction.

A useful network can learn more features from more examples when we can afford to train it.

Hestness and colleagues, empirical scaling across several deep-learning tasks.

Empirical scaling is task-dependent. The cited paper measures several domains; it does not guarantee a common scaling law for every architecture or arbitrary new dataset. Data quality, distribution and the training objective matter.

More rows need useful new information

More recordings of the same narrow situation may add little. Broader users, contexts and examples can teach the model more.

Check on genuinely held-out cases. For listening data, a time-based or user-based split may answer a more useful question than randomly splitting related events.

The right split follows the deployment question. A user-based split tests new users; a time-based split tests later interactions. Neither is a universal requirement for every recommendation task.

Choosing a neural network architecture

What do the familiar defaults and templates actually buy us?

A template you may encounter

MLPClassifier(
    hidden_layer_sizes=(256, 128),
    activation="relu",
    solver="adam"
)

Two hidden layers, with 256 and 128 units. ReLU transforms their outputs; Adam updates the parameters.

scikit-learn’s actual default is one hidden layer of 100 units, with ReLU and Adam.

MLPClassifier documentation.

Why 256 then 128?

ChoiceWhat it means
256 unitsMany parallel feature responses
128 units nextA further combination of those responses
Powers of twoA common convention, rather than a statistical requirement

These numbers are starting choices. The validation results must justify the capacity.

There is no theorem making 256/128 optimal. Powers of two are convenient familiar sizes; actual hardware performance depends on implementation, batch size, device and precision. Hidden widths need not be powers of two or decrease monotonically.

Count the parameters before choosing the width

\[ P_{\mathrm{layer}}=(n_{\mathrm{in}}+1)n_{\mathrm{out}} \]

Architecture for two inputsTrainable parameters
2 → 3 → 113
2 → 16 → 165
2 → 256 → 128 → 133,793

The +1 counts the bias for each output unit. A wider template can be a large jump for a tiny dataset.

Totals include every dense weight and bias: 9+4=13; 48+17=65; 768+32896+129=33793. A large parameter count is not itself a proof of poor generalisation, but it changes capacity and training cost.

Does doubling the width double the size?

Double both hidden-layer widthsThe original network has widths two, 256, 128 and one. The wider network has widths two, 512, 256 and one. Both hidden widths double, while the input and output shapes are unchanged.Inputs2Hidden layer 1256Hidden layer 2128Output1Inputs2Hidden layer 1512Hidden layer 2256Output1

Both hidden widths double. Do we get twice as many trainable parameters, or more?

Audience question. The input still has two measurements and the output still has one unit. Encourage students to consider how many connections run between the two hidden layers.

The biggest weight matrix becomes four times larger

\[ (2\times256)(2\times128)=4(256\times128) \]

Parameters256 → 128512 → 256
Weights between hidden layers32,768131,072
All weights and biases33,793133,121

The whole model is almost four times larger. Most parameters connect the two hidden layers.

The wider model has (2+1)×512+(512+1)×256+(256+1)×1=133121 parameters. The total ratio is approximately 3.94. Exactly four times applies to the hidden-to-hidden weight matrix, not the complete model.

Does every layer need to shrink?

A narrow hidden layer compresses informationAll input information must pass through the bottleneck. Later layers cannot recover distinctions that the bottleneck discarded.Input informationMany measurementsBottleneckOne numberLater hidden layerCannot recover lost detailCompression is useful only if it preserves what the task needs.

A narrower layer can encourage compression. Making it too narrow can discard useful distinctions.

Some networks expand before compressing. Choose the shape for the information the task needs.

Why start with ReLU?

How a unit transforms its inputChanging the weights and bias changes the feature calculated by the unit. −4 −3 −2 −1 0 1 2 3 4 Input to the unit 0 1 2 3 4 Unit output input −2 input 3

It is cheap to compute, supplies a nonlinearity, and has slope 1 on its positive side.

Units that stay negative can become inactive. ReLU still needs sensible scaling, initialisation and learning rates.

Why is Adam a common starting choice?

Adam usesWhy it can help
A moving average of gradientsA less erratic update direction
A moving average of squared gradientsDifferent adjustment scales for different parameters

It is a practical starting optimiser. We still choose a learning rate and check the training curves.

The scikit-learn documentation notes that L-BFGS can converge faster and perform better on small datasets. Adam is not universally best and does not choose the network architecture. MLPClassifier optimiser guidance.

Initialisation must let hidden units differ

Identically initialised hidden units can stay identicalTwo hidden units with identical incoming parameters and identical outgoing weights receive identical gradients, so ordinary gradient descent preserves the symmetry.Hidden unit 1same starting W, bSame featuresame activationSame gradientsame next weightsHidden unit 2same starting W, bSame featuresame activationSame gradientsame next weights

Identical incoming and outgoing parameters can give identical gradients. Extra units then repeat the same feature.

Different starting weights let features develop differently

Different initial weights permit different featuresTwo units with different weights and biases begin with different activation functions. Their updates can then differ. −2.0 −1.5 −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 Input x 0.0 0.5 1.0 1.5 2.0 Hidden feature weight 0.8, bias -0.2 weight -0.55, bias 0.4

Random initial weights break that symmetry. Different units can learn different useful responses.

Keep the forward and backward signals on a useful scale

Part of the modelA practical starting point
Input measurementsScale using the training data
Sigmoid or tanh layersXavier/Glorot-style initialisation
ReLU layersHe/Kaiming-style initialisation

The layer width and activation affect how signals grow or shrink. Libraries provide standard initialisers.

Glorot and Bengio, initialisation. He and colleagues, rectifier initialisation. These are common engineering choices, not a claim that every library automatically chooses the same scheme.

Compare a few small architectures first

Candidate hidden layersWhat we are testing
(16,)One modest layer
(32,)More parallel features
(32, 16)A second stage of composition

Use the same data split, a comparable tuning effort and more than one random seed. Let validation performance guide the choice.

The appropriate comparison controls data, preprocessing and tuning opportunity. Record training time as well as predictive performance. Early stopping can use the same validation design; keep a separate final test evaluation.

Match the output to the prediction task

TaskFinal outputLoss
Virginica or versicolorOne sigmoid probabilityBinary cross-entropy
A numerical responseA linear valueFor example, mean squared error

The hidden architecture and the output calculation solve different parts of the problem.

Match the architecture to the structure of the data

Input structureArchitecture to consider
A fixed vector of measurementsA feedforward dense network
Neighbouring pixels in imagesConvolutional networks
Sequences and relationships between elementsAttention-based architectures

Next lecture: how those specialised architectures build on learned features and backpropagation.

Today we covered

  • Hidden units learn features of their inputs.
  • Their outputs combine to make curved boundaries and complex functions.
  • Backpropagation supplies gradients throughout the network.
  • Architecture, useful data and computation shape what we can learn.