Memory tricks that make neurons, backprop and deep architectures click
From the single neuron to backpropagation through thousands of layers -- these memory tricks lock in how neural networks are built, trained, and prevented from overfitting.
Or continue to the sub-topics below for more specialized Study Rooms and Forums
Neural Networks
Memory Tricks
Proven Mnemonics & Acronyms — fast to learn, hard to forget.
Foundation
WISE -- Weights, Input, Summation, Excitation (activation) -- what every neuron does
INPUT TIMES WEIGHT THEN SUM THEN ACTIVATE THEN OUTPUT
Without activation functions, stacking layers is pointless -- still just one linear function
Inputs times Weights, summed plus bias: z = w1x1 + w2x2 + b. Activation function applies nonlinearity. Without activations, any depth network can only learn linear functions. Nonlinear activations allow networks to approximate any function (Universal Approximation Theorem). The activation function is what makes deep learning powerful.
Weights
Learned parameters -- how important is each input?
Bias
Allows activation threshold to shift -- also learned
Summation z
z = w1x1 + w2x2 + ... + b -- the dot product
Activation
Applies nonlinearity -- without it, deep = pointless
Activation Functions
Silly Tom Really Likes -- Sigmoid, Tanh, ReLU, Leaky ReLU
Sigmoid (Silly): squashes to 0-1, use ONLY at binary output layer, vanishing gradient kills it in hidden layers. Tanh (Tom): output -1 to 1, centered at zero, still vanishes in deep nets. ReLU (Really): max(0,x), THE default for hidden layers, fast, avoids vanishing gradient. Leaky ReLU (Likes): fixes dying ReLU with small negative slope. Softmax: always at multi-class output -- converts logits to probabilities summing to 1.
Sigmoid
Binary output layer ONLY -- never in hidden layers
Tanh
Centered at zero -- slightly better than sigmoid, still vanishes
ReLU
max(0,x) -- default for hidden layers, fast, no vanishing
Softmax
Multi-class output -- logits to probabilities (sum=1)
Architecture
IHO -- Input, Hidden, Output -- every network has these three types of layers
DEPTH = HIDDEN LAYERS AND WIDTH = NEURONS PER LAYER
Deep networks learn hierarchical features -- edges to shapes to objects to concepts
Input layer: one neuron per feature, no computation. Hidden layers: where representations are learned. Output layer: one per class (classification) or one neuron (regression). Depth allows hierarchical representation learning. Universal Approximation Theorem: even one hidden layer with enough neurons can approximate any continuous function.
Input layer
One neuron per feature -- no computation, just passes data in
Hidden layers
Where representations are learned -- the depth
Output layer
One per class (classification) or one (regression)
Depth vs width
Deep = hierarchical features. Wide = capacity within a layer.
Backpropagation
ERROR flows BACKWARDS like a RIVER OF REGRET -- backpropagation in one vivid image
FORWARD PREDICT THEN MEASURE REGRET THEN FLOW BACKWARD THEN ADJUST
Each weight gets its blame assigned via the chain rule -- then gets updated
Forward pass: data flows forward producing a prediction. Loss: measures how wrong the prediction was -- the regret. Backward pass: regret flows BACKWARD through the network via chain rule of calculus, assigning blame (gradient) to each weight. Weight update: w = w - alpha times gradient. Adam optimizer: adaptive per-parameter learning rate -- the standard default (lr=0.001).
Forward pass
Input flows through network -- prediction at output
Loss
Measures how wrong -- the regret (MSE, cross-entropy)
DROP -- Dropout Randomly Omits Percentages of neurons during training
DROPOUT AND BATCH NORM AND L2 AND EARLY STOPPING -- FOUR TOOLS
Batch Normalization speeds training so dramatically it should be used by default
Dropout: 20-50% neurons disabled per step, forces redundant representations, scale by (1-p) at inference. Batch Normalization: normalizes layer inputs to mean=0, std=1, speeds training dramatically, allows higher learning rates. L2 weight decay: penalizes large weights. Early stopping: monitor validation loss, stop when it rises.
Dropout
20-50% neurons disabled per step -- inference uses all, scaled by (1-p)
Batch Normalization
Normalize layer inputs -- speeds training, allows higher LR
L2 weight decay
Penalize large weights -- keeps model simple
Early stopping
Stop when validation loss stops improving
Hyperparameters
BLAND -- Batch size, Layers, Activation, Neurons, Dropout -- set BEFORE training
NOT LEARNED FROM DATA -- SET BY THE DEVELOPER BEFORE TRAINING BEGINS
Learning rate is the single most important hyperparameter -- start with 0.001 for Adam
Learning rate (most critical), batch size (32-128 typical), number of layers, neurons per layer, activation functions, dropout rate. Tuning methods: random search (often better than grid for same budget), Bayesian optimization. Transfer learning: start from pretrained model -- dramatically helps with small datasets.
Learning rate
Most critical -- too high=diverges, too low=slow. Start 0.001.
Batch size
32-128 typical. Small=noisy. Large=stable.
Tune with
Random search or Bayesian optimization
Transfer learning
Pretrained model + fine-tune = state of art with small data
Loss Functions
MSE for regression and Cross-Entropy for classification -- match loss to task
WRONG LOSS FUNCTION = MODEL CANNOT LEARN WHAT YOU NEED
Binary cross-entropy with sigmoid. Categorical cross-entropy with softmax. Always pair correctly.
MSE (Mean Squared Error): regression, sensitive to outliers. MAE: regression, robust to outliers. Binary Cross-Entropy: binary classification with sigmoid output. Categorical Cross-Entropy: multi-class classification with softmax output. Loss is optimized during training (must be differentiable). Metric is what you report (can be anything -- accuracy, F1, AUC).
MSE
Regression -- averages squared prediction errors
Binary CE
Binary classification + sigmoid output
Categorical CE
Multi-class + softmax output
Loss vs Metric
Loss: optimized. Metric: reported. They can differ.
Weight Initialization
ZERO INIT = all neurons learn the SAME thing -- symmetry never breaks
XAVIER FOR SIGMOID AND TANH -- HE FOR RELU -- NEVER ZERO
Random initialization breaks symmetry -- every neuron starts differently and learns different features
Zero initialization: catastrophic -- all neurons identical, all gradients identical, network never diversifies (symmetry problem). Xavier: scales by 1/sqrt(n_in) -- designed for sigmoid and tanh. He initialization: scales by 2/sqrt(n_in) -- designed for ReLU (accounts for half of neurons being zeroed). Batch Normalization reduces sensitivity to initialization.
Zero init
Catastrophic -- symmetry problem -- never use
Xavier init
For sigmoid and tanh activations
He init
For ReLU -- larger variance since half neurons are zeroed
Batch Norm
Reduces sensitivity to initialization choice
Gradient Problems
DEEP networks VANISH or EXPLODE -- residual connections and clipping are the fixes
VANISHING = EARLY LAYERS DON'T LEARN -- EXPLODING = WEIGHTS BLOW UP
ResNet skip connections solved the vanishing gradient problem -- enabled 100+ layer networks
Vanishing gradients: gradients shrink exponentially backward through many layers -- early layers barely update. Caused by sigmoid/tanh and many layers. Fix: ReLU, batch normalization, residual connections (ResNet skip connections -- gradient highway bypasses layers). Exploding gradients: weights blow up. Fix: gradient clipping (cap magnitude), careful initialization.
Vanishing
Sigmoid + many layers = early layers get nearly zero gradient
Exploding
Gradients grow exponentially -- weights blow up, training diverges
Residual connections
Skip connections -- gradient highway from output to early layers
Gradient clipping
Cap gradient magnitude -- essential for RNNs and LSTMs
Attention
SPOTLIGHT on the important words -- attention decides what to illuminate at each step
QUERY TIMES KEY = SCORE -- WEIGHTED SUM OF VALUES = CONTEXT
Multi-head attention runs h parallel spotlights capturing different relationship types
For each output position: Query (what am I looking for?), Key (what do I contain?), Value (what do I provide?). Score = Q dot K divided by sqrt(d_k), then softmax for weights, then weighted sum of Values. Self-attention: tokens attend to each other. Causal (decoder): only attends LEFT -- future tokens masked to enable autoregressive generation.
Query
What am I looking for at this position?
Key
What information do I contain?
Value
What information do I provide to the output?
Causal masking
Decoder looks LEFT only -- enables autoregressive text generation
Normalization Layers
BATCH normalizes ACROSS samples -- LAYER normalizes WITHIN a sample
BATCH NORM FOR CNNs -- LAYER NORM FOR TRANSFORMERS AND RNNs
Different axis of normalization -- choose based on your architecture type
Batch Normalization: normalize across batch dimension for each feature -- great for CNNs, needs large batch, fails with small batches or variable-length sequences. Layer Normalization: normalize across feature dimension within each sample -- batch-size independent, works with variable lengths, standard for Transformers and RNNs. Both add learnable scale and shift parameters.
Batch Norm
Across batch -- great for CNNs, needs large consistent batch
Layer Norm
Within each sample -- standard for Transformers and RNNs
RMSNorm
Simpler LayerNorm -- used in Llama and modern LLMs
Both add
Learnable scale (gamma) and shift (beta) parameters
Optimizers
SGD then Momentum then RMSProp then Adam -- each fixed a problem with the previous
ADAM = MOMENTUM PLUS ADAPTIVE LEARNING RATE = THE MODERN DEFAULT
AdamW adds proper weight decay -- the standard for fine-tuning large language models
SGD: simple, often oscillates. Momentum: adds inertia, accelerates in consistent directions. RMSProp: adaptive per-parameter learning rate. Adam: combines momentum plus RMSProp -- most popular, works with defaults (lr=0.001, beta1=0.9, beta2=0.999). AdamW: proper weight decay fix -- better generalization, standard for fine-tuning transformers.
SGD
Simple but oscillates and gets stuck in saddle points
Momentum
Adds inertia -- faster convergence, less oscillation
Adam
Momentum + RMSProp -- works well with default settings
AdamW
Adam + proper weight decay -- standard for transformer fine-tuning
🧠 Vivid Story
A neuron FIRES when enough friends nudge it — just like a real brain cell
THRESHOLD · WEIGHTS · ACTIVATION — the three-part neuron
How an artificial neuron works
Each artificial neuron receives inputs (signals from other neurons), multiplies each by a weight (importance), sums them up, and fires if the total exceeds a threshold — controlled by an activation function. Like a real brain cell: weak signals from many friends can add up and trigger a response. The weights are what the network learns — adjusting them is how training happens.
🎯 Exam Favorite
RELU = MAX(0, x) — below zero it's dead, above zero it's alive
THE BOUNCER FUNCTION — NOTHING NEGATIVE GETS IN
ReLU activation function — the most common in deep learning
ReLU (Rectified Linear Unit) is the most widely used activation function: output = max(0, x). If input is negative, output is zero (neuron silent). If positive, output equals input (neuron passes it through). Simple, fast, and avoids the vanishing gradient problem that plagued older functions like sigmoid. Think of ReLU as a bouncer — nothing negative gets past the door.
🔑 Key Distinction
CNN SEES SPACE — RNN REMEMBERS TIME — Transformer ATTENDS TO EVERYTHING
THREE ARCHITECTURES, THREE SUPERPOWERS
CNN vs RNN vs Transformer — one line each
CNN (Convolutional Neural Network): designed for spatial data — images, detecting features regardless of position. RNN (Recurrent Neural Network): designed for sequential data — processes time-ordered inputs like text or audio, with memory of past steps. Transformer: attends to all positions simultaneously using attention, no sequential processing — this is what powers GPT, BERT, and all modern LLMs. Each architecture has a superpower matched to a data type.
💡 Concept Anchor
DROPOUT = Randomly FIRING employees so the team can't rely on any one person
REGULARIZATION BY RANDOM REMOVAL
Dropout — the regularization trick that prevents overfitting
During training, dropout randomly turns off a percentage of neurons (typically 20–50%) on each pass. This forces the network to learn redundant representations — it can't rely on any single neuron. Result: a more robust, generalizable network that doesn't overfit. At test time, all neurons are active. Think of it as randomly benching players in practice so the whole team builds skills, not just the stars.
📅 Quick Reference
VANISHING GRADIENT = Whisper down the lane — signal fades before reaching early layers
WHY DEEP NETWORKS WERE HARD TO TRAIN
The vanishing gradient problem — why it matters
In backpropagation, error signals flow backward through layers. Each layer multiplies the gradient by a small number (like 0.1). After 10 layers: 0.1^10 = 0.000000001. By the time the signal reaches early layers it's essentially zero — those layers stop learning. This is the vanishing gradient problem that crippled deep networks before ReLU and residual connections solved it. Modern architectures are specifically designed to keep gradients alive.
How neural network training actually works — the complete cycle
Every training step has three phases: Forward pass — feed input through all layers, compute the prediction, calculate the loss (how wrong were we?). Backward pass (backpropagation) — compute how much each weight contributed to the error, flowing gradients back through layers. Weight update — adjust each weight slightly in the direction that reduces error, scaled by the learning rate. Repeat millions of times.
Forward
Input → layers → prediction → loss calculation
Backward
Loss → gradients → flow back through every layer
Update
weights = weights - learning_rate × gradient
🐍 Code
import torch, torch.nn as nn loss = criterion(model(X_batch), y_batch) # forward loss.backward() # backward optimizer.step() # update weights optimizer.zero_grad() # reset gradients
🎯 Exam Favorite
SIGMOID squashes to 0–1 · TANH squashes to -1 to 1 · RELU passes positives, kills negatives
THREE ACTIVATION FUNCTIONS — THREE JOBS
Activation functions compared — know when to use each
Sigmoid: output 0–1, used for binary classification output layer, suffers vanishing gradient in deep nets. Tanh: output -1 to 1, zero-centered (better than sigmoid for hidden layers), still suffers vanishing gradient. ReLU: max(0,x), fastest to compute, avoids vanishing gradient in most cases, standard choice for hidden layers in deep networks. Softmax: converts logits to probabilities summing to 1 — used in multi-class output layers.
Sigmoid
Binary output, probability interpretation — avoid in hidden layers
Tanh
Better than sigmoid in hidden layers, still vanishes in very deep nets
ReLU
Default for hidden layers — fast, effective, avoids vanishing gradient
Softmax
Multi-class output — probabilities that sum to 1.0
WEIGHT INITIALIZATION matters — start wrong and the network never recovers
XAVIER FOR TANH · HE FOR RELU — MATCH INIT TO ACTIVATION
Why weight initialization is a critical hyperparameter
Initializing all weights to zero: every neuron computes the same gradient — symmetry never breaks, nothing learns. Random weights too large: activations explode. Too small: vanishing gradient. Xavier initialization (Glorot): scales weights by input/output size — designed for sigmoid/tanh. He initialization: scales larger — designed for ReLU. PyTorch applies He init by default for linear and conv layers. Match the initializer to the activation function.
All zeros
Catastrophic — all neurons identical, no learning possible
Xavier/Glorot
For sigmoid or tanh — balances variance across layers
He init
For ReLU — accounts for the fact that half the neurons are zeroed out
🐍 Code
import torch.nn as nn layer = nn.Linear(256, 128) nn.init.xavier_uniform_(layer.weight) # for tanh/sigmoid nn.init.kaiming_uniform_(layer.weight) # for ReLU (He init)
💡 Concept Anchor
EPOCHS vs BATCH SIZE vs LEARNING RATE — the three dials every student must know cold
THREE HYPERPARAMETERS · THREE DIFFERENT JOBS
The most tested neural network hyperparameters
Epochs: how many complete passes through the entire training set. More epochs = more learning, but risk overfitting. Batch size: how many samples to process before updating weights. Small batch (8–32): noisier updates, better generalization. Large batch (256–1024): faster, smoother, may overfit. Learning rate: how big each weight update step is. The single most important hyperparameter. Too high: diverges. Too low: never converges. Use a learning rate finder or start at 1e-3 with Adam.
Epochs
Full passes through training data — more = more learning, risk overfit
Batch size
Samples per weight update — small=noisy but generalizes, large=smooth but may overfit
Learning rate
Step size per update — the most important hyperparameter, start at 1e-3
🐍 Code
model = MyNet() optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) for epoch in range(50): # epochs for X_batch, y_batch in DataLoader(dataset, batch_size=32): # batch size # train step here
0
Correct
0
Missed
0
Remaining
What does this mean / stand for?
0
Correct
0
Wrong
0
Remaining
🔗 Related Sub-Subjects
📊 Machine Learning
The foundational ML concepts that neural networks build upon — supervised, unsupervised, gradient descent.
A: Backpropagation computes the gradient of the loss with respect to every weight in the network, using the chain rule of calculus. It flows the error signal backward from output to input layer, calculating how much each weight contributed to the mistake. These gradients are then used by an optimizer (like SGD or Adam) to update the weights. It runs after every forward pass during training.
Q: What is the vanishing gradient problem and how is it solved?
A: In deep networks, gradients are multiplied by small numbers as they flow backward through many layers. After 10+ layers, gradients shrink toward zero — early layers stop learning. Solutions: ReLU activation (does not saturate for positive values), residual connections (skip connections that allow gradients to flow directly), batch normalization (stabilizes activations), and careful weight initialization.
Q: What is the difference between an epoch and an iteration?
A: An epoch is one complete pass through the entire training dataset. An iteration is one weight update — processing one mini-batch. If you have 1000 training examples and a batch size of 100, one epoch = 10 iterations. You typically train for multiple epochs until the validation loss stops improving.
Q: What does the softmax function do and when is it used?
A: Softmax converts a vector of raw scores (logits) into a probability distribution — all outputs are positive and sum to 1.0. Used in the output layer of multi-class classification networks. Each output represents the model's confidence that the input belongs to that class.
Q: What is regularization and name two techniques used in neural networks?
A: Regularization reduces overfitting by penalizing model complexity. In neural networks: Dropout — randomly disables neurons during training, forcing redundant representations. L2 weight decay — adds the sum of squared weights to the loss, penalizing large weights. Both are applied during training only; at inference time all neurons are active and no penalty is added.