TensorFlow Deep Learning Cheat Sheet: Layers, Activations, Losses, Optimizers, Regularization and Architectures on One Page
A dense, correct, one-page reference for deep learning and neural networks. It covers layers, activation functions, loss functions, optimizers (SGD, Adam, AdamW and more), learning rate schedules, weight initialization, normalization, regularization, CNN, RNN, Transformer and generative architectures, shape and parameter-count formulas, memory estimates, metrics a side-by-side TensorFlow/Keras and PyTorch API table, and a training debugging checklist. It is for students preparing for exams or machine learning interviews, engineers who need a quick lookup while training models, and anyone who wants the formulas and defaults in one place. Formulas are framework-independent, and section 18 maps every concept to its TensorFlow/Keras and PyTorch name, including defaults that differ between the two.
Last reviewed: December 2026
Formulas are written in plain text so they render everywhere. Notation: x input, y target, ŷ prediction, W weights, b bias, g gradient, η learning rate, σ sigmoid, ⊙ element-wise product, N batch size, K number of classes, d model width.
Table of Contents
- 1. Core ideas in 12 lines
- 2. Layers
- 3. Activation functions
- 4. Loss functions
- 5. Optimizers
- 6. Learning rate schedules
- 7. Weight initialization
- 8. Normalization layers
- 9. Regularization
- 10. Architectures
- 11. Transformer details
- 12. Shapes, parameters and FLOPs
- 13. Memory estimates
- 14. Metrics
- 15. Training recipe and sensible defaults
- 16. Debugging checklist
- 17. Numerical stability
- 18. TensorFlow, Keras and PyTorch equivalents
- 19. Glossary
- 20. Key papers
- Classic models at a glance
- What to tune first
- Interview quick answers
- FAQ
- Where to go next
- Contributing
- More free resources
1. Core ideas in 12 lines
- A neural network is a composition of differentiable functions:
ŷ = f_L(... f_2(f_1(x))), each usuallyactivation(W·x + b). - Training minimizes a loss
L(ŷ, y)averaged over data, by adjusting parametersθ. - Backpropagation applies the chain rule from the loss back to every parameter to get
∂L/∂θ. - Gradient descent updates
θ ← θ − η · ∂L/∂θ, using mini-batches (stochastic gradient descent). - One epoch = one pass over the training set. One step (iteration) = one mini-batch update.
- Nonlinear activations are what let stacked layers represent nonlinear functions; without them the whole network collapses to one linear map.
- Depth composes features; width adds capacity per layer. Residual connections make depth trainable.
- Generalization is performance on unseen data. Watch the gap between training and validation loss.
- Underfitting: high training loss. Fix with more capacity, longer training, better features, lower regularization.
- Overfitting: low training loss, high validation loss. Fix with more data, augmentation, regularization, early stopping.
- Inductive bias (convolution for images, attention for sequences) reduces how much data a model needs.
- Scale (data, parameters, compute) improves large models predictably, which is why modern foundation models are large.
2. Layers
| Layer | Operation | Input → output shape | Parameters | Typical use |
|---|---|---|---|---|
| Linear / Dense | y = xWᵀ + b |
(N, in) → (N, out) |
in·out + out |
MLPs, heads, projections |
| Conv2d | sliding dot product of K×K kernels |
(N, C_in, H, W) → (N, C_out, H', W') |
C_in·C_out·K_h·K_w + C_out |
images, spatial data |
| Depthwise conv | one kernel per channel (groups = C_in) |
channels unchanged | C·K_h·K_w + C |
efficient CNNs (MobileNet style) |
| Max / Avg pooling | max or mean over a window | spatial size shrinks | 0 | downsampling |
| Global average pool | mean over all spatial positions | (N, C, H, W) → (N, C) |
0 | CNN classifier heads |
| Embedding | table lookup of row i |
(N, T) ints → (N, T, d) |
V·d |
tokens, categorical features |
| RNN | h_t = tanh(W_x x_t + W_h h_{t-1} + b) |
(N, T, in) → (N, T, h) |
h·(in + h) + h (one bias) |
short sequences (legacy) |
| LSTM | gated recurrence with cell state | (N, T, in) → (N, T, h) |
4·(h·(in + h) + h) |
sequences, time series |
| GRU | 2 gates, no separate cell | (N, T, in) → (N, T, h) |
3·(h·(in + h) + h) |
lighter alternative to LSTM |
| Self-attention | softmax(QKᵀ/√d_k)V |
(N, T, d) → (N, T, d) |
4·d² + 4·d (Q, K, V, output with biases) |
Transformers |
| Dropout | zero activations with prob p, scale by 1/(1−p) |
unchanged | 0 | regularization |
| Normalization | see section 8 | unchanged | 2·C or 2·d typically |
stable training |
| Residual | y = x + F(x) |
unchanged | 0 extra | deep networks |
Notes: PyTorch’s nn.RNN, nn.LSTM and nn.GRU use two bias vectors per gate (b_ih and b_hh), so their parameter counts are 4·(h·(in + h) + 2h) for LSTM and similarly for the others.
LSTM equations
i_t = σ(W_i·[h_{t−1}, x_t] + b_i) input gate
f_t = σ(W_f·[h_{t−1}, x_t] + b_f) forget gate
o_t = σ(W_o·[h_{t−1}, x_t] + b_o) output gate
c̃_t = tanh(W_c·[h_{t−1}, x_t] + b_c) candidate
c_t = f_t ⊙ c_{t−1} + i_t ⊙ c̃_t cell state
h_t = o_t ⊙ tanh(c_t) hidden state
GRU equations
z_t = σ(W_z·[h_{t−1}, x_t]) update gate
r_t = σ(W_r·[h_{t−1}, x_t]) reset gate
h̃_t = tanh(W·[r_t ⊙ h_{t−1}, x_t])
h_t = (1 − z_t) ⊙ h_{t−1} + z_t ⊙ h̃_t
(Some libraries swap the roles of z_t and 1 − z_t; the model is equivalent.)
3. Activation functions
| Name | Formula | Derivative | Range | Notes |
|---|---|---|---|---|
| Sigmoid | σ(x) = 1 / (1 + e^(−x)) |
σ(x)·(1 − σ(x)) |
(0, 1) | binary outputs, gates; saturates, max gradient 0.25 |
| Tanh | (e^x − e^(−x)) / (e^x + e^(−x)) |
1 − tanh²(x) |
(−1, 1) | zero-centered; RNN cells; saturates |
| ReLU | max(0, x) |
1 if x > 0 else 0 |
[0, ∞) | default for CNNs and MLPs; can “die” |
| Leaky ReLU | x if x > 0 else α·x (α ≈ 0.01) |
1 or α |
(−∞, ∞) | avoids dead units |
| PReLU | Leaky ReLU with learned α |
1 or α |
(−∞, ∞) | small gains in CNNs |
| ELU | x if x > 0 else α·(e^x − 1) |
1 or α·e^x |
(−α, ∞) | smooth negative part |
| SELU | λ·ELU(x) with λ ≈ 1.0507, α ≈ 1.6733 |
λ or λ·α·e^x |
(−λα, ∞) | self-normalizing nets; needs LeCun normal init |
| Softplus | ln(1 + e^x) |
σ(x) |
(0, ∞) | smooth ReLU; positive outputs (variances) |
| GELU | x·Φ(x), Φ = standard normal CDF |
Φ(x) + x·φ(x) |
≈ (−0.17, ∞) | Transformers (BERT, GPT-2 style) |
| GELU (tanh approx.) | 0.5x·(1 + tanh(√(2/π)·(x + 0.044715x³))) |
faster approximation | ||
| SiLU / Swish | x·σ(x) |
σ(x)·(1 + x·(1 − σ(x))) |
≈ (−0.28, ∞) | modern CNNs and LLM MLPs |
| Mish | x·tanh(softplus(x)) |
≈ (−0.31, ∞) | some vision models | |
| Softmax | softmax(z)_k = e^(z_k) / Σ_j e^(z_j) |
s_k(δ_kj − s_j) |
(0, 1), sums to 1 | multi-class probabilities |
| GLU family | GLU(x) = (xW) ⊙ σ(xV); SwiGLU(x) = (Swish(xW) ⊙ xV)·W₂ |
gated MLPs in many LLMs |
Rules of thumb:
- Hidden layers: ReLU for CNNs and simple MLPs; GELU or SiLU/SwiGLU for Transformers.
- Output layer depends on the task, not taste: see the table below.
- Sigmoid and tanh in deep stacks cause vanishing gradients; use them for gates and outputs.
Output layer + loss pairings
| Task | Output layer | Loss | PyTorch (numerically stable) |
|---|---|---|---|
| Regression | none (identity) | MSE, MAE or Huber | nn.MSELoss, nn.L1Loss, nn.HuberLoss |
| Binary classification | 1 logit (sigmoid at inference) | binary cross-entropy | nn.BCEWithLogitsLoss |
| Multi-class, single label | K logits (softmax at inference) |
cross-entropy | nn.CrossEntropyLoss (takes raw logits) |
| Multi-label | K logits, independent sigmoids |
BCE per label | nn.BCEWithLogitsLoss |
| Positive values (counts, rates) | softplus or exp | Poisson NLL, MSE on log | nn.PoissonNLLLoss |
| Language modeling | V logits per position |
cross-entropy on next token | nn.CrossEntropyLoss on flattened logits |
4. Loss functions
Regression
MSE L = (1/N) Σ (ŷ − y)²
MAE L = (1/N) Σ |ŷ − y|
Huber a = ŷ − y
L = 0.5·a² if |a| ≤ δ
δ·(|a| − 0.5·δ) otherwise
MSE punishes large errors heavily (sensitive to outliers); MAE is robust but has a constant gradient; Huber is quadratic near zero and linear far away.
Classification
Binary cross-entropy L = −[ y·log(p) + (1 − y)·log(1 − p) ], p = σ(z)
Cross-entropy L = −Σ_k y_k·log(p_k), p = softmax(z)
with one-hot y: L = −log(p_true) = −z_true + log Σ_j e^(z_j)
Gradient w.r.t. logits ∂L/∂z = p − y (for both softmax+CE and sigmoid+BCE)
Label smoothing y_smooth = (1 − ε)·one_hot + ε/K (ε ≈ 0.1)
Focal loss L = −α_t·(1 − p_t)^γ·log(p_t) (γ ≈ 2; down-weights easy examples)
Hinge (SVM) L = max(0, 1 − y·f(x)), y ∈ {−1, +1}
Distributions and representations
KL divergence KL(P‖Q) = Σ P(x)·log(P(x) / Q(x)) (not symmetric, ≥ 0)
Cross-entropy H(P, Q) = H(P) + KL(P‖Q)
Triplet L = max(0, d(a, p) − d(a, n) + margin)
Contrastive (InfoNCE) L = −log( exp(sim(q, k⁺)/τ) / Σ_i exp(sim(q, k_i)/τ) )
VAE (ELBO, minimized) L = reconstruction_loss + KL( q(z|x) ‖ N(0, I) )
Common gotchas:
- Never apply softmax before
nn.CrossEntropyLoss, or sigmoid beforenn.BCEWithLogitsLoss. They expect raw logits. nn.CrossEntropyLosstargets are class indices of shape(N,)(or class probabilities of shape(N, K)).nn.KLDivLossexpects log-probabilities as input; target is probabilities unlesslog_target=True.- For imbalanced classes, use class weights, focal loss or resampling, and judge with precision/recall rather than accuracy.
5. Optimizers
Update rules for one parameter tensor θ with gradient g at step t.
| Optimizer | Update | Typical hyperparameters |
|---|---|---|
| SGD | θ ← θ − η·g |
η 0.01 to 0.1 for CNNs |
| SGD + momentum | v ← μ·v + g; θ ← θ − η·v |
μ = 0.9 |
| Nesterov momentum | v ← μ·v + g; θ ← θ − η·(g + μ·v) (PyTorch form) |
μ = 0.9 |
| AdaGrad | G ← G + g²; θ ← θ − η·g / (√G + ε) |
good for sparse features; LR decays forever |
| RMSProp | v ← ρ·v + (1 − ρ)·g²; θ ← θ − η·g / (√v + ε) |
ρ 0.9 to 0.99 (PyTorch default 0.99) |
| Adam | see below | η = 1e-3, β₁ = 0.9, β₂ = 0.999, ε = 1e-8 |
| AdamW | Adam + decoupled weight decay | η 1e-4 to 3e-4 for Transformers, weight decay 0.01 to 0.1 |
| Lion | u = sign(β₁·m + (1 − β₁)·g); θ ← θ − η·(u + λ·θ); m ← β₂·m + (1 − β₂)·g |
β₁ = 0.9, β₂ = 0.99; use a 3 to 10x smaller LR than AdamW |
Adam / AdamW in full
m ← β₁·m + (1 − β₁)·g first moment (mean of gradients)
v ← β₂·v + (1 − β₂)·g² second moment (uncentered variance)
m̂ = m / (1 − β₁^t) bias correction (m, v start at 0)
v̂ = v / (1 − β₂^t)
Adam: θ ← θ − η·m̂ / (√v̂ + ε) (L2 via g ← g + λθ is coupled to the adaptive scaling)
AdamW: θ ← θ − η·( m̂ / (√v̂ + ε) + λ·θ ) (decoupled weight decay)
Practical notes:
- AdamW is the default for Transformers and most modern training. SGD + momentum is still competitive for CNNs on images, often with better generalization at the cost of more tuning.
- Exclude biases and normalization parameters from weight decay in Transformers (common practice).
εmatters in low precision; values like1e-6to1e-8are common.- Optimizer state costs memory: Adam keeps two extra tensors per parameter.
- Gradient clipping by global norm (
max_norm = 1.0is common for Transformers) prevents occasional huge updates. - Linear scaling rule: when multiplying the batch size by
k, multiply the SGD learning rate by aboutkand use warmup (Goyal et al., 2017). For Adam, scaling by√kis a common starting point. Verify empirically.
6. Learning rate schedules
Step decay η_t = η₀ · γ^floor(t / step) (e.g. γ = 0.1 every 30 epochs)
Exponential η_t = η₀ · γ^t
Linear warmup η_t = η_max · t / T_warmup for t < T_warmup
Cosine decay η_t = η_min + 0.5·(η_max − η_min)·(1 + cos(π·t / T))
Inverse sqrt η_t = η_max · √(T_warmup / t) for t ≥ T_warmup (original Transformer style)
One-cycle warm up to η_max, then anneal far below η₀ over the run
Warmup-stable-decay warmup, long constant phase, short final decay (popular for LLM pretraining)
- Warmup (a few hundred to a few thousand steps) stabilizes early training, especially with Adam, large batches and Transformers.
- Cosine with warmup is a strong default.
- ReduceLROnPlateau (divide LR when validation stops improving) is simple and works well for small projects.
- Cosine with restarts (SGDR) periodically resets the LR (Loshchilov & Hutter, 2016).
- Find a starting LR with an LR range test: increase LR exponentially over a few hundred steps and pick a value a bit below where the loss starts to explode.
7. Weight initialization
Goal: keep activation and gradient variance roughly constant across layers.
| Scheme | Distribution | Use with |
|---|---|---|
| Xavier / Glorot uniform | U(−a, a), a = √(6 / (fan_in + fan_out)) |
tanh, sigmoid, linear |
| Xavier / Glorot normal | N(0, 2 / (fan_in + fan_out)) |
tanh, sigmoid |
| He / Kaiming normal | N(0, 2 / fan_in) |
ReLU family |
| He / Kaiming uniform | U(−a, a), a = √(6 / fan_in) |
ReLU family |
| LeCun normal | N(0, 1 / fan_in) |
SELU |
| Orthogonal | random orthogonal matrix (times a gain) | RNNs, very deep nets |
| Small normal | N(0, 0.02²) |
common in GPT-style Transformers |
| Zero | all zeros | biases; last layer of residual branches (helps very deep nets) |
fan_in = inputs per unit (for conv: C_in·K_h·K_w), fan_out = outputs per unit (C_out·K_h·K_w). Never initialize all weights to the same value: units would stay identical (symmetry).
PyTorch’s default for nn.Linear and nn.Conv* is a Kaiming-uniform variant with a = √5, which gives U(−1/√fan_in, 1/√fan_in) for weights.
8. Normalization layers
BatchNorm μ, σ² over (N, H, W) per channel
y = γ·(x − μ)/√(σ² + ε) + β
uses running mean/var at inference
LayerNorm μ, σ² over the feature dimension(s) of each example
y = γ·(x − μ)/√(σ² + ε) + β
RMSNorm y = γ·x / √(mean(x²) + ε) no mean subtraction, no β
GroupNorm μ, σ² over groups of channels per example (G groups)
InstanceNorm μ, σ² over (H, W) per channel per example (style transfer)
| Layer | Depends on batch? | Typical use |
|---|---|---|
| BatchNorm | yes | CNNs with reasonable batch sizes (≥ 16 or so) |
| LayerNorm | no | Transformers, RNNs |
| RMSNorm | no | many modern LLMs (cheaper than LayerNorm) |
| GroupNorm | no | CNNs with small batches (detection, segmentation) |
| InstanceNorm | no | style transfer, some generative models |
Gotchas: call model.eval() at inference so BatchNorm uses running statistics (and dropout is disabled). Pre-norm Transformers (normalize before attention and MLP) train more stably than post-norm and are the common choice.
9. Regularization
| Technique | What it does | Typical setting |
|---|---|---|
| Weight decay | shrinks weights toward zero each step | AdamW 0.01 to 0.1; SGD 1e-4 to 5e-4 |
| L1 penalty | λ·Σ|w|, encourages sparsity |
rare in deep nets |
| Dropout | randomly zeroes activations during training | 0.1 (Transformers), 0.2 to 0.5 (MLPs) |
| Data augmentation | random transforms that preserve the label | flips, crops, color jitter, RandAugment; SpecAugment for audio |
| Early stopping | stop when validation metric stops improving | patience 5 to 20 epochs; keep the best checkpoint |
| Label smoothing | soften one-hot targets | ε = 0.1 |
| Mixup | train on convex combinations of example pairs and labels | α 0.2 to 0.4 |
| CutMix | paste patches between images, mix labels by area | vision |
| Stochastic depth | randomly skip residual blocks | drop rate grows with depth, up to about 0.1 to 0.5 |
| Gradient clipping | caps gradient norm | max_norm 1.0 |
| Smaller model | fewer parameters | when data is small |
| More data | the most reliable fix for overfitting | always worth checking first |
10. Architectures
| Family | Core idea | Typical uses | Representative models |
|---|---|---|---|
| MLP | stacked dense layers | tabular data, heads, small problems | |
| CNN | shared local filters, translation equivariance | images, audio spectrograms | LeNet, AlexNet, VGG, ResNet, EfficientNet, ConvNeXt |
| ResNet | residual connections x + F(x) make very deep nets trainable |
vision backbones | ResNet-50 |
| U-Net | encoder-decoder with skip connections at each scale | segmentation, diffusion denoisers | |
| RNN / LSTM / GRU | recurrent hidden state over time | time series, small sequence tasks | |
| Transformer | self-attention over all positions | language, vision, audio, multimodal | BERT (encoder), GPT (decoder), T5 (encoder-decoder) |
| Vision Transformer | image split into patches treated as tokens | image classification and backbones | ViT |
| Autoencoder | compress to a bottleneck and reconstruct | denoising, anomaly detection, representation | |
| VAE | probabilistic latent space with KL regularization | generation, latent spaces for diffusion | |
| GAN | generator vs discriminator game | image synthesis, super-resolution | StyleGAN |
| Diffusion | learn to reverse a gradual noising process | image, video, audio generation | DDPM, latent diffusion |
| Graph neural network | message passing between connected nodes | molecules, social and knowledge graphs | GCN, GAT |
| Mixture of Experts | router sends each token to a few expert MLPs | large language models at lower compute per token | Switch Transformer |
| State space models | linear-time sequence mixing with selective state | long sequences | Mamba |
Encoder vs decoder Transformers
| Type | Attention mask | Pretraining objective | Good for |
|---|---|---|---|
| Encoder-only | bidirectional | masked language modeling | classification, retrieval embeddings, NER |
| Decoder-only | causal (no peeking ahead) | next-token prediction | text generation, chat, code; most LLMs |
| Encoder-decoder | bidirectional encoder, causal decoder with cross-attention | span corruption, seq2seq | translation, summarization |
11. Transformer details
Attention(Q, K, V) = softmax( Q·Kᵀ / √d_k + M ) · V
Q = X·W_Q, K = X·W_K, V = X·W_V
M = mask: 0 where allowed, −∞ where blocked (causal mask blocks future positions)
Multi-head: split d into h heads of size d_k = d/h, attend in parallel, concat, project with W_O.
Block (pre-norm):
x = x + Attention(Norm(x))
x = x + MLP(Norm(x)) MLP: d → 4d → d (GELU), or SwiGLU with hidden ≈ (8/3)·d
- Why
√d_k: dot products of random vectors grow with dimension; scaling keeps softmax out of its saturated region. - Positional information: sinusoidal (original), learned absolute embeddings (BERT, GPT-2), rotary embeddings, RoPE (common in modern LLMs), ALiBi.
- Attention cost:
O(T²·d)time andO(T²)memory per head for sequence lengthT(FlashAttention keeps memory linear in practice by never materializing the full matrix). - KV cache: at generation time, keys and values of previous tokens are stored so each new token costs
O(T)attention instead of recomputing everything. - Multi-query and grouped-query attention (MQA, GQA) share key/value heads across query heads to shrink the KV cache.
- Tokenization: subword schemes (BPE, WordPiece, Unigram) map text to integer ids; vocabulary size
Vis often tens of thousands to a few hundred thousand. - Decoding: greedy, beam search, temperature sampling
softmax(z / T), top-k, top-p (nucleus).
12. Shapes, parameters and FLOPs
Convolution output size (per spatial dimension)
out = floor( (in + 2·padding − dilation·(kernel − 1) − 1) / stride ) + 1
Examples: in=224, k=3, p=1, s=1 → 224 in=224, k=7, p=3, s=2 → 112 in=32, k=5, p=0, s=1 → 28
"same" padding for odd k, s=1, dilation 1: p = (k − 1) / 2
Transposed convolution output size
out = (in − 1)·stride − 2·padding + dilation·(kernel − 1) + output_padding + 1
Pooling uses the same formula as convolution (dilation 1). A 2×2 pool with stride 2 halves height and width.
Receptive field of stacked layers: r_L = r_{L−1} + (k_L − 1)·Π_{i<L} s_i, starting from r_0 = 1. Two stacked 3×3 convs (stride 1) see 5×5; three see 7×7.
Parameter counts
Linear(in, out) in·out + out
Conv2d(C_in, C_out, k×k) C_in·C_out·k² + C_out
Embedding(V, d) V·d
LayerNorm(d) / BatchNorm(C) 2·d / 2·C (plus non-trained running stats for BatchNorm)
Multi-head attention(d) 4·d² + 4·d
Transformer block (d, MLP 4d) ≈ 12·d² (4d² attention + 8d² MLP), ignoring biases and norms
Decoder LLM ≈ 12·L·d² + V·d (L layers; add V·d again if output head is untied)
Example: L = 12, d = 768, V = 50,257 gives 12·12·768² ≈ 85M plus 50,257·768 ≈ 39M embedding, about 124M total (the size of the smallest GPT-2).
Compute
Forward pass FLOPs ≈ 2 · N_params per token (one multiply + one add per weight)
Training FLOPs ≈ 6 · N_params · N_tokens (forward 2N + backward 4N)
Linear layer FLOPs ≈ 2 · in · out per example
Conv2d FLOPs ≈ 2 · C_in · k² · C_out · H_out · W_out per example
Attention scores FLOPs ≈ 4 · T² · d per sequence per layer (QKᵀ and attention·V)
Compute-optimal scaling (Hoffmann et al., 2022): for a fixed training compute budget, parameters and training tokens should grow roughly together, at about 20 tokens per parameter. Many current models train on far more tokens than that because smaller models are cheaper to serve.
13. Memory estimates
| Item | Bytes per parameter |
|---|---|
| fp32 weights | 4 |
| fp16 / bf16 weights | 2 |
| int8 weights | 1 |
| 4-bit weights | about 0.5 (plus small overhead for scales) |
| Mixed-precision training with Adam | about 16: fp16/bf16 weights 2 + gradients 2 + fp32 master weights 4 + Adam m and v 8 |
Inference weights N_params × bytes_per_param 7B params in bf16 ≈ 14 GB
Full fine-tune with Adam ≈ 16 × N_params + activations 7B ≈ 112 GB before activations
KV cache per sequence 2 × n_layers × n_kv_heads × head_dim × seq_len × bytes
Ways to fit more: gradient accumulation (bigger effective batch, same memory), activation checkpointing (recompute activations in backward), mixed precision, sharding optimizer state and parameters across GPUs (ZeRO / FSDP), parameter-efficient fine-tuning such as LoRA, and quantization.
14. Metrics
Classification (TP, FP, TN, FN from the confusion matrix)
Accuracy (TP + TN) / (TP + TN + FP + FN)
Precision TP / (TP + FP) of predicted positives, how many are right
Recall (TPR) TP / (TP + FN) of actual positives, how many were found
Specificity TN / (TN + FP)
F1 2·P·R / (P + R) harmonic mean of precision and recall
F_β (1 + β²)·P·R / (β²·P + R) β > 1 weights recall more
ROC AUC area under TPR vs FPR curve; probability a random positive outranks a random negative
PR AUC area under precision-recall curve; more informative for rare positives
Log loss cross-entropy of predicted probabilities
Macro avg average the metric over classes equally; micro avg: pool counts over classes
Regression: MAE, RMSE √(mean((ŷ − y)²)), R² 1 − SS_res / SS_tot, MAPE (avoid when y can be near zero).
Other common metrics
| Area | Metric |
|---|---|
| Language modeling | perplexity = exp(mean cross-entropy per token) |
| Object detection | IoU = area(A ∩ B) / area(A ∪ B); mAP at IoU thresholds |
| Segmentation | mean IoU, Dice = 2|A ∩ B| / (|A| + |B|) |
| Machine translation | BLEU, chrF, COMET |
| Summarization | ROUGE |
| Ranking and retrieval | recall@k, MRR, nDCG |
| Generative images | FID |
15. Training recipe and sensible defaults
Recipe
- Get a baseline running end to end on a small subset. Check the input pipeline by visualizing a batch with labels.
- Overfit a single batch to near-zero loss. If you cannot, there is a bug.
- Train on the full data with defaults. Plot training and validation curves.
- Tune the learning rate first, then batch size, then regularization.
- Add complexity (bigger model, augmentation, schedules) one change at a time, keeping the best checkpoint.
- Evaluate on a held-out test set once, at the end.
Defaults that usually work
| Setting | CNN on images | Transformer fine-tuning | Small MLP / tabular |
|---|---|---|---|
| Optimizer | SGD momentum 0.9 or AdamW | AdamW | Adam or AdamW |
| Learning rate | 0.1 (SGD, batch 256) or 1e-3 (AdamW) | 1e-5 to 5e-5 (full fine-tune); about 1e-4 to 2e-4 for LoRA | 1e-3 |
| Schedule | cosine or step, with warmup for large batches | linear or cosine decay with warmup (about 5 to 10%) | ReduceLROnPlateau |
| Weight decay | 1e-4 to 5e-4 (SGD), 0.05 (AdamW) | 0.01 | 0 to 1e-4 |
| Batch size | as large as fits; 32 to 256 | 16 to 64 | 32 to 512 |
| Normalization | BatchNorm | (model’s own) LayerNorm / RMSNorm | BatchNorm or none |
| Precision | bf16 or fp16 mixed | bf16 mixed | fp32 is fine |
For tabular data, gradient-boosted trees (XGBoost, LightGBM, CatBoost) are often a stronger baseline than a neural network.
16. Debugging checklist
| Symptom | Likely causes | What to try |
|---|---|---|
| Loss is NaN or inf | LR too high, log(0), division by zero, fp16 overflow | lower LR, use loss functions that take logits, gradient clipping, bf16, check inputs for NaN |
| Loss does not decrease at all | LR far too low or high, frozen params, wrong labels, bug in data | overfit one batch, check requires_grad, inspect a batch, LR range test |
Loss stuck at ln(K) (classification) |
model predicts uniform probabilities | check labels match inputs, check the final layer, LR |
| Training loss down, validation loss up | overfitting | more data or augmentation, weight decay, dropout, early stopping, smaller model |
| Both losses high | underfitting | bigger model, train longer, higher LR, less regularization |
| Validation better than training | dropout or augmentation active only in training, or leakage | usually fine; check for duplicates between splits |
| Great validation, bad production | distribution shift, leakage, preprocessing mismatch | compare feature distributions; use identical preprocessing code |
| Accuracy high but model is useless | class imbalance | check per-class precision and recall, confusion matrix |
| Loss spikes | bad batch, LR too high, missing warmup | gradient clipping, warmup, lower LR, inspect the batch |
| Slow training | data loading bottleneck, small batches, CPU-GPU copies | profile; more data loader workers; pin memory; mixed precision |
| Different results at inference | forgot model.eval(), different preprocessing |
eval mode, torch.no_grad(), shared preprocessing |
| Gradients vanish (early layers barely change) | saturating activations, deep plain nets | ReLU/GELU, residual connections, normalization, proper init |
| Gradients explode | deep RNNs, high LR | gradient clipping, lower LR, normalization |
17. Numerical stability
log-sum-exp log Σ e^(z_i) = m + log Σ e^(z_i − m), m = max(z)
stable softmax softmax(z) = softmax(z − max(z))
log-softmax z − logsumexp(z) (use instead of log(softmax(z)))
stable sigmoid σ(x) = 1/(1 + e^(−x)) for x ≥ 0; e^x/(1 + e^x) for x < 0
softplus log(1 + e^x) = max(x, 0) + log(1 + e^(−|x|))
- Use losses that take logits (
BCEWithLogitsLoss,CrossEntropyLoss), which apply these tricks internally. - Add a small
εinsidelog,sqrtand denominators you write yourself. - fp16 has a small range (max about 65,504) and needs loss scaling; bf16 has the same exponent range as fp32 and usually needs none.
18. TensorFlow, Keras and PyTorch equivalents
Keras 3 runs on TensorFlow, JAX or PyTorch backends; the keras.* names below are the Keras 3 API (in TensorFlow 2 they are also available as tf.keras.*).
Layers
| Concept | Keras | PyTorch |
|---|---|---|
| Dense / linear | keras.layers.Dense(units) |
nn.Linear(in_features, out_features) |
| 2D convolution | keras.layers.Conv2D(filters, kernel_size, strides, padding="same") |
nn.Conv2d(in_ch, out_ch, kernel_size, stride, padding) |
| Pooling | MaxPooling2D, AveragePooling2D, GlobalAveragePooling2D |
nn.MaxPool2d, nn.AvgPool2d, nn.AdaptiveAvgPool2d(1) |
| Embedding | keras.layers.Embedding(input_dim, output_dim) |
nn.Embedding(num_embeddings, embedding_dim) |
| LSTM / GRU | keras.layers.LSTM(units, return_sequences=True) |
nn.LSTM(input_size, hidden_size, batch_first=True) |
| Multi-head attention | keras.layers.MultiHeadAttention(num_heads, key_dim) |
nn.MultiheadAttention(embed_dim, num_heads, batch_first=True) |
| Normalization | BatchNormalization, LayerNormalization, GroupNormalization |
nn.BatchNorm2d, nn.LayerNorm, nn.GroupNorm |
| Dropout | keras.layers.Dropout(rate) |
nn.Dropout(p) |
Losses, optimizers, schedules, training utilities
| Concept | Keras | PyTorch |
|---|---|---|
| Binary cross-entropy on logits | keras.losses.BinaryCrossentropy(from_logits=True) |
nn.BCEWithLogitsLoss() |
| Cross-entropy, integer labels, logits | keras.losses.SparseCategoricalCrossentropy(from_logits=True) |
nn.CrossEntropyLoss() |
| Cross-entropy, one-hot labels | keras.losses.CategoricalCrossentropy(from_logits=True) |
nn.CrossEntropyLoss() with probability targets |
| MSE / Huber / KL | MeanSquaredError, Huber(delta), KLDivergence |
nn.MSELoss, nn.HuberLoss(delta), nn.KLDivLoss |
| Optimizers | keras.optimizers.SGD(momentum=0.9, nesterov=True), Adam, AdamW, RMSprop, Adagrad, Lion |
torch.optim.SGD, Adam, AdamW, RMSprop, Adagrad (Lion via third-party packages) |
| Cosine schedule with warmup | keras.optimizers.schedules.CosineDecay(initial_learning_rate, decay_steps, warmup_target=..., warmup_steps=...) |
torch.optim.lr_scheduler.LinearLR + CosineAnnealingLR combined with SequentialLR |
| Early stopping, LR on plateau, checkpoints | keras.callbacks.EarlyStopping, ReduceLROnPlateau, ModelCheckpoint |
write it in the loop; torch.optim.lr_scheduler.ReduceLROnPlateau |
| Gradient clipping | optimizer argument global_clipnorm=1.0 |
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) |
| Training loop | model.compile(...) then model.fit(...) |
explicit loop: forward, loss, backward(), step(), zero_grad() |
| Mixed precision | keras.mixed_precision.set_global_policy("mixed_bfloat16") |
torch.autocast(device_type, dtype=torch.bfloat16) |
Defaults that differ (common source of “same model, different results”)
| Setting | Keras | PyTorch |
|---|---|---|
| Image tensor layout | channels last (N, H, W, C) |
channels first (N, C, H, W) |
| Dense / conv weight init | Glorot uniform | Kaiming uniform variant, U(−1/√fan_in, 1/√fan_in) |
| BatchNorm momentum | 0.99, meaning moving = 0.99·moving + 0.01·batch |
0.1, meaning running = 0.9·running + 0.1·batch (same behavior, opposite convention) |
| BatchNorm epsilon | 1e-3 |
1e-5 |
| Adam / AdamW epsilon | 1e-7 |
1e-8 |
| AdamW weight decay | 0.004 |
0.01 |
| RMSprop decay | rho = 0.9 |
alpha = 0.99 |
| Losses expect | probabilities by default (from_logits=False) |
logits for CrossEntropyLoss and BCEWithLogitsLoss |
| Train vs inference mode | training=True/False passed to layers; fit() and predict() handle it |
model.train() / model.eval() |
When porting a model between frameworks, match these explicitly instead of relying on defaults.
19. Glossary
| Term | Meaning |
|---|---|
| Logit | raw, unnormalized score before sigmoid or softmax |
| Epoch / step | full pass over the data / one parameter update |
| Batch size | examples per gradient step |
| Gradient accumulation | summing gradients over several mini-batches before one update |
| Backbone / head | feature-extracting body / task-specific final layers |
| Fine-tuning | continuing training of a pretrained model on new data |
| Transfer learning | reusing a model trained on one task for another |
| Freezing | keeping some parameters fixed during training |
| LoRA | fine-tuning small low-rank update matrices instead of all weights |
| Distillation | training a small student model to match a large teacher’s outputs |
| Quantization | storing weights or activations with fewer bits |
| Pruning | removing weights or structures with little effect on output |
| Embedding | learned dense vector representation of a discrete item |
| Latent space | the internal representation a model compresses data into |
| Inductive bias | assumptions built into an architecture |
| Teacher forcing | feeding ground-truth previous tokens during sequence training |
| Data leakage | information from the test set or the future influencing training |
| Ablation | removing one component to measure its contribution |
| Checkpoint | saved model and optimizer state |
| Mixed precision | computing in fp16/bf16 while keeping sensitive values in fp32 |
20. Key papers
Free books for going deeper: Deep Learning (Goodfellow, Bengio, Courville), Dive into Deep Learning, and Understanding Deep Learning (Prince).
Classic models at a glance
Landmark architectures and the one idea each is remembered for. Years are first publication.
| Year | Model | Domain | Key idea |
|---|---|---|---|
| 1998 | LeNet-5 | vision | Convolution + pooling + dense layers, trained end to end |
| 2012 | AlexNet | vision | Deep CNN on GPUs with ReLU and dropout; won ImageNet 2012 by a wide margin |
| 2014 | VGG | vision | Depth with stacks of small 3×3 convolutions |
| 2014 | GoogLeNet (Inception) | vision | Parallel convolution branches; 1×1 convs for cheap channel mixing |
| 2014 | GAN | generative | Generator and discriminator trained against each other |
| 2014 | Seq2seq with attention | language | Encoder-decoder RNNs; attention over source tokens |
| 2015 | ResNet | vision | Residual connections make 100+ layer networks trainable |
| 2015 | U-Net | segmentation | Encoder-decoder with skip connections at every scale |
| 2017 | Transformer | language | Self-attention only, no recurrence; parallel training |
| 2017 | MobileNet | vision | Depthwise separable convolutions for phones |
| 2018 | BERT | language | Bidirectional encoder pretrained with masked language modeling |
| 2018-2020 | GPT, GPT-2, GPT-3 | language | Decoder-only Transformers scaled up; few-shot prompting |
| 2019 | EfficientNet | vision | Compound scaling of depth, width and resolution |
| 2020 | ViT | vision | Images as sequences of patches fed to a Transformer |
| 2020 | DDPM | generative | Diffusion: learn to reverse gradual noising |
| 2021 | CLIP | multimodal | Contrastive image-text pretraining; zero-shot classification |
| 2022 | ConvNeXt | vision | CNNs modernized with Transformer-era design choices |
| 2023 | Mamba | sequence | Selective state space models with linear-time sequence mixing |
What to tune first
Not all hyperparameters matter equally. A rough priority order for a new problem:
| Priority | Hyperparameter | Typical search |
|---|---|---|
| 1 | Learning rate | log scale, for example 1e-5 to 1e-1; the single most important knob |
| 2 | Schedule and warmup | cosine vs constant, warmup 0 to 10% of steps |
| 3 | Batch size | as large as fits, then retune the learning rate |
| 4 | Model size (width, depth) | grow until validation stops improving |
| 5 | Weight decay | 0, 1e-4, 1e-2, 0.1 |
| 6 | Dropout and augmentation strength | only once the model overfits |
| 7 | Optimizer betas, epsilon | rarely worth tuning |
Search tips: random search beats grid search when only a few hyperparameters matter; tune on a smaller model or subset first; change one thing at a time when debugging; always compare against the same validation split and seed set.
Interview quick answers
| Question | Short answer |
|---|---|
| Why do we need nonlinear activations? | Without them, stacked linear layers collapse into one linear map |
| What causes vanishing gradients? | Repeated multiplication by small derivatives (saturating activations, deep chains); fixed by ReLU-family activations, residuals, normalization, good init |
| Why does BatchNorm help? | Stabilizes activation distributions, allows higher learning rates, adds mild regularization |
| Dropout at inference? | Disabled; inverted dropout scales activations during training so no rescaling is needed at test time |
| Why divide attention scores by √d_k? | Keeps dot products from growing with dimension and saturating softmax |
| L1 vs L2 regularization? | L1 pushes weights to exactly zero (sparsity); L2 shrinks all weights smoothly |
| Precision vs recall? | Precision: how many predicted positives are right. Recall: how many actual positives were found |
| Why is cross-entropy preferred over MSE for classification? | Larger, better-behaved gradients for confident wrong predictions; matches maximum likelihood |
| What is the receptive field? | The input region that affects one output unit; grows with depth, kernel size and stride |
| Encoder vs decoder Transformer? | Encoder sees the whole sequence (understanding); decoder is causal (generation) |
| How does Adam differ from SGD? | Per-parameter adaptive step sizes from running averages of gradients and squared gradients, with bias correction |
| What is overfitting and how do you detect it? | Training loss keeps falling while validation loss rises; watch both curves |
| Why use a learning rate warmup? | Early gradients and Adam’s variance estimates are unreliable; small steps first avoid divergence |
| What is transfer learning? | Starting from weights trained on a large dataset, then fine-tuning on the target task |
FAQ
What is the difference between machine learning and deep learning? Deep learning is the part of machine learning that uses neural networks with many layers, learning features directly from raw data (pixels, audio, text) instead of hand-engineered features.
Which activation function should I use? ReLU for CNNs and simple MLPs, GELU or SiLU (often inside SwiGLU) for Transformers. The output activation is decided by the task (see the pairing table in section 3).
Adam or SGD? AdamW is the safe default and the standard for Transformers. SGD with momentum still trains excellent CNNs and can generalize slightly better, but needs more learning-rate tuning.
How do I choose the learning rate? Start from the defaults in section 15, run a learning-rate range test, and use warmup plus cosine decay. If loss explodes, lower it; if it barely moves, raise it.
What batch size should I use? The largest that fits in memory is usually fine for throughput; adjust the learning rate when you change it a lot. Very small batches are noisy; BatchNorm needs batches of roughly 16 or more.
Why is my validation loss lower than my training loss? Dropout and augmentation are only active during training, and training loss is averaged over an epoch while the model was improving. It is usually harmless; check for data leakage if the gap is large.
How many layers and neurons do I need? Start from a known architecture for your data type, then scale width and depth until validation stops improving. Overfit a small batch first to prove the model can learn.
Do I need a GPU to learn deep learning? No. Small MLPs and CNNs on MNIST-sized data train on a CPU in minutes, and free notebook GPUs exist for bigger experiments.
BatchNorm or LayerNorm? BatchNorm for CNNs with reasonable batch sizes; LayerNorm (or RMSNorm) for Transformers, RNNs and small-batch settings.
What does “parameters” mean in a model like “7B”? The number of learned weights and biases: 7 billion. Memory needed is that number times bytes per parameter (section 13).
Where to go next
- Build intuition with the free books listed above: Dive into Deep Learning has runnable code for every chapter.
- Practice the formulas in code: the PyTorch snippets repository in this collection implements many of them in a few lines each.
- Read the original papers in section 20 for the techniques you use most.
- Official framework guides: PyTorch tutorials and Keras developer guides.
- For large models: the Hugging Face transformers cheat sheet and the GGUF quantization guide in this collection.
Contributing
PRs are welcome, especially corrections. Every formula and default here should be checkable: when you change one, link the paper or official documentation that supports it. Keep entries short; this is a cheat sheet, not a textbook.
If this cheat sheet helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.