Tune it, measure it honestly, then decide where to draw the line

Module 4 of a visual study guide for the AWS Certified Machine Learning Engineer – Associate (MLA‑C02) exam: hyperparameter tuning, metrics for rare classes, choosing a decision threshold, comparing models, explaining and checking them for bias, evaluating generative AI, and registering the winner for approval.

Predicted fraudPredicted legit Actually fraudTPcaughtFNmissed: money lost Actually legitFPfalse alarm: angry customerTNleft alone
Exam versionThese notes follow MLA‑C02 (the English MLA‑C01 exam ended on September 28, 2026). This module covers Task 2.3 (analyze and evaluate ML and AI performance), hyperparameter optimization from Task 2.2, and model versioning from Task 3.3. Two tools the exam still names, SageMaker Debugger and SageMaker Clarify, are now closed to new customers; the sections below cover both the names and the current replacements.
Start here

What the exam expects you to do

This module covers hyperparameter tuning from task 2.2 and all of task 2.3 (analyze model performance). After it you should be able to do each of these without notes:

  1. Pick a tuning strategy, set ranges and scaling, and reuse earlier tuning with warm start.Tuning
  2. Work out precision, recall, F1 and the rest from a confusion matrix.Metrics
  3. Set a decision threshold from business costs or review capacity.Threshold
  4. Compare candidate models fairly against baselines.Comparing
  5. Read training curves: overfitting, underfitting, learning rate problems.Diagnostics
  6. Explain one prediction and the model as a whole.Explaining
  7. Measure fairness in a model’s predictions.Fairness
  8. Version, approve and roll back models with Model Registry.Registry
  9. Choose metrics for regression, generated text, foundation models and RAG; shadow vs A/B tests.Deep dives
How to use this pageRead a section, then run the flashcards. Take the practice test at the end; the results table links each weak topic back to its section. Repeat the flashcards a day later.
Cheatsheet

Everything to recall on one screen

Each line maps an exam phrase to the answer it usually points to.

If the question says… pick

“Tune hyperparameters, learn from earlier trials”AMT, Bayesian strategy
“Run as many trials in parallel as possible”Random search
“Deep learning; stop weak trials after a few epochs”Hyperband (set early stopping to OFF)
“Try every combination of a few categorical values”Grid search (categorical only)
“Continue a previous tuning job”Warm start, IDENTICAL_DATA_AND_ALGORITHM
“Re‑tune on new data, reuse what was learned”Warm start, TRANSFER_LEARNING
“Learning rate range spans 0.0001 to 0.1”Logarithmic scaling
“Stop poor training jobs early to save cost”Tuner early stopping = Auto
“Rare positive class; one summary number”PR‑AUC (not accuracy, not ROC‑AUC alone)
“Missing a positive is very costly”Prioritize recall; lower the threshold
“False alarms are very costly”Prioritize precision; raise the threshold
“Balance precision and recall in one number”F1
“Reviewers can handle only N alerts a day”Set the threshold by capacity (top N scores)
“Different costs for FP and FN”Choose the threshold that minimizes expected cost
“Predict a number; penalize big errors more”RMSE (MAE if outliers shouldn’t dominate)
“Multi‑class with rare classes that matter”Macro‑averaged F1
“Why did the model flag this one transaction?”SHAP local explanation
“Do two groups get flagged at different rates?”DPPL / DI (post‑training)
“Do two groups get different recall?”RD, recall difference
“Bias in labels before training”CI, DPL (pre‑training)
“Detect overfitting or vanishing gradients during training”Debugger rules (exam name); today TensorBoard / MLflow + CloudWatch
“Version models, require sign‑off before deploy”Model Registry, PendingManualApproval → Approved
“Deploy automatically when a model is approved”EventBridge rule on the approval change
“Document intended use, risks and metrics”SageMaker Model Cards
“New model sees real traffic, users see old one”Shadow test
“Score a translation or summary against a reference”BLEU (translation), ROUGE (summaries), BERTScore (meaning)
“Grade LLM answers at scale without people”LLM‑as‑a‑judge (Bedrock Evaluations)
“Check RAG answers stay true to retrieved text”Faithfulness, Bedrock Knowledge Base evaluation

