Neural Network Math & Techniques
ML@UVA Lecture 4
Presenter: Shubs Debsarkar
Neural Network Internals
Recap: One Neuron
Logistic regression: One Neuron
Forward
z = w₁x₁ + w₂x₂ + b
ŷ = σ(z)
Backward
∂L/∂z = ŷ − y
∂L/∂wᵢ = (ŷ − y) · xᵢ
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
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.
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⁽¹⁾
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
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!
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
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
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⁽²⁾ᵀ
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?
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.
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) |
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.
Vanishing and Exploding Gradients
Common Issues in Training
With lots of parameters, NN training can be somewhat unstable
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.
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.
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
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 |
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
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 |
Regularization
Keeping the network from memorizing its training data
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.
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.
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
Regularization: L1
Loss = MSE + λ Σ |wᵢ|
sum of absolute values of every weight, with hyperparameter 0 < λ < 1
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.
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.
Regularization: L2
Loss = MSE + λ Σ wᵢ²
Gradient = 2λw, so it scales with the weight
Large weights get a large push; small weights barely move
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.
Dropout
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
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 |
Normalization
Putting inputs and layers on the same scale
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
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)
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.
Normalized Loss Landscape
Cleaner loss landscape → Better gradient updates
Batch Normalization (BatchNorm)
Can we also normalize inside the network? For each neuron, normalize its pre-activations z across the batch.
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
BatchNorm: γ, β, and Batch Size
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
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
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 |
Next Week: Image Models