ML study guide visual recall sheet

Machine Learning visual recall sheet

Recall board 1 · Weeks 1–4

Reason first. Measure honestly.

Frame the answer, seal evaluation, then reason from geometry and counts. Every change below has a visible consequence.

DefineName the job. MechanismShow flow or math. PerturbMove one condition. ConcludeChoose + trade-off.
Notation + reasoning

Translate symbols into a story

y^=fθ(x) θ*=argminθL(θ)
x
one input or feature vector
fθ
model governed by parameters
y^
model prediction
θ*
parameter choice with the smallest loss
argminθ
choose the parameter value that minimizes the following quantity
  • Parameter is learned; hyperparameter is chosen on validation evidence.
  • Representation is what numbers the learner sees; inductive bias is the solution shape it prefers.

Paradigms: supervised = labels · unsupervised = structure · semi-supervised = few labels + many unlabeled · reinforcement = reward. Bayes error is the irreducible floor.

Perturb: change representation → distances, splits, margins, and learned features can all change.
Evaluation + leakage

Train learns. Validation chooses. Test stays sealed.

Trainfit weights
Train onlyfit scaler
Validatechoose settings
Freezeall choices
Test oncefinal estimate
Deploywatch shift
Actual ↓Pred +Pred − PositiveTP 8FN 2 NegativeFP 2TN 88
Accuracy96%
Precision80%
Recall80%
F180%
P=TPTP+FPR=TPTP+FN F1=2PRP+R specificity=TNTN+FP FPR=1specificity
TP / TN
correct positive / negative counts
FP / FN
incorrect positive / negative counts
P/R
precision / recall
F1
harmonic mean of precision and recall
specificity
fraction of negatives correctly rejected
FPR
false-positive rate

CV: rotate k validation folds; LOOCV uses k=n. Fit scaler, preprocessing, and feature selection inside each training fold. ROC plots TPR vs FPR; PR plots precision vs recall.

Leakage: selecting depth, threshold, epoch, preprocessing, or features after looking at test results turns that “test” into validation. Obtain a new untouched test set.
Features + trees

Pick the split that removes weighted impurity

Decision tree split A parent node splits by outlook into a pure yes leaf and a mixed child. Outlook? overcast → Yes other → split
H(S)=c=1Cpclog2pc IG=H(parent)v|Sv||S|H(Sv)
S
examples at the current node
pc
fraction belonging to class
C
number of classes
Sv
child subset for branch
|S|
number of examples in that set
IG
information gained by the split
Micro-exampleParent: four positive / four negative, so H=1. After a split, weighted H0.451, so IG0.549.

Features: preprocess → extract → select. Filter scores before a model; wrapper searches with CV. Fit both within folds; univariate filters miss XOR interactions.

Continuous candidates are adjacent-value midpoints. Weight every child; prune/stop depth for variance. Many-valued features inflate IG → use gain ratio.
KNN

Distance → nearest neighbors → vote

K nearest-neighbor vote A query point is surrounded by its three nearest points, two green and one red. nearest distances 0.7 G · 1.0 R · 1.4 G k=3 → Green, 2–1
dp(x,z)=(j=1d|xjzj|p)1p x~j=xjμj,trainσj,train
p
norm order: Manhattan at p=1, Euclidean at p=2
d
number of input features
z
comparison point whose distance is measured
x~j
standardized value of one feature
μj,train/σj,train
training mean / standard deviation for that feature
  • Small k: flexible, high variance. Large k: smoother, more bias.
  • Scale first when units differ; choose k and metric with validation/CV.
  • Weight by 1dp; kd-trees help mainly in low dimensions; condensation stores fewer prototypes.
Perturb: scaling can reorder neighbors and flip the vote. If d=0, use exact matches instead of 1d.
SVM

The closest points set the widest margin

