IF3270 ML - Neural Networks from Scratch (Midterm Notes)
1. The Perceptron
1.a Biological Motivation
McCulloch and Pitts (1943) described a neuron as a simple logic gate with binary outputs.
- Dendrites → x - receive input signals; analogous to input features
- Synapse strength → w - connection strength; analogous to weights
- Cell body → Σ - integrates all incoming signals; analogous to weighted sum
- Axon firing → f(net) - fires only when threshold is exceeded; analogous to activation function
1.b Formal Definition
Given real-valued input , weight vector , and bias (also written or ). Hypothesis space: .
Sign Function (output ±1) - Perceptron Training Rule:
Step Function (output 0/1) - Alternative Notation:
Both produce a discrete-valued output. The perceptron represents a hyperplane decision surface in .
1.c m-of-n Functions
A perceptron easily represents m-of-n functions: functions where at least of the inputs must be true. Set all input weights to the same value, then set threshold .
Example: AND with . Only when gives .
The XOR Problem (Minsky & Papert, 1969) A single perceptron can only solve linearly separable problems. XOR cannot be separated by any hyperplane - no single perceptron can learn it. This drove the development of multi-layer networks.
1.d Perceptron Training Rule
Uses the thresholded output for the update signal. Proven to converge if training data is linearly separable and learning rate is sufficiently small.
Algorithm (Mitchell 1997):
- Input: Training data , learning rate , activation: sign or step
- Init: Set each or small random value. Set .
- Repeat for each example :
- Compute prediction:
- If : update where
- Update error:
- Until: All examples correctly classified (), or max epochs reached.
Where: = learning rate · = true label (±1) · = predicted label (thresholded) · = -th feature of example . If correct: (no update).
Convergence Theorem The Perceptron Training Rule is guaranteed to converge in a finite number of steps if the training data is linearly separable and is sufficiently small. It does not converge if data is not linearly separable.
1.e The Delta Rule (Batch Gradient Descent)
When data is NOT linearly separable, the Perceptron rule fails. The Delta Rule (= Widrow-Hoff rule = LMS rule = Adaline rule) uses the unthresholded linear output and minimizes SSE - always converges to best-fit approximation.
Error Function - Sum of Squared Errors (SSE):
Where is the linear (unthresholded) output. The factor simplifies the derivative.
Gradient Vector:
Training Rule:
Weights updated once per epoch after accumulating over all .
1.f Stochastic & Mini-Batch Gradient Descent
| Variant | Update Rule | Notes |
|---|---|---|
| Batch GD | One update per epoch. Stable, but slow for large datasets. Can get stuck in local minima. | |
| Stochastic (Incremental) GD | One update per example. Faster, noisier gradient - can escape local minima. |
- Epoch - one full pass through all training data
- Batch Size - number of samples per mini-batch; if = 1 → true SGD; if = |D| → Batch GD; if 1 < b < |D| → Mini-batch SGD
- Step - processing one mini-batch, ending with one weight update. Steps per epoch = |D| / batch_size
Key Distinction Perceptron Training Rule uses thresholded output (sign/step) - only converges if linearly separable. Delta Rule / Batch GD uses unthresholded linear output - converges to best-fit regardless of separability.
2. Feedforward Neural Network (FFNN)
2.a From Adaline to FFNN
Adaline (ADAptive LInear NEuron) is a single-layer neural network and the direct bridge from the Perceptron to FFNN. It uses the identity activation for weight updates, and applies a threshold only at inference time.
The activation function here is the identity (linear). Threshold applied only at inference to produce class label 0 or 1. Multiple names: Delta Rule = LMS = Widrow-Hoff = Adaline.
2.b FFNN Architecture
- Input Layer (l=0) - receives feature vector ; no computation; width = number of features; convention: (bias)
- Hidden Layers - learn internal representations; one or more layers; non-linear activation required
- Output Layer - produces ; width = number of classes (classification) or 1 (regression)
- Depth - number of layers (hidden + output); deeper → learns more abstract, hierarchical features
- Width - neurons per layer; wider → more capacity but more parameters; notated as
- Fully Connected - every neuron in layer connects to every neuron in layer with a unique weight
2.c Forward Propagation
Goodfellow Notation - General Forward Pass:
Where: = pre-activation at layer · = post-activation · = weight matrix · = bias vector · = total cost · = loss function · = regularization
Compact Notation ( / style):
Mini-Batch X Notation:
is the mini-batch matrix of shape . When using batches: vs single input: .
2.d Number of Parameters
Where accounts for the bias weight per neuron. Example (Raschka): input=8, h1=12, h2=8, output=1 → total params.
2.e Worked Example: XOR with Sigmoid
- Input : ✓
- Input : ✓
- Input : ✓
3. Activation Functions & Loss Functions
3.a Why Non-linearity?
Universal Approximation Theorem A single hidden layer with sufficient neurons can approximate any continuous function to arbitrary accuracy. However, deep networks require exponentially fewer neurons than shallow networks for the same approximation quality, generalize better, and empirically outperform shallow networks. Test accuracy improves as depth increases; CNNs consistently outperform fully-connected nets with the same parameter count.
Without non-linearity, stacking any number of layers collapses to a single linear transformation.
3.b Common Activation Functions
| Function | Formula | Range | Notes |
|---|---|---|---|
| Step / Sign | {0,1} or {±1} | Perceptron. Non-differentiable → cannot use in backprop. | |
| Sigmoid (σ) | (0, 1) | Output as probability. Vanishing gradient for large |z|. | |
| Tanh | (−1, 1) | Zero-centered. Stronger gradients than sigmoid. Used in LeNet-5. | |
| ReLU | [0, ∞) | Most popular for hidden layers. No vanishing gradient for . Suffers from dying ReLU. | |
| Leaky ReLU | (−∞, ∞) | Fixes dying ReLU. Small slope for negative inputs. | |
| Softmax | (0,1), sum=1 | Output layer for multi-class. Converts logits to probability distribution. |
Key Derivatives (required for Backprop):
Sigmoid and tanh derivatives become very small near saturation → vanishing gradient. ReLU derivative is either 0 or 1 - no vanishing gradient for positive inputs.
3.c Loss Functions
Mean Squared Error (MSE) - Regression:
Use with linear output activation. Penalizes larger errors quadratically.
Binary Cross-Entropy - Binary Classification:
Use with sigmoid output.
Categorical Cross-Entropy - Multi-Class Classification:
Use with softmax output for classes. for the true class, 0 otherwise (one-hot encoding).
4. Backpropagation
4.a Three-Step Learning Procedure
- Forward Propagation: Compute output for input . Cache all pre-activations and post-activations .
- Backward Propagation: Compute error term for each unit. The target for hidden units is NOT directly available - it must be inferred from output deltas via the chain rule.
- Weight Update: Update every weight using the computed gradients and learning rate .
4.b Output Unit Gradient (with Sigmoid)
Using the chain rule for weight connecting unit to output unit :
Output unit error signal δ:
captures how wrong the output is, scaled by how sensitive the activation is at that operating point.
4.c Hidden Unit Gradient
For hidden unit , no direct target is available. Back-propagate error from all output units that receive from :
is a weighted sum of output deltas - this is the “propagating error backward” step.
4.d Weight Update (same for all layers)
4.e Full Backpropagation Algorithm (Mitchell, 1997)
BACKPROPAGATION(training_examples, η, n_in, n_out, n_hidden):
- Init: Create feed-forward network. Initialize all weights to small random values (e.g., between −0.05 and 0.05).
- Repeat until termination (fixed iterations / training error < threshold / validation criterion met). For each in training_examples:
- Forward pass: Compute output of every unit .
- Output deltas: For each output unit :
- Hidden deltas: For each hidden unit :
- Update weights:
Computational Efficiency One backward pass computes gradients for ALL parameters simultaneously, reusing cached forward-pass values. This makes deep network training feasible.
4.f Common Training Problems
| Problem | Cause | Fix |
|---|---|---|
| Vanishing Gradient | Gradients shrink exponentially through deep layers | ReLU, residual connections, batch normalization |
| Exploding Gradient | Gradients grow exponentially → unstable (NaN) | Gradient clipping, careful initialization |
| Local Minima | Batch GD can get stuck | SGD noise helps escape |
| Bad Learning Rate η | Too small → slow; too large → diverges | LR schedules, adaptive optimizers (Adam) |
| Overfitting | Network memorizes training data | Dropout, L1/L2 regularization , early stopping |
| Dying ReLU | Neurons always output 0 → zero gradient → never recover | Leaky ReLU (), He initialization |
5. Convolutional Neural Network (CNN)
An ANN that replaces general matrix multiplication with the convolution operation in at least one layer. Explicitly assumes inputs have grid-like (spatial) topology. (LeCun et al. 1989, 1998; Goodfellow et al. 2016)
5.a Why CNN? - The Problem with FFNN on Images
Dimensionality Explosion A RGB image has pixels. A single FFNN input→output layer requires billion multiplications. A CNN with a kernel needs only operations - roughly 60,000× more efficient.
Three core problems with FFNN on images:
- Dimensionality explosion - flattening a 2D/3D image to 1D and connecting every pixel to every neuron creates an impractical number of parameters
- Spatial information destroyed - flattening kills neighborhood relationships; pixels and their neighbors carry joint meaning (edges, textures)
- Parameter explosion → overfitting - more weights = more memorization, not better generalization
5.b Core CNN Concepts
- Input - a multidimensional array (e.g., RGB image stored as array)
- Kernel / Filter - small learnable weight matrix (e.g., 3×3 or 5×5) that slides over the input
- Feature Map - output produced when a kernel is convolved with the input; high values = pattern detected at that location
- Convolution - sliding a kernel over the input, computing dot products at each position
5.c Two Core Innovations
Local (Sparse) Connectivity: Each output neuron connects only to a local region of the input - the receptive field. A 3×3 kernel: each output connects to only 9 inputs, not thousands. Biologically inspired by Hubel & Wiesel (1959).
Parameter Sharing: The same kernel weights are used at every spatial position. One kernel is learned and applied everywhere - gives translation equivariance: the same feature anywhere uses the same detector.
| Configuration | Weights |
|---|---|
| Fully connected (FFNN) | >3,200 |
| Locally connected (no weight sharing) | 1,226 |
| Locally connected + weight sharing (CNN) | 206 |
(LeCun 1989 Net-3 comparison)
5.d The Convolution Operation
- 1D: Slide a kernel across a 1D input array, element-wise products, sum at each position.
- 2D (Grayscale): Kernel slides across both rows and columns, element-wise multiply + sum → one output value per position.
- 3D (RGB / Multi-channel): Kernel has depth = number of input channels (). A kernel → one feature map. Using different kernels → feature maps.
Output Dimension Formula:
Where: = input width/height · = filter size · = padding · = stride · Output volume = (for filters)
Padding Types:
- Valid (P=0): No padding → output shrinks each conv layer
- Same ( with ): Zero-pad to keep output same size as input
Worked Examples:
| Input Shape | Filters | P | S | V Calculation | Output Volume |
|---|---|---|---|---|---|
| 3×3×3 | 1, size 2×2×3 | 0 | 1 | 2×2×1 | |
| 3×3×2 | 3, size 2×2×2 | 0 | 1 | 2×2×3 | |
| 32×32×3 | 10, size 5×5×3 | 0 | 1 | 28×28×10 |
5.e The Three Stages of a CNN Layer
Stage 1 - Convolution (Affine Transform):
Kernel slides across input computing linear combinations. Produces raw feature map - still linear.
Stage 2 - Detector (Non-linearity / Activation):
Non-linear activation applied element-wise. Without this, stacking conv layers collapses to one linear transform. Example:
Stage 3 - Pooling (Downsampling):
Reduces spatial dimensions. Benefits: fewer parameters downstream, translation invariance, controls overfitting.
| Type | Operation | Notes |
|---|---|---|
| Max Pooling | Maximum value in each window | Most common. 2×2 pool with S=2 halves spatial dimensions. Preserves dominant features. |
| Average Pooling | Mean value in each window | Smoother downsampling. Used in LeNet-5. |
| L2-norm Pooling | in each window | Less common. Emphasizes larger activations. |
5.f Parameter Counting in CNN Layers
Number of Neurons in a Conv Layer:
Parameters WITHOUT Weight Sharing (locally connected):
Parameters WITH Weight Sharing (standard CNN):
Example (LeNet C1): params
5.g Full CNN Architecture Pattern
INPUT (H×W×C)
→ CONV + ReLU → POOL
→ CONV + ReLU → POOL
→ FLATTEN (1D vector)
→ FC (Dense)
→ OUTPUT (Softmax)
Feature Hierarchy Conv layer 1 → edges/colors. Conv layer 2 → corners/textures. Deeper layers → shapes, object parts, objects. Pooling reduces spatial size. FC layers do the final classification.
5.h LeNet-5 (LeCun et al., 1998)
First practical CNN for handwritten digit recognition (MNIST). Input: 32×32 grayscale. End-to-end training with backpropagation.
| Layer | Type | Output Shape | Details | Parameters |
|---|---|---|---|---|
| Input | Image | 32×32×1 | Grayscale, padded from 28×28 | - |
| C1 | Conv | 28×28×6 | 6 filters, 5×5, S=1, P=0, tanh · | |
| S2 | Avg Pool | 14×14×6 | 2×2 window, S=2 | 0 |
| C3 | Conv | 10×10×16 | 16 filters, 5×5, S=1, P=0, tanh · | |
| S4 | Avg Pool | 5×5×16 | 2×2 window, S=2 | 0 |
| Flatten | - | 400 | - | |
| FC C5 | FC | 120 | Fully connected, tanh | |
| FC F6 | FC | 84 | Fully connected, tanh | |
| Output | FC | 10 | 10 classes (digits 0–9), Softmax | |
| Total | 61,706 |
C3: . Tiny by modern standards (ResNet-50 ≈25M params), but proved CNN viability for image tasks for the first time.
5.i Notable CNN Architectures
| Architecture | Year | Key Innovation |
|---|---|---|
| LeNet-5 | 1998 | First practical CNN. Local connectivity + weight sharing. |
| AlexNet | 2012 | 8 layers, ReLU (novel), dropout, GPU training on ImageNet. Marked the “Rise of CNN.” |
| VGG16 | 2015 | 16 layers, only 3×3 filters. Full model: ~138M params. Input: 224×224×3. |
| GoogLeNet | 2014 | Inception modules: parallel filter paths of different sizes in one layer. |
| ResNet | 2015 | Skip (residual) connections: gradients flow directly through layers, enabling 50/101/152-layer nets. |
| Vision Transformer | 2020 | Transformer self-attention applied to image patches - no convolution needed. |
5.j CNN vs FFNN Comparison
| Aspect | FFNN (MLP) | CNN |
|---|---|---|
| Input handling | Flattened 1D vector - spatial structure lost | Grid-structured - spatial info preserved |
| Connectivity | Every neuron → every input (fully connected) | Each neuron → local receptive field only |
| Weight sharing | No - unique weight per connection | Yes - same kernel at every position |
| Spatial feature detection | No | Yes - kernels learn edges, textures, shapes |
| Parameter count | Very high for image inputs | Much lower due to weight sharing |
| Overfitting tendency | Higher for image tasks | Lower for image tasks |
| Feature engineering | Manual | Automatic (learned filters) |
| Translation invariance | No | Yes (shared filters + pooling) |
| Best for | Tabular data, fixed-size vectors | Images, audio spectrograms, grid-structured data |
Two Key Properties of CNN(1) Translation equivariance: if the input shifts, the feature map shifts by the same amount - a feature is detected regardless of where it appears. (2) Hierarchical feature learning: layer 1 learns edges → layer 2 learns textures → deeper layers learn shapes → object parts → full objects.
6. Glossary
6.a Math & Notation
| Symbol | Meaning |
|---|---|
| input vector / mini-batch | |
| weights | |
| bias | |
| / net / | pre-activation |
| / | post-activation |
| predicted output | |
| / | true label / target |
| / | error / total cost |
| learning rate | |
| error signal (delta) | |
| regularization rate | |
| regularizer | |
| sigmoid | |
| activation function | |
| kernel/filter | |
| output dimension | |
| filter size | |
| padding | |
| stride |
6.b Key Terms
Perceptron: artificial neuron for linear classification · McCulloch-Pitts: early neuron model · threshold θ: cutoff for firing · sign function: outputs ±1 · step function: outputs 0/1 · hyperplane decision surface: linear separator · linear separability: classes separable by a hyperplane · XOR problem: not linearly separable · m-of-n function: true if at least m inputs are true · epoch: one full pass over the data · delta rule: LMS / Widrow-Hoff update · SSE: sum of squared errors
feedforward: information flows only forward · MLP: multi-layer perceptron · depth: number of layers · width: number of neurons per layer · forward propagation: compute outputs from inputs · backpropagation: reverse-mode gradient computation · chain rule: derivative composition rule · vanishing gradient: gradients shrink through layers · exploding gradient: gradients grow too large · overfitting: memorizes training data · underfitting: model too simple · dying ReLU: neurons stuck at zero · one-hot encoding: vector with one active class entry · universal approximation theorem: single hidden layer can approximate any continuous function
convolution / cross-correlation: sliding local dot product · kernel / filter: learnable weight window · feature map: convolution output · receptive field: local input region a filter sees · parameter sharing: same kernel reused everywhere · sparse connectivity: each output connects to local inputs · max pooling: take maximum value per window · average pooling: take mean value per window · flatten: reshape volume into 1D vector · translation equivariance: shifted input shifts feature map · translation invariance: small shifts do not change output much · feature hierarchy: edges to objects across layers · : output dimension formula · : CNN parameter formula
References
- Goodfellow, Bengio & Courville (2016) - Deep Learning
- LeCun et al. (1989) - Backpropagation Applied to Handwritten Zip Code Recognition
- LeCun et al. (1998) - Gradient-Based Learning Applied to Document Recognition (LeNet-5)
- Mitchell (1997) - Machine Learning, Ch. 4
- Raschka, Liu & Mirjalili (2022) - Machine Learning with PyTorch and Scikit-Learn, Ch. 11
- IF3270 Pembelajaran Mesin - Lecture Slides, Sem 2-2025/2026, Tim Pengajar IF3270