Formulas

  • Precision TP / (TP + FP)
  • Recall (TPR) TP / (TP + FN)
  • F1 2PR / (P + R)
  • False‑positive rate FP / (FP + TN)
  • Specificity TN / (TN + FP)
  • Accuracy (TP + TN) / all
  • DPPL q̂a − q̂d; DI q̂d / q̂a (1 = parity)
  • Expected cost FN × cost_FN + FP × cost_FP

Tuning in one breath

  • Built‑in XGBoost tunes on validation:auc, f1, logloss and others, not aucpr
  • Its learning rate is eta
  • High parallelism makes Bayesian behave like random
  • Warm start: up to 5 parents, same objective metric
  • Up to 500 training jobs per tuning job, parents included

Governance in one breath

  • Registry statuses: PendingManualApproval, Approved, Rejected
  • Attach metrics, bias and explainability reports to the model version
  • Clarify and Debugger: closed to new customers. Bias metrics with pandas/scikit‑learn, explanations with the SHAP library
  • Profiler support ends June 30, 2027

MLA‑C02 tasks this module covers

2.3 Analyze and evaluate performancemain
2.2.3 Hyperparameter optimizationone skill
3.3.6 Model versions for auditone skill

Mostly Domain 2, ML Model and FM Development (24%).

1

The module on one page

A trained model is a candidate, not a product. This is the path from candidate to approved version.

Tune hyperparametersAMT: Bayesian, random, Hyperband, grid Evaluate on held‑out dataPR‑AUC, precision, recall, F1 Pick the decision thresholdcosts, capacity or a precision target Compare candidatesmetrics, spread, latency, cost Explain itfeature importance, SHAP Check fairnessDPPL, DI, recall gap Register a model versionmetrics + reports, PendingManualApproval Human approvalApproved triggers deployment
2

Automatic Model Tuning (AMT)

AMT launches many training jobs with different hyperparameters inside ranges you set, watches one objective metric, and reports the best job. Your choices: the strategy, the ranges, the objective, and the budget.

Only a few categorical values,and you want every combination? Yes Gridcategorical only No Iterative training that reportsa metric every epoch? Yes Hyperbanddrops weak trials No Need to run most trialsat the same time? Yes Randomfully parallel No Bayesian (default)learns from each finished trial Bayesian needs trials to finish before it can learn: keep parallelism low.

Ranges and scaling

Range typeExampleScaling
ContinuousParametereta 0.01–0.5Logarithmic when the range spans orders of magnitude
IntegerParametermax_depth 3–10Linear
CategoricalParameteroptimizer in {adam, sgd}n/a
Values close to 1momentum 0.9–0.999ReverseLogarithmic

Why grid search explodes

Values tried per hyperparameter, if each were a grid.

Built‑in XGBoost: what you can tune toward

Objective metricsMost influential hyperparameters
validation:auc, f1, accuracy, error, logloss, rmse, mae, map, ndcg and others. aucpr is not on the list.alpha, min_child_weight, subsample, eta, num_round
Tuning on a rare classWith the built‑in XGBoost, tune on validation:f1 or validation:auc, then compare finalists on PR‑AUC with your own evaluation step. To tune directly on PR‑AUC, use Script Mode, print the metric, and capture it with a metric_definitions regex.

Warm start

TypeData and algorithmUse it to
IDENTICAL_DATA_AND_ALGORITHMMust match the parentsContinue a search: more jobs, narrower ranges
TRANSFER_LEARNINGCan change (new data, new image version)Re‑tune on a fresh data snapshot

Limits: up to 5 parent jobs, all finished; the same objective metric; parameter types can’t change; parents’ jobs count toward the 500‑job cap.

3

Metrics built from four numbers

Every classification metric comes from the confusion matrix. Type any four counts to see how they move.

Confusion‑matrix calculator

MetricQuestion it answersWatch out
PrecisionOf the flags, how many were real?Can be high while missing most positives
RecallOf the real positives, how many did we flag?Flag everything and it reaches 100%
F1One number that needs bothWeights precision and recall equally; use F‑beta to favour one
ROC‑AUCHow well are positives ranked above negatives, overall?Flattering when negatives vastly outnumber positives
PR‑AUCPrecision across all recall levelsBaseline equals the positive rate (0.005 here), not 0.5
AccuracyShare of all predictions that were rightMeaningless for rare classes
4

