1 of 46

Neural Network Math & Techniques

ML@UVA Lecture 4

Presenter: Shubs Debsarkar

2 of 46

Neural Network Internals

3 of 46

Recap: One Neuron

Logistic regression: One Neuron

Forward

z = w₁x₁ + w₂x₂ + b

ŷ = σ(z)

Backward

∂L/∂z = ŷ − y

∂L/∂wᵢ = (ŷ − y) · xᵢ

  • Neural Network: Many neurons in layers
  • Error has to travel back through more than one layer.

4 of 46

Our Network: 2 → 2 → 2

Hidden layer

h = ReLU(x W⁽¹⁾ + b⁽¹⁾)

4 weights + 2 biases

Output layer

p = softmax(h W⁽²⁾ + b⁽²⁾)

4 weights + 2 biases

Labels

w⁽¹⁾ᵢⱼ connects input i to hidden neuron j

12 parameters in total

5 of 46

ReLU and Softmax

ReLU (hidden layers): keep positives, zero out negatives. Its slope is 1 or 0.

Softmax (output layer): pₖ = exp(sₖ) / Σⱼ exp(sⱼ). Becomes a probability dist.

6 of 46

Forward: Hidden Layer

x = [1, 2]

z₁ = (1)(−1) + (2)(1) + 0.5 = 1.5

z₂ = (1)(2) + (2)(−0.5) − 0.5 = 0.5

h = ReLU(z) = max(0, z) = [1.5, 0.5]

Matrix form: z = x W⁽¹⁾ + b⁽¹⁾

7 of 46

Forward: Output and Loss

L = 1.31

s₁ = (1.5)(1) + (0.5)(−1) + 0 = 1

s₂ = (1.5)(−1) + (0.5)(1.5) + 0.75 = 0

p₂ = e⁰ / (e¹ + e⁰) = 0.27

L = −log p₂ = −log 0.27 = 1.31

8 of 46

Backward: The Chain Rule

Goal: Figure out how much to move each weight and bias using derivatives

∂L/∂z = ∂L/∂s · ∂s/∂h · ∂h/∂z

Chain Rule!

9 of 46

Backward: Softmax + Loss

p − y

1. Log-loss w.r.t scores

L = −log pₜ = −sₜ + log Σⱼ exp(sⱼ)

2. derivative w.r.t each score

∂L/∂sₖ = −1[k = t] + exp(sₖ) / Σⱼ exp(sⱼ)

3. Simplifies very cleanly

∂L/∂sₖ = pₖ − yₖ

Our network

[0.73, 0.27] − [0, 1]

= [0.73, −0.73]

Positive: lower s₁. Negative: raise s₂.

Higher loss → Move more

10 of 46

Backward: Output Weights

input × error

Forward: sⱼ = h₁w⁽²⁾₁ⱼ + h₂w⁽²⁾₂ⱼ + b⁽²⁾ⱼ

Local slopes: ∂sⱼ/∂w⁽²⁾ᵢⱼ = hᵢ, ∂sⱼ/∂b⁽²⁾ⱼ = 1

∂L/∂w⁽²⁾ᵢⱼ = hᵢ · ∂L/∂sⱼ, ∂L/∂b⁽²⁾ⱼ = ∂L/∂sⱼ

∂L/∂w⁽²⁾₁₁ = (1.5)(0.73) = 1.10

∂L/∂w⁽²⁾₂₂ = (0.5)(−0.73) = −0.37

Matrix form: dW⁽²⁾ = hᵀ · ds

11 of 46

Backward: Hidden Layer

h₁ feeds both s₁ and s₂, so its blame adds up over both paths

Local slope: ∂sⱼ/∂hᵢ = w⁽²⁾ᵢⱼ (the same weight used going forward)

∂L/∂hᵢ = Σⱼ w⁽²⁾ᵢⱼ · ∂L/∂sⱼ

∂L/∂h₁ = (1)(0.73) + (−1)(−0.73) = 1.46

