Practical methodology: metrics, baselines and hyperparameters
Practical guidance on choosing metrics, setting baselines, and selecting hyperparameters for building and evaluating deep learning models, with clear definitions, formulas, examples and exam guidance.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
When you train a deep learning model you must measure whether it actually solved the problem (metrics), compare it to simple or known solutions (baselines), and choose the algorithm settings that control learning (hyperparameters). These three topics prevent wasted compute, avoid misleading conclusions, and give repeatable, defendable results for engineering and exams.
Key ideas
Classification basics (binary): given true labels y ∈ {0,1} and predictions ŷ ∈ {0,1} (after a threshold), define the four counts: True Positive (TP), False Positive (FP), True Negative (TN), False Negative (FN). These four build most classification metrics.
- To draw the diagram for exams: draw a 2×2 table. Top row label Predictions: Positive, Negative. Left column label Actual: Positive, Negative. Fill cells with TP (actual positive predicted positive), FN (actual positive predicted negative), FP (actual negative predicted positive), TN (actual negative predicted negative). Label sums: Pos = TP+FN, Neg = FP+TN, PredPos = TP+FP, PredNeg = FN+TN.
Accuracy: fraction of correct predictions. Use only when classes are balanced or equal cost of errors. Balanced accuracy = (TPR + TNR)/2 is preferred under class imbalance.
Precision: proportion of predicted positives that are correct. Important when false positives are costly.
Recall (Sensitivity, True Positive Rate): proportion of actual positives found. Important when false negatives are costly.
Specificity (True Negative Rate): proportion of actual negatives correctly identified.
F1 score: the harmonic mean of precision and recall. Use when you want a single number balancing precision and recall and classes are imbalanced. For multi-class or multi-label tasks, report macro-F1 (unweighted mean of per-class F1), micro-F1 (compute global TP/FP/FN then F1), or weighted-F1 (per-class F1 weighted by support).
ROC curve and AUC: plot True Positive Rate (TPR) vs False Positive Rate (FPR) as you vary the decision threshold on a probabilistic classifier; AUC (area under curve) measures ranking performance and equals the probability a random positive is ranked above a random negative (assumes continuous scoring, no ties).
Precision–Recall (PR) curve: for imbalanced data PR curves can be more informative than ROC. Use average precision (AP) to summarise. AP is the weighted mean of precisions at each threshold and approximates area under the PR curve; a random classifier's expected AP equals the positive class prevalence.
Log loss / cross-entropy: a proper scoring rule for probabilistic classifiers that penalises confident wrong predictions. It is differentiable and used during training. For regression tasks, common evaluation metrics include MAE, MSE/RMSE, and R^2 (coefficient of determination).
Calibration: a model is well-calibrated if its predicted probability p means roughly p fraction of those examples are positive. Calibration matters when probabilities are used for decisions. On validation data, choose decision thresholds to match costs or constraints (e.g., maximize F1, maximize Youden's J = TPR − FPR, or minimize expected cost from a cost matrix); use calibrated probabilities when making cost-sensitive decisions.
Baselines: minimal reference methods to check that your model does better than trivial solutions. Typical baselines:
- Random baseline: predict randomly (with or without preserved class proportions).
- Majority class: always predict the most frequent class.
- Simple heuristic: domain rule (e.g., threshold on one feature).
- Classical ML baseline: logistic regression, linear SVM, decision tree — fast, interpretable baselines.
Always report that your deep model improves over at least one reasonable baseline.
Hyperparameters: parameters set outside gradient-based optimisation. Common ones: learning rate, batch size, number of epochs, weight decay (L2 regularisation), dropout rate, momentum, optimizer choice, architecture choices (layers, width), and data augmentation settings. Hyperparameters control convergence speed, generalisation and compute cost. Also include learning rate schedules (e.g., step, cosine) and early stopping/patience.
- Principle: change one hyperparameter at a time (or use controlled grid/random search with validation) and keep a reproducible log (seed, code, data split, hardware).
Hyperparameter search methods:
- Grid search: try all combinations in a discrete grid — expensive but exhaustive for small grids.
- Random search: sample configurations uniformly from ranges — often finds better configs with fewer runs if some hyperparameters matter more than others.
- Bayesian optimisation: model-based search to propose promising hyperparameters (complex but sample-efficient).
- Successive halving / Hyperband / Population-based: allocate resources adaptively, prune bad runs early.
Validation protocol: split data into training/validation/test. Use validation for hyperparameter tuning and model selection; test only once for final performance. For small datasets, use k-fold cross-validation (stratified if classification) and report mean ± standard deviation across folds; keep a final held-out test set if possible.
Statistical significance: when improvements are small, run multiple random seeds and report mean ± standard deviation; use paired tests if needed. Examples: paired bootstrap or permutation tests for metrics, McNemar's test for accuracy on the same test set, and DeLong's test for ROC-AUC; report confidence intervals.
Assumptions to state in exam answers: binary vs multi-class, thresholding of probabilistic outputs, availability of calibrated scores, and independence between train/validation/test splits.
Formulas
accuracy = (TP + TN) / (TP + TN + FP + FN)
- TP, TN, FP, FN are counts (dimensionless). Applies to classification with discrete predictions.
precision = TP / (TP + FP)
- Fraction (dimensionless). Undefined if TP+FP = 0 (report as 0 or not-applicable).
recall = TP / (TP + FN)
- Fraction (dimensionless). Undefined if TP+FN = 0.
specificity = TN / (TN + FP)
- Fraction (dimensionless). Undefined if TN+FP = 0.
F1 = 2 * (precision * recall) / (precision + recall)
- Harmonic mean; dimensionless. Undefined if precision+recall = 0.
Fβ = (1 + β^2) * (precision * recall) / (β^2 * precision + recall)
- Generalised F-score weighting recall by β. Require β > 0; β > 1 emphasizes recall, β < 1 emphasizes precision.
log_loss = - (1/N) * Σ [ y_i * log(p_i) + (1 - y_i) * log(1 - p_i) ] for i=1..N
- y_i ∈ {0,1}, p_i predicted probability for class 1. Units: nats per example if natural log, or bits per example if log base 2 (information units). In practice clamp p_i to [ε, 1−ε] to avoid log(0).
TPR (recall) = TP / (TP + FN) ; FPR = FP / (FP + TN)
- Used to plot ROC curve.
SGD update: w ← w - η * ∇_w ℓ(w; x_batch)
- η is learning rate (dimensionless scalar), ∇_w ℓ gradient. Applies to SGD-based optimisers.
SGD with momentum: v ← μ v + η ∇_w ℓ ; w ← w - v
- μ is momentum coefficient (0 ≤ μ < 1). Sign convention may vary by implementation.
Note: most metric formulas are dimensionless. Learning rate and weight decay are hyperparameters without SI units; they are scalar multipliers.
Worked examples
Example 1 — Numerical confusion-matrix metrics (binary): Given: TP = 70, FP = 10, FN = 20, TN = 100. Compute accuracy, precision, recall, specificity and F1. Steps:
- Total = TP+FP+FN+TN = 70+10+20+100 = 200.
accuracy = (TP + TN)/Total = (70 + 100)/200 = 170/200 = 0.85→ 0.85 (85%).precision = TP/(TP+FP) = 70/(70+10) = 70/80 = 0.875→ 0.875 (87.5%).recall = TP/(TP+FN) = 70/(70+20) = 70/90 ≈ 0.777777...→ 0.7778 (77.78%).specificity = TN/(TN+FP) = 100/(100+10) = 100/110 ≈ 0.90909→ 0.9091 (90.91%).F1 = 2 * precision * recall / (precision + recall) = 2 * 0.875 * 0.777777... / (0.875 + 0.777777...) ≈ 2 * 0.6805555 / 1.6527777 ≈ 1.3611111 / 1.6527777 ≈ 0.823529→ 0.8235 (82.35%).
Example 2 — Python program: compute metrics from counts (runs exactly as written). Copy this into a .py file and run with Python 3.
# metrics_from_counts.py
TP = 70
FP = 10
FN = 20
TN = 100
total = TP + FP + FN + TN
accuracy = (TP + TN) / total
precision = TP / (TP + FP) if (TP + FP) > 0 else 0.0
recall = TP / (TP + FN) if (TP + FN) > 0 else 0.0
specificity = TN / (TN + FP) if (TN + FP) > 0 else 0.0
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0
print(f"accuracy: {accuracy:.4f}")
print(f"precision: {precision:.4f}")
print(f"recall: {recall:.4f}")
print(f"specificity: {specificity:.4f}")
print(f"f1: {f1:.4f}")
Sample output (exact):
accuracy: 0.8500 precision: 0.8750 recall: 0.7778 specificity: 0.9091 f1: 0.8235
Example 3 — Python program: simple hyperparameter sweep for a threshold-based baseline. This is deterministic and illustrates hyperparameter evaluation.
# threshold_baseline.py
# Data: two features per example, label 1 when sum(features) >= 1.5
X = [[1.0, 1.0], [0.9, 1.2], [1.0, 0.5], [0.4, 0.4], [0.0, 1.0], [0.6, 1.6]]
y = [1, 1, 1, 0, 0, 1]
thresholds = [0.5, 1.5, 2.0, 2.5]
for t in thresholds:
preds = [1 if (x[0] + x[1]) >= t else 0 for x in X]
correct = sum(1 for p,gt in zip(preds, y) if p == gt)
acc = correct / len(y)
print(f"threshold={t:.1f}, preds={preds}, accuracy={acc:.4f}")
Sample exact output:
threshold=0.5, preds=[1, 1, 1, 1, 1, 1], accuracy=0.6667 threshold=1.5, preds=[1, 1, 1, 0, 0, 1], accuracy=1.0000 threshold=2.0, preds=[1, 1, 0, 0, 0, 1], accuracy=0.8333 threshold=2.5, preds=[0, 0, 0, 0, 0, 0], accuracy=0.3333
Interpretation: threshold 1.5 perfectly matches the labeling rule here; 2.0 is stricter but still good; 0.5 is too lenient; and 2.5 is too strict.
Common mistakes
- Not specifying whether metrics use thresholded predictions or probabilities; forgetting to report threshold used.
- Comparing on test set while tuning hyperparameters (data leakage).
- Forgetting to run multiple random seeds or folds when variance is large and reporting a single-run number.
- Not reporting baseline results (e.g., majority class accuracy) then claiming improvement without context.
- Confusing precision vs recall in word problems; mixing up denominator terms in TP/FP/FN/TN.
- Reporting AUC value without stating whether higher is better or what the baseline random AUC (0.5) means.
- Not stating units or undefined cases (e.g., precision undefined when no predicted positives).
For your exam
Typical question forms:
- Definitions: define precision, recall, F1, AUC, baseline, hyperparameter. Full marks: exact formula, short explanation of when to use, mention edge cases.
- Short notes: compare ROC-AUC and PR-AUC. Full marks: explain axes, sensitivity to class imbalance, when one is preferred, include sketch of curves (label axes and show a random baseline diagonal for ROC and horizontal baseline for PR reflecting prevalence).
- Derivations: show algebra to derive F1 from precision and recall or show how AUC equals probability that a random positive scores above a random negative (show counting/probability argument). Full marks: clear assumptions (continuous scores, handle ties), step-by-step proof.
- Numericals: compute metrics from confusion matrix. Full marks: show all intermediate sums, carry units (dimensionless), and final values with correct rounding.
- Programs: small script to compute metrics or run a simple baseline. Full marks: working code, sample output, and explanation of reproducibility (seed, deterministic data).
- Diagrams: draw a confusion matrix, ROC curve, PR curve. Full marks: labelled axes, example operating points, and explanation.
Quick check
- If TP=30, FP=10, FN=20, TN=40, what is precision?
- Why is PR-AUC often preferred over ROC-AUC for very imbalanced problems?
- Give two reasonable baselines for an image classifier.
Answers: 1) precision = 30/(30+10) = 0.75. 2) PR-AUC focuses on positive class precision and recall and does not hide poor positive-class performance when negatives dominate the data (ROC can look optimistic under heavy imbalance). 3) majority-class baseline and a simple classical ML model such as logistic regression or a small decision tree.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?