The threshold is a business decision

A classifier outputs a score. Where you cut that score decides who gets flagged. 0.5 is just a default; the right cut comes from costs, review capacity or a policy limit.

Minimize costprice each FN and FP;pick the cut with thelowest totalbest when costs are known Fit review capacityteam reviews N a day:flag the top N scoresbest when people review Precision target“9 in 10 flags mustbe real”: lowest cutthat reaches itbest for auto‑declines Cap on false alarms“block under 1% ofgood customers”: maxrecall within the capbest for policy limits

Threshold explorer

Simulated scores for 100,000 transactions with 500 frauds. Move the threshold and set your costs.

5

Comparing candidates fairly

Compare models on the same data split and the same evaluation code, then look past the headline metric.

CheckWhy
Primary metric on held‑out data (PR‑AUC here)The number you’ll defend
Spread across folds or random seedsIf the spread is bigger than the gap between two models, they’re tied
Training vs validation gapA large gap signals overfitting
Metric at your chosen thresholdTwo models with equal PR‑AUC can differ where you operate
Latency and cost per predictionReal‑time fraud has a tight time budget
Explainability and fairnessRegulated decisions need both
CandidatePR‑AUC (± seeds)Recall @ 600 alertsp99 latencyVerdict
XGBoost, tuned0.71 ± 0.0174%8 msShip
XGBoost, default0.66 ± 0.0269%8 msBaseline
Neural network0.70 ± 0.0373%21 msTied on quality, slower, harder to explain
Linear Learner0.55 ± 0.0158%3 msToo weak

Illustrative numbers. Log every candidate in MLflow (or SageMaker Experiments, its Studio Classic predecessor) so the table can be regenerated from the runs.

6

Diagnosing training from its curves

Debugger rule (exam name)What it detectsUsual fix
LossNotDecreasingLoss flat or stuckCheck learning rate and data
OverfitValidation worsens while training improvesEarly stopping, regularization
OvertrainingTraining continues long after the best pointEarly stopping
VanishingGradient / ExplodingTensorGradients near zero, or values blow upActivations, initialization, gradient clipping, lower LR
ClassImbalanceSkewed labels during trainingWeights, resampling
Current toolsSageMaker Debugger is closed to new customers, and SageMaker Profiler support ends June 30, 2027. AWS points to MLflow or TensorBoard for training metrics, TensorBoard for gradients and weights, the PyTorch or TensorFlow profiler for GPU kernels, and CloudWatch metrics and alarms for CPU, GPU, memory and disk. GPU utilization stuck low usually means the data pipeline can’t keep up.
7

Explaining what the model learned

XGBoost importance typeMeasuresWatch out
gainAverage loss reduction when a feature is usedThe most useful default
coverHow many rows the feature’s splits affectBreadth, not strength
weightHow often the feature is used to splitFavors features with many distinct values

Built‑in importance is global and has no direction. SHAP values explain single predictions: each feature pushes the score up or down from a baseline, and the pushes add up to the prediction.

Why this transaction scored 0.33 (log‑odds view)
Illustrative values. Average SHAP magnitudes across many rows give a global ranking with direction. Clarify ran SHAP under the hood; with Clarify closed to new customers, use the SHAP library directly.
Low importance is not proof of fairnessDropping a protected attribute, or seeing it rank low, doesn’t mean the model ignores it: zip code, merchant mix or transaction times can stand in for it. Measure outcomes by group (section 8).
8

Post‑training fairness

Pre‑training metrics (Module 2) look at the labels. Post‑training metrics look at the model’s predictions by group. First decide the favorable outcome: here, not being flagged.

MetricCompares across groups
DPPLShare predicted positive (difference)
DI Disparate impactShare predicted positive (ratio); 1 = parity, and many teams investigate below 0.8
RD Recall differenceTrue‑positive rate
AD Accuracy differenceAccuracy
DAR Difference in acceptance ratesPrecision
SD Specificity differenceTrue‑negative rate
TE Treatment equalityRatio of false positives to false negatives
CDDPL, FT, GEDisparity within subgroups, counterfactual fliptest, generalized entropy

DPPL, DI and recall gap

After ClarifyClarify is closed to new customers; existing customers keep it. The metrics are published formulas, so compute them with pandas and scikit‑learn from labels and predictions per group, and log the results to MLflow next to the model.
9