∂L/∂h₂ = (−1)(0.73) + (1.5)(−0.73) = −1.83

Matrix form: dh = ds · W⁽²⁾ᵀ

12 of 46

Backward: Through the ReLU

gate open

Forward

hⱼ = max(0, zⱼ)

Local slope: 1 where zⱼ > 0, and 0 where zⱼ ≤ 0

∂hⱼ/∂zⱼ = 1[zⱼ > 0]

Chain rule

∂L/∂zⱼ = ∂L/∂hⱼ · 1[zⱼ > 0]

Our example

z = [1.5, 0.5], both > 0

∂L/∂z = [1.46, −1.83]

What if z₂ had been −0.5?

13 of 46

Backward: Input Weights

input × error

Forward: zⱼ = x₁w⁽¹⁾₁ⱼ + x₂w⁽¹⁾₂ⱼ + b⁽¹⁾ⱼ (same shape as before)

Local slopes: ∂zⱼ/∂w⁽¹⁾ᵢⱼ = xᵢ, ∂zⱼ/∂b⁽¹⁾ⱼ = 1

∂L/∂w⁽¹⁾ᵢⱼ = xᵢ · ∂L/∂zⱼ, ∂L/∂b⁽¹⁾ⱼ = ∂L/∂zⱼ

∂L/∂w⁽¹⁾₂₁ = (2)(1.46) = 2.92

∂L/∂w⁽¹⁾₂₂ = (2)(−1.83) = −3.66

x₂ = 2 doubles its row. Keep this in mind.

14 of 46

Backprop in Three Rules

Stage

Forward

Backward (d = gradient arriving from the right)

Softmax + loss

p = softmax(s)

L = −log pₜ

∂L/∂s = p − y

Linear layer

out = a W + b

∂L/∂W = aᵀ · d

∂L/∂b = d

∂L/∂a = d · Wᵀ (send it back)

ReLU

h = max(0, z)

∂L/∂z = d · 1[z > 0] (gate)

15 of 46

One Gradient Step

L: 1.31 → 0.02

w ← w − η · ∂L/∂w, η = 0.1

Parameter

Old

Gradient

New

w⁽¹⁾₁₁

−1

1.46

−1.15

w⁽¹⁾₂₂

−0.5

−3.66

−0.13

b⁽¹⁾₂

−0.5

−1.83

−0.32

w⁽²⁾₁₁

1

1.10

0.89

w⁽²⁾₂₂

1.5

−0.37

1.54

b⁽²⁾₂

0.75

−0.73

0.82

Probability of the true class

0.27 → 0.98

Negative gradient: the loss drops if the weight goes up.

...and the same for all 12 parameters.

16 of 46

Vanishing and Exploding Gradients

17 of 46

Common Issues in Training

With lots of parameters, NN training can be somewhat unstable

  • Overfitting vs Underfitting
  • Vanishing / Exploding Gradient
  • Curse of Dimensionality

18 of 46

Backprop Multiplies

In our network, an input weight's gradient was a product of every stage's slope:

∂L/∂w⁽¹⁾ᵢⱼ = xᵢ · Σₖ w⁽²⁾ⱼₖ (pₖ − yₖ) · 1[zⱼ > 0]

Each extra layer adds one more weight and one more activation slope:

p − y

×

W₄ᵀ

×

slope

×

W₃ᵀ

×

slope

×

W₂ᵀ

×

slope

→

error at layer 1

If most factors are below 1, the product shrinks. If most are above 1, it blows up.

19 of 46

Vanishing vs Exploding

Vanishing gradient

0.25¹⁰ ≈ 0.000001

Sigmoid's slope is at most 0.25. After 10 layers almost no error is left, so the early layers stop learning.

Exploding gradient

2¹⁰ = 1024

Large weights grow the error at every layer. Early layers take huge steps and the loss can turn into NaN.

20 of 46

Gradient Size by Layer

A 10-layer network, measuring the error that reaches each layer.

Sigmoid: layer 1 gets a millionth of the signal