Support vector machine margin Two classes lie on either side of a decision boundary and two dashed margins; ringed points are support vectors. supportvectors
y^=sign(wTx+b) margin width=2w minw,b,ξ12w2+Ci=1nξi subject toyi(wTxi+b)1ξi ξi0
w
boundary orientation and margin scale
b
boundary offset
C
penalty for margin violations
ξi
slack of one training case
sign(·)
turns the score into the negative or positive class
xi/yi
training input / signed class target
  • Move a non-support point: boundary normally unchanged.
  • Move a support vector: optimum can move.
  • Lower C: tolerate slack, usually wider margin. Higher C: punish violations.
  • Polynomial/RBF kernels bend the boundary; large RBF γ is local/spiky. One-vs-rest trains one classifier per class; one-vs-one trains one per class pair.
Diagnosis + metrics

Read the symptom before prescribing

Train high · val highunderfit → capacity/features
Train low · val highoverfit → regularize/data
Both good · deploy badshift or leakage
  • Lower threshold → more predicted positives: recall tends up, precision may fall.
  • Rare positives → inspect precision-vs-recall; its baseline is prevalence. ROC (TPR-vs-FPR) can look optimistic.
  • Macro weights classes equally; weighted follows support; micro pools decisions.
Constraint first: “catch ≥95%” means tune validation threshold for recall, then compare precision/workload among qualifying choices.

Test set: one final estimate after every decision is frozen. A zero metric denominator is undefined, not confidently zero. Error near the Bayes floor needs better information, not just more capacity.

Recall board 2 · Weeks 5–8

Trace signal forward. Trace blame backward.

Keep a shape ledger and a gradient ledger. Deep learning questions become short when every arrow names what it carries.

ShapeWrite dimensions. ForwardAffine then activate. LossCompare with target. BackwardLocal derivatives.
Neural forward + backprop

One graph, two directions

Neural forward and backward computation graph Values flow from input through affine, ReLU, output, sigmoid and loss; gradients flow backward. x Wx+b ReLU vh+b σ L forward: values → ← backward: incoming gradient × local derivative
zh=Whx+bh;h=ReLU(zh) zo=vh+bo;y^=σ(zo) LBCE=[ylny^+(1y)ln(1y^)] Lzo=y^y σ=σ(1σ);tanh=1tanh2 ReLU=1 if z>0, else 0
zh/zo
hidden / output pre-activation values
h
hidden activation passed to the output
Wh/v
hidden / output trainable weights
bh/bo
hidden / output biases
σ/LBCE
sigmoid function / binary cross-entropy loss
Lzo
loss sensitivity entering the output unit
NumbersUsing x=[1,2],Wh=[.5,.25] and bh=0,v=.8,bo=.3 gives h=1,zo=.5,y^=.622. For y=1, the output gradient is .378.
Sigmoid/tanh can saturate; ReLU can die (leaky ReLU keeps a small negative slope). Identical zero-initialized hidden units stay symmetric. Backprop follows each dependency backward.
Optimization + regularization

Optimization fits; regularization generalizes

vt=βvt1+gt;θt+1=θtηvt L2=L+λ2iwi2;L1=L+λ1i|wi| elastic net=L+λ1i|wi|+λ2iwi2
gt
current loss gradient
vt
momentum accumulator
β
how much previous momentum is retained
η
learning rate or update step size
λ1/λ2
sparsity / shrinkage strengths
  • Batch=all; stochastic=1; mini-batch=middle. Adam rescales coordinates with gradient moments.
  • On a quadratic, 0<η<2λmax; tiny crawls, near-limit oscillates, larger diverges. Warm up, then decay.
  • L1 zeros; L2 shrinks; elastic net combines. Momentum smooths alternating gradients.
  • Augment only label-preserving transforms. Dropout off at inference; BatchNorm uses running, not batch, statistics.
Train loss falls while validation rises → restore best validation checkpoint; do not inspect test to choose the epoch.
CNN

Local window, shared weights, shape ledger

Convolutional filter sliding over an input A three by three kernel reads a patch in a five by five input and writes one cell in a feature map. × kernel Σ Yᵣ꜀
D=1:Nout=N+2PKS+1 parameters=(KhKwCin+1)Cout
D
dilation; the displayed size rule assumes one
N/Nout
input / output side length
K/S/P
kernel width / stride / zero padding
Kh/Kw
kernel height / width
Cin/Cout
input / output channel counts
+1
one learned bias per output filter
Example32×32×3,K=3,S=1,P=1,16 filters gives 32×32×16 and (3·3·3+1)16=448 parameters.
Conv32×32×16
Pool 2×216×16×16
Flatten4096
Dense m(4096+1)m
“Same” at S=1 keeps size with P=K12; “valid” means P=0. Keep the floor. Pooling has zero learned parameters.
RNN + LSTM

