Jaber Notes · 11 of 16
Neural Network Fundamentals
MLPs, activations, losses, full backprop derivation, init, gradients.
The neural network from first principles: perceptron to MLP, every common activation and its derivative, the full backpropagation derivation with vectorized mini-batch gradients, weight initialization variance analysis, and the vanishing-gradient fix.
Visual reference
Forward pass through a network
Sigmoid function
Build everything from first principles: from a single neuron up to a full deep network, forward pass, and the complete backpropagation derivation.
Table of contents
- From linear models to neural networks
- The perceptron and its limits
- Multi-layer perceptron (MLP)
- Activation functions
- Forward pass (computation graph)
- Loss functions for deep learning
- Backpropagation — full derivation
- Universal approximation theorem
- Weight initialization
- Vanishing and exploding gradients
1. From linear models to neural networks
1.1 Limitation of linear classifiers
A single linear model can only separate classes with a hyperplane. For the XOR problem:
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
No single line separates the 0s from the 1s. Minsky & Papert (1969) showed the perceptron cannot learn XOR — this was a key insight motivating multi-layer networks.
1.2 The key idea: learned feature transformations
Instead of hand-engineering features, learn a hierarchy of transformations:
Each layer transforms its input into a new representation. The final layer is (usually) a linear classifier on top of these learned features.
2. The perceptron and its limits
2.1 Original perceptron (Rosenblatt, 1958)
A single neuron:
Perceptron learning rule: for misclassified sample :
Perceptron convergence theorem: if data is linearly separable, the algorithm converges in a finite number of steps bounded by (\|\mathbf{x}\|_\max \cdot \|\mathbf{w}^\star\| / \text{margin})^2.
Limitation: non-differentiable step function → cannot use gradient descent. Solution: smooth differentiable activations.
3. Multi-layer perceptron (MLP)
3.1 Architecture
An MLP with layers. Denote:
- (input, dimension )
- Layer : weight matrix , bias
- = number of neurons in layer ; = output size
Pre-activation (linear combination):
Post-activation (element-wise nonlinearity):
where is an activation function.
Final output: .
3.2 Parameters
Total parameters:
4. Activation functions
4.1 Sigmoid
Derivative: . Max derivative = 0.25 (at ).
Problems:
- Saturates at large : gradient → 0 (vanishing gradient).
- Not zero-centered: outputs always positive → all-positive or all-negative gradients for weights, causing zig-zag updates.
- Expensive ().
Use: output layer for binary classification.
4.2 Tanh
Derivative: . Max derivative = 1 (at ).
Zero-centered (advantage over sigmoid), but still saturates at large .
4.3 ReLU (Rectified Linear Unit)
Derivative: (subgradient: set to 0 at ).
Advantages:
- Does not saturate for .
- Sparse activation (exactly 0 for ) — natural regularization.
- Fast to compute.
- Default choice for hidden layers in modern networks.
Problems:
- Dying ReLU: if always (e.g., large negative bias, large learning rate update), gradient = 0 → neuron never updates.
- Not zero-centered.
- Unbounded (no saturation for large positive ).
4.4 Leaky ReLU and variants
Fixes dying ReLU: small but nonzero gradient for negative inputs.
PReLU (Parametric ReLU): is learned per-neuron.
ELU (Exponential Linear Unit):
Smooth, zero-centered in expectation, theoretically motivated — but slower than ReLU.
4.5 GELU (Gaussian Error Linear Unit)
where is the standard Gaussian CDF. Approximation: .
Stochastic interpretation: GELU = expected value of where . "Soft" stochastic gating.
Default activation in BERT, GPT, and most modern transformers.
4.6 Softmax (output layer, multi-class)
Properties: outputs sum to 1, all positive → valid probability distribution.
Numerical stability: subtract before exponentiating (doesn't change value):
Jacobian of softmax: , where is Kronecker delta.
4.7 Comparison summary
| Activation | Range | Zero-centered | Saturates | Dying units | Best use |
|---|---|---|---|---|---|
| Sigmoid | No | Yes | No | Binary output | |
| Tanh | Yes | Yes | No | LSTM gates, old nets | |
| ReLU | No | No (pos) | Yes | Default hidden | |
| Leaky ReLU | No | No | No | When dying ReLU observed | |
| GELU | Yes | No | No | Transformers | |
| Softmax | — | — | — | Multi-class output |
5. Forward pass (computation graph)
5.1 Example: 2-layer network
Input , hidden layer , output scalar .
5.2 Vectorized over a mini-batch
For mini-batch (batch size ):
All operations are matrix multiplications → parallelizable on GPU.
6. Loss functions for deep learning
6.1 Binary cross-entropy
For binary labels , output :
6.2 Categorical cross-entropy
For one-hot labels , output :
6.3 MSE (regression)
6.4 Huber loss (robust regression)
Quadratic near zero (smooth), linear for large errors (robust to outliers).
6.5 Numerical trick: log-sum-exp + softmax
In practice, compute cross-entropy directly from logits (numerically stable):
This is what torch.nn.CrossEntropyLoss and tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) do internally.
7. Backpropagation — full derivation
7.1 The core idea
Backpropagation is reverse-mode automatic differentiation: efficiently compute for all parameters by reusing computations via the chain rule.
Two passes:
- Forward pass: compute and cache all intermediate values .
- Backward pass: propagate gradients from loss back to inputs using the chain rule.
7.2 Define the error signal
Define (delta / error) as the gradient of the loss w.r.t. the pre-activation of layer :
7.3 Output layer delta
For softmax + cross-entropy (very clean result):
Derivation: let where .
7.4 Backpropagating through a layer
By the chain rule, from layer to layer :
where is element-wise multiplication and is the derivative of the activation.
7.5 Gradients w.r.t. parameters
For a mini-batch of size :
where contains for each sample.
7.6 Complete backprop algorithm
Forward pass:
for l = 1 to L:
z[l] = W[l] @ a[l-1] + b[l]
a[l] = activation(z[l])
L = loss(a[L], y)
Backward pass:
delta[L] = dL/dz[L] # output layer delta
for l = L-1 downto 1:
dL/dW[l] = delta[l] @ a[l-1].T / B
dL/db[l] = mean(delta[l], axis=0)
delta[l] = (W[l+1].T @ delta[l+1]) * sigma'(z[l])
Parameter update (SGD):
for l = 1 to L:
W[l] -= lr * dL/dW[l]
b[l] -= lr * dL/db[l]7.7 Complexity
Forward pass: operations. Backward pass: same order — backprop has the same computational cost as 2 forward passes.
Memory: need to cache all activations during forward pass for use in backward pass. Memory depth × batch size × layer size.
7.8 Automatic differentiation (autograd)
Modern frameworks (PyTorch, JAX, TensorFlow) implement dynamic or static computation graphs and handle backprop automatically via:
- Forward mode AD: accumulate derivatives forward. Efficient for .
- Reverse mode AD (backprop): accumulate derivatives backward. Efficient for (i.e., scalar loss). This is what we always use in DL.
import torch
import torch.nn as nn
x = torch.tensor([1.0, 2.0], requires_grad=True)
W = torch.randn(3, 2, requires_grad=True)
loss = ((W @ x)**2).sum()
loss.backward()
print(W.grad) # dL/dW computed automatically8. Universal approximation theorem
8.1 Statement
Cybenko (1989) / Hornik (1991): An MLP with a single hidden layer of sufficiently many neurons and a non-polynomial activation function can approximate any continuous function on a compact subset of to arbitrary precision.
Formally: for any and continuous , there exists an MLP with one hidden layer such that .
8.2 Implications and limits
- Existence does not imply learnability (may require exponentially many neurons, or gradient descent may not find the solution).
- Width vs depth tradeoffs: deep networks with neurons can represent functions that require exponential neurons in a shallow network.
- The theorem motivates why neural nets can work, but not how to train them.
9. Weight initialization
9.1 Why initialization matters
- All-zero init: all neurons produce the same gradient (symmetry) → learn the same features. Symmetry breaking requires random init.
- Too-large init: activations saturate or explode.
- Too-small init: vanishing gradients.
9.2 Variance analysis
For layer with inputs, if weights and inputs have unit variance:
To keep variance stable across layers: .
9.3 Xavier / Glorot initialization
Derived for tanh/sigmoid activations. Balances forward and backward variance:
9.4 He / Kaiming initialization
Derived for ReLU activations. Since ReLU zeros out half the inputs on average:
Derivation: For ReLU, (half the distribution contributes). To keep variance constant: .
# PyTorch uses Kaiming uniform by default for Conv and Linear
nn.init.kaiming_normal_(layer.weight, mode='fan_in', nonlinearity='relu')
nn.init.xavier_uniform_(layer.weight)9.5 Orthogonal initialization
Initialize weight matrices as random orthogonal matrices. Preserves gradient norms exactly in linear networks; works well for RNNs.
10. Vanishing and exploding gradients
10.1 Formal analysis
In a deep network, the gradient of the loss w.r.t. early layer weights:
This is a product of matrices (each element also multiplied by a scalar derivative).
If the eigenvalues of are : gradients shrink exponentially → vanishing gradients. If eigenvalues are : gradients grow exponentially → exploding gradients.
10.2 Sigmoid/tanh saturation
Sigmoid derivative: (at ). For all : derivative . Product of 10 layers: . Early layers receive negligible gradients.
10.3 Solutions
| Problem | Solution |
|---|---|
| Vanishing (sigmoid/tanh) | Use ReLU; use residual connections (skip connections) |
| Vanishing (depth) | Batch normalization; careful init |
| Exploding gradients | Gradient clipping () |
| Both | Residual networks (ResNets) — gradient can flow directly through skip connections |
10.4 Skip connections (ResNets preview)
The term creates a direct path for gradients:
The identity ensures gradients can flow even if .
*File: notes/11_neural_network_fundamentals.md — next: notes/12_training_deep_networks.md*