Large weights: layer 1 gets 500× the signal

Ideal ReLU: stays the same size

21 of 46

Exploding Gradient in Our Network

Gradient = input × error. What if x₂ were measured differently

Input x₂

Gradients for x₂'s weights

One step (lr = 0.1)

2

2.92, −3.66

0.37

2000

2924, −3655

366

22 of 46

Overfitting vs Underfitting

Overfitting: the model "memorizes" the training data, learning the noise and outliers

Underfitting: the model is "too simple" and fails to learn the pattern

23 of 46

How We Fix These

Problem

Fix

Vanishing gradient

ReLU instead of sigmoid, careful initialization, normalization

Exploding gradient

Normalization, keeping weights small (L1 / L2)

Overfitting

Regularization: L1, L2, early stopping, dropout

24 of 46

Regularization

Keeping the network from memorizing its training data

25 of 46

Bias vs Variance

Bias: failure to capture the underlying trend in the data

Variance: sensitivity to which subset (from the same distribution) we trained on

Expected error = Bias² + Variance + Irreducible noise

High bias

Simple model (few parameters) → underfitting

High variance

Complex model (many parameters) → overfitting

Regularization: changes to training made specifically to reduce overfitting.

26 of 46

Regularization Motivations

Example: "True distribution" of the data below is close to y = 2x₁

x₁

x₂

Y

Predicted Y

1

0.1

2.15

1.878

2

0.4

4.3

3.912

3

0.2

6.45

5.916

4

0.3

8.3

7.934

5

0.05

10.2

9.639

x₂ is just noise. It should not really contribute to the model.

27 of 46

Regularization: Early Stopping

Overfitting often happens when we train too long

If training loss ≈ 0, the model has learned the noise too

Stop when the test loss starts to rise

28 of 46

Regularization: L1

Loss = MSE + λ Σ |wᵢ|

sum of absolute values of every weight, with hyperparameter 0 < λ < 1

  • Penalizes weights just for being away from 0
  • "Useless" weights go to exactly 0
  • Smaller weights also help prevent exploding gradients

29 of 46

L1: Pushing Useless Weights to 0

The L1 gradient is always λ · sign(w): the same-sized push toward 0. Arrows show each update.

Risk: if λ is too large, L1 can cancel out useful gradients too.

30 of 46

Regularization: L1 Result

Updated model: it learns to ignore x₂

x₁

x₂

Y

Predicted y

1

0.1

2.15

1.99

2

0.4

4.3

3.98

3

0.2

6.45

5.97

4

0.3

8.6

7.96

5

0.05

10.2

9.95

Training loss is higher than last time. Why?

We no longer fit the noise, so we expect a higher training loss but a better test loss.

31 of 46

Regularization: L2

Loss = MSE + λ Σ wᵢ²

Gradient = 2λw, so it scales with the weight

Large weights get a large push; small weights barely move

32 of 46

Regularization: Dropout

Example: "True distribution" of the data below is y = 2x₁ + 2x₂

x₁

x₂

Y

Predicted Y

1

1

4

4.08

2

2.1

8.2

8.43

3

2.9

11.8

12.23

4

4.1

16.2

16.73

5.5

4

19

22.03

Co-adaptation: a neuron relies on one specific input instead of all of them

The model may ignore x₂. Loss stays low until x₁ gets an outlier (last row).

Co-adaptation makes the model less robust.

33 of 46

Dropout

  • Each forward pass, randomly turn off neurons (multiply their output by 0)
  • No neuron can over-rely on one input, so it learns to use different combinations
  • No dropout during inference

34 of 46

Dropout: Spreading the Weight

When input 4 is turned off, the neuron must learn to use inputs 2 and 3: a "distributed" representation.

Risk: turning off too many neurons → Underfitted model

35 of 46

Comparison of Techniques

Category

L1

L2

Dropout

How it behaves

Pushes small weights to exactly zero, selects features

Pushes all weights toward zero without eliminating them

Learns to predict using random subsets of the network

Impact on gradients