A recurrent path can fade; a gated highway can carry

LSTM cell state highway Old cell state passes through a forget gate and combines additively with gated candidate content before an output gate reveals hidden state. × f + i × g o × tanh cₜ₋₁cₜhₜ
ht=tanh(Wxxt+Whht1+b) ct=ftct1+itgt ht=ottanh(ct)
xt
input vector at the current sequence step
ht
hidden state exposed to later computation
ct
LSTM memory or cell state
Wx/Wh
input / recurrent weight matrices
ft/it/gt/ot
forget / input / candidate / output gate vectors
element-by-element multiplication
Forget fkeep old memory near 1
Input iwrite candidate near 1
Output oreveal state near 1
Numberscprev=.8,f=.75,i=.4,g=.5 gives c=.6+.2=.8. With o=.9, h.598.

GRU merges forget/input into an update gate and has no separate cell state. Bidirectional needs the whole sequence—invalid for strict streaming. Seq2seq attention selects encoder states instead of one fixed summary.

γ<1 across many steps → vanishing: gates/attention. γ>1 → exploding: clip gradients.
Transformers

Match with Q·K; move content with V

Causal attention order of operations Scaled query-key scores receive a causal mask before row-wise softmax, then multiply values. QKᵀ / √dₖ + mask row softmax × V forbidden logits → −∞ causal mask each allowed rowrenormalizes to 1
A=softmaxrow(QKTdk+M);O=AV Mi,j=0 if allowed; −∞ if forbidden
Q/K/V
query / key / value matrices
dk
key-vector width used to scale scores
Mi,j
mask entry for query row and key column
A/O
attention-weight matrix / resulting output
softmaxrow
normalize each score row to sum to one
Inputtoken embedding + position
Multi-headparallel learned Q/K/V projections
Blockattention → Add&Norm → FFN → Add&Norm
  • Encoder-only: bidirectional (BERT: masked language modeling + original next-sentence objective).
  • Decoder-only: causal generation; teacher forcing during training, autoregressive feedback at inference.
  • Encoder–decoder: decoder Q cross-attends to encoder K/V; useful for sequence-to-sequence tasks.
Mask before softmax. Zeroing probabilities afterward breaks row sums and does not renormalize the allowed evidence.
Architecture routing

Choose the information path

CNNlocal, repeated spatial patterns; shared filters.
RNNonline sequence, compressed past; long gradient path.
LSTMsequential, gated long memory; still cannot parallelize time.
Transformerdirect token links, parallel training; standard full attention costs O(n2).
Exam verb “compare” → path length, parallelism, memory mechanism, and cost. Do not answer with popularity.

Softmax + categorical CE gives zL=py. Adding the same constant to all logits leaves probabilities unchanged.

Recall board 3 · Weeks 9–10

Route by constraint. Verify by evidence.

Choose whether to change instructions, context, a small update, all weights, or the representation—and isolate the exact failed stage.

ConstraintFreshness, labels, GPU. InterventionWhat actually changes? TestIsolate one stage. EvidenceAgreement is not truth.
Method selector

Change the smallest thing that solves the constraint

Promptknown task; format or instruction steering
RAGfresh/private facts; citations; no retraining
PEFTstable labeled task; limited memory
Full tunelarge stable corpus; compute; deep change

Prompt: zero-shot → few-shot examples → explicit reasoning steps when justified. Transfer: frozen feature extractor → partial → full tune. PEFT: soft prompt, per-layer prefix, adapters, or mergeable LoRA. Pruning removes low-value weights/units after validation.

Weekly policy updates + strict citations → RAG. A response-format failure with known knowledge → prompt/template first.
Exam routing

Turn the question cue into a complete answer