Model Registry and approval

Model package groupone per use case, e.g. card‑fraud New model versionartifact, image, metrics, bias and explanationreports; status PendingManualApproval Reviewer decides ApprovedEventBridge → deploy Rejectedreason recorded Roll back = redeploy an earlier Approved version.Model Cards record intended use, risks and evaluation.
10

Is the model worth running?

Price the outcomes at your chosen threshold. Example: 300 fraud attempts a day averaging $180, 80% caught, 2,000 false alarms a day at $1.50 of friction each, and $4,000 a month for training, hosting and monitoring.

$1,296k −$90k −$4k $1,202k Fraudprevented Customerfriction Platformcost Net permonth
300 × 0.8 × $180 × 30 = $1,296,000; 2,000 × $1.50 × 30 = $90,000. Re‑run it at a few thresholds: the best threshold maximizes net value, which is the same as minimizing expected cost.
11

Hands‑on project: decide like an engineer

Three situations you will meet when tuning and evaluating for real. Pick an answer, then open the reasoning.

1. A Bayesian search that didn’t learn

A tuning job uses the Bayesian strategy with max_jobs=24 and max_parallel_jobs=24. The results look no better than random.

  1. Raise max_jobs to 200
  2. Lower max_parallel_jobs (for example to 3–4), or switch to random search on purpose
  3. Switch to grid search
Suggested answer
b. Bayesian search chooses each trial from finished ones. Launch all 24 at once and none has finished, so every trial is effectively random. Fewer parallel jobs let it learn; if wall‑clock time matters more, use random search deliberately.

2. The objective metric that doesn’t exist

A tuning job on the built‑in XGBoost sets objective_metric_name='validation:aucpr' and fails immediately.

  1. Rename it to validation:pr_auc
  2. Tune on validation:f1 or validation:auc and compare finalists on PR‑AUC yourself, or use Script Mode and emit PR‑AUC with a metric_definitions regex
  3. Remove the objective metric
Suggested answer
b. Built‑in algorithms can only be tuned on the metrics they publish, and the built‑in XGBoost list doesn’t include aucpr. Script Mode lets you print any metric and capture it from the logs.

3. More alerts than people

At the default 0.5 threshold the model raises 2,300 alerts a day. The review team can handle 600.

  1. Hire more reviewers before launch
  2. Set the threshold so about 600 transactions a day score above it, and report precision and recall at that point
  3. Keep 0.5 and review a random 600
Suggested answer
b. Capacity is a constraint, so the threshold follows from it. Ranking by score and reviewing the top 600 catches far more fraud than a random sample of the 2,300.

The build, step by step

  1. Tune the Module 3 XGBoost with AMT: Bayesian, 30 jobs, 3 in parallel, objective validation:f1, eta on a log scale, early stopping Auto.
  2. Evaluate the top 3 on the untouched test set: PR‑AUC, plus precision and recall at several thresholds.
  3. Pick the threshold twice, by cost and by a 600‑alert capacity, and compare the two.
  4. Explain with SHAP: a global summary and three individual flagged transactions.
  5. Check fairness with pandas: DPPL, DI and recall gap across age bands at the chosen threshold.
  6. Register the winner with its metrics and reports as PendingManualApproval, and write a Model Card.
  7. Approve it and confirm an EventBridge rule sees the status change.
  8. Is the winner really better? Retrain the top two configurations with three random seeds each. If the seed‑to‑seed spread is larger than the gap between them, call it a tie and pick on latency and explainability.
12

The rest of the exam guide for this module

Every skill MLA‑C02 lists for Task 2.3, plus related skills from 2.2 and 3.3, where each is covered, then a short lesson for each one the sections above don’t fully reach.

Skill in the exam guideWhere
2.2.3 Hyperparameter optimization (AMT)Section 2
2.3.1 Reproducible experiments (MLflow, Bedrock evaluations, Prompt Management)Section 5, Module 3, deep dive 6
2.3.2 Performance baselines and drift detectionDeep dive 2
2.3.3 Shadow variants vs production variantsDeep dive 3
2.3.4 Explain model outputsSection 7
2.3.5 Debug convergenceSection 6
2.3.6 Evaluation for traditional ML and GenAISections 3–4, deep dives 1 and 4
2.3.7 Human evaluation, human‑in‑the‑loopDeep dive 5
2.3.8 BLEU, ROUGE, BERTScore, semantic similarityDeep dive 4
2.3.9 AI evaluation, bias detection, LLM‑as‑a‑judgeSection 8, deep dive 6
2.3.10 RAG monitoring and retrieval accuracyDeep dive 7
3.3.6 Model versions (Model Registry, MLflow)Section 9

