Multi-layer perceptron architecture
What is an MLP?
Each layer contains multiple neurons (nodes), and every neuron in layer is connected to every neuron in layer (fully connected). Information flows forward only—no cycles.
Why Multiple Layers?
Single-layer perceptrons can only learn linearly separable functions. The XOR problem famously cannot be solved by a single layer. Adding hidden layers allows the network to learn non-linear decision boundaries by composing simple transformations.
Where:
- = activations from previous layer (inputs to this neuron)
- = weight from neuron in layer to neuron in layer
- = bias term for neuron
- = pre-activation (weighted sum)
- = activation (after applying non-linearity)
- = activation function (sigmoid, ReLU, tanh, etc.)
Why this formula? Each neuron performs a weighted vote of its inputs, adds a bias (shifts the decision boundary), then applies a non-linear function. Without , stacking layers would collapse to a single linear transformation: . The non-linearity breaks this and enables learning complex patterns.
Architecture Components
Input Layer
- Purpose: Holds the raw feature vector
- No computation: These "neurons" just pass values forward
- Size: Determined by your data (e.g., 784 for 28×28 pixel images, 100 for 100 features)
Hidden Layers
How many neurons per layer? Common heuristics:
- Start with 2-3x the input size
- Use powers of 2 (32, 64, 128, 256) for computational efficiency
- More neurons = more capacity but risk of overfitting
- Deeper (more layers) often beats wider (more neurons per layer) for the same parameter count
Derivation of layer output (vectorized form):
For the entire layer with neurons:
Where is an matrix ( = number of neurons in layer ), and is applied element-wise.
Why matrix form? Efficiently computes all neurons in parallel. Modern libraries (NumPy, PyTorch) are optimized for matrix operations, making this100-1000x faster than loping over individual neurons.
Output Layer
- Size: Depends on the task
- Binary classification: 1 neuron with sigmoid ()
- Multi-class: neurons with softmax (probabilities sum to 1)
- Regression: 1 neuron, no activation or linear activation
Why exponentiation?
- Makes all outputs positive
- Larger logits become much larger probabilities (amplifies differences)
- Outputs sum to 1 (valid probability distribution)
Activation Functions
Common Choices
ReLU (Rectified Linear Unit):
- Why? Fast to compute, doesn't saturate for positive values, enables training deep networks
- Drawback: "Dying ReLU" problem—neurons can get stuck at 0 if weights push always negative
Sigmoid:
- Why? Outputs in , interpretable as probability
- Drawback: Saturates (gradient near 0 for large ), causes vanishing gradients
Tanh:
- Why? Zero-centered (mean output = 0), symmetric
- Drawback: Also saturates, but less problematic than sigmoid
Leaky ReLU:
- Why? Fixes dying ReLU by allowing small negative gradients
Task: Classify if a tumor is malignant (1) or benign (0) from10 features.
Architecture:
- Input layer: 10 neurons (features: radius, texture, perimeter, etc.)
- Hidden layer 1: 16 neurons, ReLU activation
- Hidden layer 2: 8 neurons, ReLU activation
- Output layer: 1 neuron, sigmoid activation
Forward pass for one sample :
-
Hidden layer 1:
Why this step? We're projecting the 10D input into a 16D space where patterns might be more separable.
-
Hidden layer 2:
Why this step? Further refining the representation into8D space that captures higher-level tumor characteristics.
-
Output layer: Why sigmoid? Squashes output to so we can interpret as probability: .
If , we predict malignant (typically threshold at 0.5).
Parameter count: parameters.
Task: Classify 28×28 grayscale images into digits 0-9.
Architecture:
- Input: 784 neurons (28×28 flattened pixels)
- Hidden 1: 128 neurons, ReLU
- Hidden 2: 64 neurons, ReLU
- Output: 10 neurons (one per class), softmax
Forward pass:
-
Flatten image:
-
Hidden 1:
Why 128 neurons? Captures stroke patterns, curves, edges.
-
Hidden 2:
Why 64 neurons? Combines stroke patterns into digit-like features (loops, lines, intersections).
-
Output:
Why softmax? Converts 10 scores (logits) into probabilities: where .
If output is , we predict class 3 (highest probability).
Parameter count: parameters.
Why this step? The network learns which pixel combinations correspond to which digits through training (backpropagation + gradient descent).
Universal Approximation Theorem
What does this mean? Given enough neurons, an MLP can theoretically learn any pattern. But: this says nothing about how many neurons "enough" is, or whether we can actually find the right weights (training might fail).
In practice, deeper networks (more layers, fewer neurons per layer) train better and generalize better than very wide shallow networks.
Design Considerations
Width vs. Depth
Width = neurons per layer
Depth = number of layers
Modern trend: Deeper is better (ResNets have 50-200+ layers).
Why deeper?
- Each layer learns a level of abstraction (layer 1: edges, layer 2: textures, layer 3: parts, layer 4: objects)
- Fewer parameters for the same capacity (more efficient)
- Better generalization (deeper networks have implicit regularization)
Trade-off: Very deep networks are harder to train (vanishing/exploding gradients) → need techniques like batch normalization, skip connections (ResNets).
Hyperparameters to Choose
- Number of hidden layers: Start with 2-3, increase if underfitting
- Neurons per layer: Common: 32, 64, 128, 256
- Activation functions: ReLU for hidden layers (default), sigmoid/softmax for output
- Initialization: Xavier/He initialization (prevents vanishing/exploding activations at start)
- Regularization: Dropout, L2 penalty to prevent overfitting
Why it feels right: More capacity should learn more complex patterns.
Steel-man: If you have infinite data and perfect optimization, yes. In reality, more capacity leads to overfitting—the network memorizes training data instead of learning general patterns. The test error increases even as training error decreases.
Fix: Use regularization (dropout, L2), early stopping, or reduce capacity. The goal is the sweet spot: enough capacity to capture true patterns, not so much that you fit noise.
Why it feels right: Activations are just functions, should work anywhere.
Steel-man: The output activation must match your loss function and task. For binary classification with BCE loss, you need sigmoid (outputs in ). For multi-class with cross-entropy, you need softmax (valid probability distribution). Using ReLU in output for classification would give negative values or , breaking probability interpretation and loss computation.
Fix: Match output activation to task:
- Binary classification → sigmoid
- Multi-class → softmax
- Regression → linear (no activation) or ReLU if outputs must be positive
Why it feels right: Weights already control the transformation, bias seems redundant.
Steel-man: Without bias, every decision boundary/hyperplane must pass through the origin. For a single neuron , the activation switches at always. With bias , it switches at (shiftable threshold). Bias gives the network freedom to shift functions vertically, crucial for fitting data that doesn't center at zero.
Fix: Always include bias unless you've standardized inputs to zero mean AND have a specific reason (very rare).
Connections
- 3.1.01-SinglePerceptron-and-Linear-Separability – MLPs solve the XOR problem single perceptrons cannot
- 3.1.03-Backpropagation-Algorithm – How MLPs actually learn (gradient-based weight updates)
- 3.1.04-Activation-Functions – Deep dive into sigmoid, ReLU, tanh, and others
- 3.2.01-Gradient-Descent-Optimization – Training algorithm that updates MLP weights
- 3.3.02-Dropout-Regularization – Prevents overfitting in deep MLPs
- 4.1.01-Convolutional-Neural-Networks – Specialized architecture for images (more efficient than fully-connected MLPs)
- 2.1.05-Feature-Engineering – MLPs automatically learn features that traditional ML requires manual engineering for
Recall
Imagine explaining to a12-year-old:
"Think of an MLP like a team of detectives solving a mystery. The first detective (input layer) collects all the clues (features). Then groups of detectives (hidden layers) discuss and combine clues—the first group notices simple things ('this suspect was near the scene'), the next group combines those ('this suspect was near the scene AND has no alibi'), and so on. Finally, the head detective (output layer) makes the final decision based on what all the teams found.
Each detective has their specialty (different weights), and they vote on what's important. The more detective teams you have (more layers), the more complex patterns they can recognize. But too many teams might argue over tiny details that don't matter (overfitting)!
The 'activation function' is like each detective's decision rule: sigmoid is'I'm partially sure', ReLU is 'If I see something suspicious, I'll tell you, otherwise I stay quiet', and softmax is 'Out of all these suspects, here's who I think is most guilty'."
Each layer refines the representation. Data flows forward only (feedforward). Hidden layers are the magic—they learn intermediate features automatically.
#flashcards/ai-ml
What is a multi-layer perceptron (MLP)? :: A feedforward neural network with at least one hidden layer between input and output, where each layer is fully connected to the next. It can learn non-linear decision boundaries.
Why do we need multiple layers instead of just one?
What are the three main components of an MLP?
Write the forward pass equation for a single neuron.
Why are activation functions necessary?
What activation function should you use for binary classification output?
What activation function should you use for multi-class classification output? :: Softmax, because it converts logits into a valid probability distribution (all positive, sum to 1) over classes.
What is the purpose of hidden layers?
Why include bias terms in neurons?
What does "fully connected" mean?
What is the universal approximation theorem?
Why do we prefer deeper networks over wider networks?
What happens if you have too many neurons/layers?
What is the difference between pre-activation () and activation ()?
How many parameters does a layer with inputs and neurons have?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
MLP matlab Multi-Layer Perceptron ek aisa neural network hai jisme kam se kam ek hidden layer hota hai input aur output ke bech. Socho ek factory ki tarah - pehli layer raw material lati hai (input features jaise image pixels ya patient data), bech ki layers usme processing karti hai (hidden layers jo patterns dhoondhte hai), aur last layer final product deti hai (output jaise "ye image cat hai" ya "ye tumor benign hai").
Ek layer ka matlab hota hai neurons ka group. Har neuron apne inputs ka weighted sum nikalta hai (har input ko uski importance ke hisaab se multiply karta hai), phir ek bias add karta hai (threshold adjust karne ke liye), aur finally ek activation function apply karta hai jo non-linearity lata hai. Ye activation functions jaise ReLU ya sigmoid bahut zaroori hai - agar ye na ho toh kitni bhi layers stack karo, output linear hi rahega aur network complex patterns nahi seekh payega. Simple language me, agar teen layers hai W1, W2, W3 aur activation nahi hai toh ye bas W1×W2×W3 = ek bada matrix ban jata hai. Activation function ye linearity todta hai.
MLP ki power hai uski depth me. Pehli hidden layer simple chezein seekhti hai jaise edges ya colors, dosri layer combinations seekhti hai jaise textures ya shapes, aur age jake complex objects identify hote hai. Ye hierarchical learning natural hai - bilkul waise jaise bache pehle colors seekhte hai, phir shapes, phir pore objects. Lekin bahut zyada layers ya neurons dalne se overfitting ho sakta hai - network training data ko ratt leta hai instead of general patterns seekhna. Isliye sahi balance zaroori hai. Industry me ajkal trend hai deeper networks (zyada layers, kam neurons per layer) kyunki ye zyada efficient aur generalizable hote hai. Real applications me jaise image classification, medical diagnosis, ya language processing - sab jagah MLP-based architectures ka use hota hai bas structure thoda alag hota hai task ke hisaab se.