“Calculate”write formula → substitute → units/shape → sanity check
“Explain why”mechanism → consequence → one perturbation
“Compare”same axes for both methods → scenario choice
“Diagnose”observed symptom → isolating test → stage-specific fix
Fast routeMetric cost → threshold. Weighted counts → tree. Geometry → KNN/SVM. Shape → CNN. Long dependency → LSTM/attention. Fresh evidence → RAG. Limited adaptation budget → LoRA. Domain shift → DANN.
Never list every method. State the constraint, select one intervention, name what changes, and pay one honest trade-off.
RAG: six separate failure stages

Wrong answer is a symptom, not a diagnosis

1 Corpusevidence exists?
2 Chunkfact stays whole?
3 Retrieveenters top-k?
4 Reranksurvives cutoff?
5 Generateuses evidence?
6 Citepoints correctly?
1 · CoverageAbsent from owned corpus → acquire/curate source.
2 · ChunkingFact split across chunks → semantic boundary/overlap.
3 · RetrievalWhole gold chunk misses top-k → query/embedding/recall.
4 · RankingGold is rank 18 and cut → rerank shortlist.
5 · GroundingGold is in prompt; answer contradicts → generation constraint.
6 · AttributionAnswer supported; citation wrong → claim-to-passage check.
Offline → onlineCurate/chunk/embed/index once → embed query → fast bi-encoder retrieve → precise cross-encoder rerank shortlist → prompt generator → verify claim-to-passage.
Gold-passage test: inject the correct passage manually. Answer fixed → stages 1–4. Still wrong → stage 5. Correct claim, wrong pointer → stage 6.
LoRA

Freeze W0; learn a low-rank update

LoRA matrix factorization A frozen full matrix receives the product of a tall B matrix and a wide A matrix, whose inner dimension is rank r. W₀frozen + B × A = W dₒᵤₜ × r r × dᵢₙ
ΔW=BA trainable=r(din+dout) square d×d special case=2dr
W0
frozen pretrained weight matrix
ΔW
learned low-rank update
A/B
small trainable factor matrices
r
chosen rank or bottleneck width
din/dout
input / output dimensions of the base matrix
Exampledin=dout=4096,r=8 gives 65,536 trainable vs 16,777,216 full =0.391%.
Initialize B=0 so ΔW=0 at start; merge W0+BA for zero added inference latency. Use r(din+dout); 2dr is only square.
Verification

Ask: what independent evidence enters?

Rulesdeterministic, precise, narrow
Retrievalexternal trusted evidence; retrieval is gate
LLM judgeflexible rubric; shared-bias risk
Reflectioncheap revision; cannot create missing evidence
Consistencyaggregate paths; more compute
Multi-agentseparate roles; correlated failures remain
Agreement is not truth. Internal checks become factual verification only when claims are compared with trusted evidence.
DANN

Keep label signal; erase domain signal

Domain-adversarial neural network Source and target inputs share a feature extractor. A label branch minimizes source-label loss, while a gradient reversal branch trains a domain classifier but reverses its gradient into the extractor. source + targetexamples featureextractor label predictormin source label loss GRL −λ domainclassifier
θfLd λθfLd
θf
feature-extractor parameters
Ld
domain-classification loss
λ
strength of the reversed domain signal
θf
gradient with respect to extractor parameters
replace the incoming gradient during backpropagation

Example: labeled hospital A, unlabeled hospital B. Preserve disease evidence while suppressing hospital/scanner cues.

Assumption: source and target share a useful labeling structure. Domain confusion alone must not erase task signal.
Final recall check

Ten checks before you turn the page

  1. Did I name the decision and trade-off?
  2. Is every learned transform train-only?
  3. Did I weight tree children?
  4. Did I scale distance features?
  5. Which points actually set the margin?
  6. Did I preserve tensor dimensions?
  7. Where can the gradient vanish?
  8. Is the causal mask before softmax?
  9. Did I count LoRA as r(din+dout)?
  10. Which exact RAG stage failed?
Reconstruct: close the page and redraw the sealed evaluation flow, forward/backward arrows, masked attention, and six RAG stages. Reopen and mark only omissions.

Bounded to Weeks 1–10; this recall layer does not replace the guide’s worked labs, drills, flashcards, or mock exam. Complete guide →

Back to first board ↑