Deep dive 1: regression and multi‑class metrics

MetricMeaningUse when
MAEAverage absolute errorErrors should count linearly; outliers shouldn’t dominate
RMSESquare root of average squared errorBig errors are much worse than small ones
R²Share of variance explainedComparing to predicting the mean
MAPEAverage percentage errorScale‑free reporting; breaks near zero
Macro F1Average of per‑class F1Every class matters equally, including rare ones
Micro / weighted F1Pooled, or weighted by class sizeOverall performance dominated by big classes

Deep dive 2: baselines and drift

Deep dive 3: shadow tests vs A/B tests

Shadow testA/B test all requests productionanswers user shadow: copy,output logged requests split variant A90% of users variant B10% of users no user risk; comparelatency, errors, outputs real outcomes; measuresbusiness impact Usual order: offline evaluation → shadow → A/B or canary → full rollout.

Deep dive 4: metrics for generated text

MetricComparesTypical use
BLEUn‑gram precision against reference textMachine translation
ROUGE (‑1, ‑2, ‑L)n‑gram and longest‑sequence recall against a referenceSummarization
BERTScoreSimilarity of contextual embeddingsParaphrases: same meaning, different words
Semantic similarityCosine similarity of sentence embeddingsAnswer matches the reference in meaning
PerplexityHow surprised a model is by textLanguage‑model fit, not answer quality
Exact match / F1Token overlap with a short answerExtractive question answering

Reference‑based scores reward word overlap, so a correct answer worded differently can score low. Pair them with meaning‑based scores, a judge model or people.

Deep dive 5: people in the loop

Deep dive 6: evaluating foundation models

ApproachStrengthWeakness
Automatic metrics (programmatic)Cheap, repeatableMisses meaning and tone
LLM‑as‑a‑judgeScales; grades correctness, helpfulness, harmfulnessJudge can be biased; spot‑check with people
Human evaluationBest for nuance and brand fitSlow and costly

On AWS: Amazon Bedrock Evaluations (automatic, LLM‑as‑a‑judge and human jobs), the open‑source fmeval library for SageMaker‑hosted models, and Bedrock Prompt Management to version the prompts you evaluate. Responsible‑AI checks (toxicity, harmfulness, bias, refusals) belong in the same evaluation set.

Deep dive 7: evaluating and monitoring RAG

Question Retrievalcontext relevancecontext coveragerecall@k, MRRfix: chunking, embeddings Generationfaithfulness (grounded)correctness, completenesscitation precisionfix: prompt, model Bedrock KB evaluation: retrieve‑only or retrieve‑and‑generate
Evaluate retrieval separately: if the right passage never arrives, no generator can answer well.
13

Self‑check questions

Answer each one aloud first, then open it to check.

1. How does Bayesian tuning differ from random and grid search, and when is each better?

Bayesian search models how hyperparameters relate to the objective and picks each new trial from finished results, so it needs fewer jobs but runs more sequentially. Random search samples independently, so it parallelizes fully. Grid search tries every combination of categorical values and only suits small spaces. Hyperband suits iterative training that reports metrics per epoch, stopping weak trials early.

2. Why can’t you rely on accuracy for fraud, and what replaces it?

With 0.5% fraud, predicting “legit” for everything scores 99.5% accuracy and catches nothing, because true negatives dominate the formula. Use precision, recall, F1 and PR‑AUC, and always look at the confusion matrix at your chosen threshold.

3. What do you give up when you raise the threshold?

Fewer transactions get flagged, so precision usually rises and false alarms fall, but more fraud slips through, so recall drops. Lowering it does the reverse. Where to sit depends on the cost of a missed fraud versus a false alarm, and on how many alerts people can review.

4. Name three ways to choose a threshold.
  • Minimize expected cost: FN × cost of a miss + FP × cost of a false alarm.
  • Fit review capacity: flag the top N scores a day.
  • Meet a target: a minimum precision, or a maximum false‑positive rate, then maximize recall within it.
