Skip to main content
Quick Reference

DP Cheatsheet

Deep learning on one page — layers, losses, training, conv nets, and the traps around logits, eval mode, and leakage.

10 sections 10 tables 14 code snippets

Stack the layers

Hidden ReLU, linear head

Dense(128, activation="relu")
Dense(10)

Loss that expects logits

SparseCategoricalCrossentropy(from_logits=True)

What a deep net is

PieceMeaning
LayerA linear map, weights plus a bias, then a nonlinearity
No nonlinearityStacked linear maps collapse into one linear map
LogitsRaw scores. The last Dense(10) above has no activation
HeadOne logit for a binary label. One logit per class for several classes
ParametersA dense map from n to m stores n * m weights plus m biases
InitAll zeros keep every unit identical. Random init breaks that symmetry

This page is deep learning. A from-scratch single neuron and hosted GenAI APIs are left out.

Activations

The usual hidden unit

# ReLU(x) = max(0, x)

Which curve

FunctionUse
ReLUThe usual hidden unit. Negative inputs become 0
Dead ReLUA unit that stays negative gets a zero gradient and stops updating
SigmoidSquashes to the range 0 to 1. Fine as a binary head. In a deep stack the early gradient shrinks
TanhSquashes to the range -1 to 1 and is zero-centered. It also saturates
SoftmaxTurns logits into a distribution that sums to 1. Use it on the class axis
He and XavierHe init suits ReLU. Xavier suits tanh and sigmoid

Losses

Class axis only

# softmax over classes, never over the batch

Match the head

TaskPair
RegressionA linear head and squared error
BinaryOne logit and binary cross-entropy with from_logits=True
Integer classesSparseCategoricalCrossentropy and integer labels
One-hot classesCategoricalCrossentropy and a row of zeros and ones
Double squashA softmax head plus a loss that already applies softmax trains on the wrong numbers
AccuracyIgnores how far the probability is from the cutoff. The loss can fall while accuracy sits still

The training step

Watch a validation split

model.fit(X_train, y_train, validation_data=(X_val, y_val))

One update

StepWhat it does
ForwardThe layers turn a batch into logits
LossCompares those scores with the labels
BackwardThe chain rule sends a gradient to every weight
StepMoves each weight against its gradient
EpochOne pass over the training rows. A step is one mini-batch
ShuffleShuffle which rows a new epoch sees. Keep order when order is the signal

Optimizers

A common start

Adam(learning_rate=0.001)

The step size

NameDetail
Learning rateToo high and the loss climbs or becomes NaN. Too low and the weights barely move
SGDOne global step size. Momentum keeps a velocity from earlier steps
AdamA step size per weight, from how large the recent gradients were. 0.001 is a common start
AdamWWeight decay applied apart from that adaptive step. L2 inside Adam is a different update
ScheduleLower the rate as the loss settles. Large models often start with a warmup
Batch sizeA bigger batch is a steadier gradient and costs more memory. Retune the rate when the batch changes

Regularize

Drop half the units in training

Dropout(0.5)

Keep the val loss honest

ToolDetail
DropoutZeros random units while training. Scoring uses every unit
Weight decayPulls weights toward zero. It is a penalty, not a second dataset
AugmentNew training images from flips and crops that keep the label. Leave the test images alone
Early stopHalt when the validation loss stops improving. Stopping on the training loss does not
Batch normUses the batch mean while training, and a running average while scoring
Eval modeA handmade loop must turn training behavior off before it scores

Conv nets

32 filters, 3 by 3

Conv2D(32, kernel_size=3, activation="relu")

Layout

# Keras is channels last. PyTorch is channels first.

Local weights

FactDetail
Shared kernelThe same small filter slides across the image. The parameter count does not grow with the width
Channels32 filters means 32 detectors, each with its own kernel
PaddingStride 1 and same padding keep height and width. Valid padding shrinks the map
Max poolKeeps the strongest value in each window and downsamples
LayoutKeras is batch, height, width, channels. PyTorch is batch, channels, height, width
PretrainedThe released model expects its own input size and its own mean and std

Sequences

A residual step

out = x + block(x)

Keep the steps in order

# shuffle which sequences you draw, not the steps inside one

Time and attention

PieceDetail
RNNA hidden state carried from step to step. A long chain of small derivatives vanishes
LSTMGates that leave a path for the gradient. A very distant token is still hard
AttentionEach position can read the others in one step. Work grows with the square of the length
ScaleDivide the attention scores by the square root of the key size before softmax
PositionsWithout them the block sees a set of vectors. Add positions so order matters
Residualx + block(x) needs matching shapes, or a small projection makes them match

Sanity checks

Prove the net can learn

# a correct net can memorize a handful of rows

Read the curves

PatternMeaning
Loss will not fall on a few rowsThe bug is in the code or the shapes, not in a lack of data
Train down, validation upOverfitting. The net is memorizing
Both stay highUnderfitting, a tiny learning rate, or a broken input
NaN lossOften a learning rate that is too high, or a gradient that blew up. Clip the gradient norm
Accuracy stuck, loss fallingThe class does not change until the probability crosses the cutoff
Rare classAccuracy still looks high if the model always predicts the majority

Interview traps

Traps worth memorising

TrapWhat happensPrefer
Softmax, then a logits lossThe loss applies softmax again and the number is wrongA linear head and from_logits=True
All-zero weightsEvery unit in the layer stays a copy of the othersRandom init. He for ReLU
Sigmoid in every hidden layerThe early gradient shrinksReLU in the hidden layers
A huge learning rateThe loss climbs or becomes NaNA smaller rate, then a schedule
Score while dropout is onEach run drops different units, and batch norm uses that batchEval mode before you score
PyTorch, no zero_gradBackward adds to the gradient already storedZero the gradient each step, unless you mean to accumulate
Mean and std from every imageThe test set leaks into the normalizationStatistics from the training images only
100% training accuracyThe net can memorize and still fail on new rowsThe validation curve
Augment the test imagesThe score is not on the real inputsAugment the training images
Channels on the wrong axisThe shape may run, and the pixels are scrambledMatch channels-last or channels-first to the framework
Softmax over the batchThe classes in one row no longer form a distributionSoftmax over the class axis
Shuffle steps inside a sequenceThe sentence or the series is destroyedShuffle whole sequences, keep each one in order

Train statistics only

# mean and std from the training images only

Clear the old gradient

# PyTorch: zero the gradients before each backward

How to use this page: stack a nonlinearity between linear maps, train on logits, and score with dropout and batch norm turned off. Fit normalization on the training images only.