Not differentiable at zero (handled in practice via subgradients)

Fully differentiable, smooth optimization

Gradient not directly affected

Risk

May zero out too many inputs; unstable with correlated inputs

Leaves many small weights that can still overfit

Rate too high: slow training or no convergence

Best use cases

Feature selection, sparse inputs (e.g. text)

General purpose; default choice in many models

Large models, limited data, robust generalization

36 of 46

Normalization

Putting inputs and layers on the same scale

37 of 46

Normalization

Example: model predicting housing price from number of rooms and square footage

Bedrooms

Square Footage

Predicted Price

2

2000

360,000

3

2000

440,000

4

2000

520,000

4

2100

526,000

4

1900

519,200

4

2200

530,050

Orange rows: small changes in bedrooms → large changes in price, so w_room has a large gradient

Blue rows: big changes in square footage → small changes in price, so w_space has a small gradient

38 of 46

Normalization: Loss Landscape

Contour map: each ring is one loss level; the star is the lowest loss

Small changes in w_bedrooms cause large changes in loss, so it dominates the gradient

Steps zigzag: training is slow and may not converge

Some weights become huge (exploding gradient), others tiny (vanishing gradient)

39 of 46

Standardization

x′ = (x − μ) / σ

Center each feature at mean 0 and scale it to standard deviation 1

Bedrooms

Square Footage

​

Bedrooms′

Square Footage′

2

2000

→

−1.96

−0.35

3

2000

→

−0.65

−0.35

4

2000

→

0.65

−0.35

4

2100

→

0.65

0.71

4

1900

→

0.65

−1.41

4

2200

→

0.65

1.77

Ranges are similar now, so neither weight dominates the gradient.

40 of 46

Normalized Loss Landscape

Cleaner loss landscape → Better gradient updates

41 of 46

Batch Normalization (BatchNorm)

Can we also normalize inside the network? For each neuron, normalize its pre-activations z across the batch.

​

  • Batch: A group of inputs that you pass in
    • You calculate the gradients for all of the inputs in the batch
    • Average them out and update by that average gradient

z for neuron A

Input 1: 3

Input 2: 4

Input 3: 2

Input 4: 5

Input 5: 6

→

Mean and std

μ = 4

σ = 1.41

→

ẑ = (z − μ) / σ

−0.71

0.0

−1.41

0.71

1.41

→

Scale and shift

γ ẑ + β

then the activation function

42 of 46

BatchNorm: γ, β, and Batch Size

  • Normalizing forces mean 0 and variance 1, so we "forget" the true mean and variance
  • Learned γ ("stretch") and β ("shift") let the network rescale as needed
  • The mean and variance now depend on the batch: the smaller the batch, the noisier they are
  • That noise acts as regularization, but it is harder to tune than L1, L2, or dropout

43 of 46

Layer Normalization (LayerNorm)

For one input, normalize each neuron's pre-activation against the other neurons in the same layer. No batch needed.

z for input 1

Neuron A: 3

Neuron B: 4

Neuron C: 2

Neuron D: 5

Neuron E: 6

→

Mean and std

μ = 4

σ = 1.41

→

ẑ = (z − μ) / σ

−0.71

0.0

−1.41

0.71

1.41

→

Scale and shift

γ ẑ + β

then the activation function

44 of 46

LayerNorm vs BatchNorm

BatchNorm: one feature, across the batch

Unstable with small or unrepresentative batches, but has built-in regularization

LayerNorm: one input, across the layer

Independent of other samples; preferred in recent architectures like Transformers

45 of 46

Summary

Problem

Why it happens

Fix

Vanishing gradient

Many factors below 1 multiply (sigmoid slopes)

ReLU, careful init, normalization

Exploding gradient

Large inputs or weights multiply the error

Normalize inputs, L1 / L2

Uneven feature scales

One weight dominates the gradient

Standardization, BatchNorm, LayerNorm

Overfitting

The model fits the noise

L1, L2, early stopping, dropout

46 of 46

Next Week: Image Models