5. When would you use warm start, and which type?

To continue a search with more jobs or narrower ranges on the same data and algorithm, use IDENTICAL_DATA_AND_ALGORITHM. To re‑tune after the data or algorithm version changes, use TRANSFER_LEARNING. Both need the same objective metric and allow up to 5 finished parent jobs.

6. How do feature importance and SHAP differ?

Built‑in importance (gain, cover, weight) ranks features globally with no direction. SHAP assigns each feature a signed contribution for each prediction, so you can explain one decision and, by averaging, get a global view with direction.

7. What do DPPL and DI measure, and how do they relate?

Both compare how often each group receives positive predictions. DPPL is the difference between the groups’ rates; DI is the ratio of the disadvantaged group’s rate to the advantaged group’s. DPPL = 0 and DI = 1 both mean demographic parity. Pair them with recall difference, since equal flag rates can still hide unequal error rates.

8. How does a model move from registered to deployed?

It’s registered as a version in a model package group with its artifact, image, metrics and reports, status PendingManualApproval. A reviewer or an automated check sets it to Approved or Rejected. An EventBridge rule on the approval change starts the deployment pipeline. Earlier Approved versions stay available for rollback.

9. How do you tell if two candidate models are really different?

Evaluate both on the same held‑out data with the same code, repeat across folds or random seeds, and compare the gap with the spread. If the spread is larger, they’re tied; decide on latency, cost, explainability and fairness.

10. How would you evaluate a RAG assistant?

Split it: score retrieval (are the right passages found? context relevance and coverage, recall@k) and generation (is the answer correct, complete and faithful to the retrieved text, with accurate citations?). Use a labeled question set, an LLM judge with human spot checks, and keep running it after launch.

Exam skill

How to read an exam question

The answer hides in a few words: who does the work, how fast, how much effort, what must not happen. Find those, then eliminate.

Walkthrough 1. A deep‑learning model reports validation loss every epoch. The tuning budget is tight, so the team wants to stop poor trials early and give more training to promising ones. Which tuning strategy should they use?

  1. Grid search
  2. Random search with 200 training jobs
  3. Bayesian search with every job running in parallel
  4. Hyperband, with the tuner’s own early stopping turned off
Show the reasoning
Clues: per‑epoch metrics, tight budget, stop bad trials, reallocate to good ones.
A is out: categorical values only, and it tries every combination.
B is out: runs every trial to the end; spends the budget the team wants to save.
C is out: Bayesian learns from finished trials; full parallelism leaves nothing to learn from.
D: uses intermediate results to stop weak trials and extend strong ones. Its early stopping is built in, so the tuner setting must be off.

Walkthrough 2. A missed fraud costs $200 and a false alarm costs $3 in customer friction. The model outputs a fraud probability. How should the team choose the decision threshold?

  1. Keep the default of 0.5
  2. Pick the threshold with the highest accuracy
  3. On validation data, pick the threshold that minimizes 200 × missed frauds + 3 × false alarms
  4. Pick the threshold with the highest F1
Show the reasoning
Clues: two errors with very different prices.
A is out: 0.5 ignores costs and the class balance.
B is out: accuracy rewards ignoring the rare class.
D is out: F1 weighs precision and recall equally; here a miss costs about 67 times a false alarm.
C: expected cost turns the business numbers straight into a threshold (a low one here).

Walkthrough 3. A new model must be tried on real production traffic to compare latency and outputs with the current model, with no effect on any customer. What should the team do?

  1. An A/B test sending 10% of traffic to the new model
  2. A canary release to 5% of traffic
  3. A shadow test: the new model gets a copy of requests and its answers are only logged
  4. A batch transform on last month’s data
Show the reasoning
Clues: live traffic, latency, zero customer impact.
A and B are out: some customers get the new model’s answers.
D is out: historical data, not live traffic or real endpoint latency.
C: only the production model’s answers reach users; the shadow is measured silently.
Recall

Flashcards

Say the answer out loud before you reveal it. “Again” puts the card back in the round; “Got it” retires it. Progress is saved in this browser.

Test yourself

Practice test

15

Common traps and outdated advice

Mistakes that show up often in tutorials and sample code, with the fix.