Learnings

AI Engineering

Machine Learning Basics

Enough machine learning to work with an ML team as a backend engineer: what a model is, how it is trained and measured, and what breaks once it is in production. One example runs through the page, a model that flags risky bank transfers, on synthetic data generated with a fixed seed. Every Python file here was run (Python 3.9, numpy 1.26, scikit-learn 1.6) and every output block is pasted from that run; the neural network, transformer and LLM chapters are diagrams and hedged description, with nothing run.

Ideas and data

Part 1 of 5 · what a model is, and what it eats

Rules or a learned model

Ideas and data

Both turn a transfer into "risky" or "safe". With rules an engineer writes the logic; with ML a training job finds it from past transfers whose outcome is known.

Same input, same output. What differs is who writes the logic.
RulesLearned model
Logic lives inCode you can readNumbers (parameters) in a file
NeedsA domain expertMany labelled examples
OutputYes or noA score, usually a probability
When the world changesEdit the ruleRetrain on new data
Explaining one decisionEasyHarder, sometimes much harder
Good forFew clear conditions, legal limitsMany weak signals that combine

Interview point: start with rules. They are the baseline a model has to beat, and below one rule is measured next to the model. Most real systems keep both.

Three kinds of learning

Ideas and data

The kinds differ in what the training data contains. Most business ML is supervised.

KindLearns fromPredictsBank example
Supervised: classificationInputs with a known categoryA categoryRisky or safe transfer
Supervised: regressionInputs with a known numberA numberNext month's balance
UnsupervisedInputs only, no answersGroups, outliers, compressed formCustomer segments, odd accounts
ReinforcementRewards for actions over timeThe next actionRare here; games, robotics, some pricing
Self-supervisedLabels made from the data itselfThe hidden partNext word of a text: how LLMs are pretrained

Training and inference

Ideas and data

Training is a batch job that reads history and writes a model file. Inference is a request path that loads the file and answers one question at a time.

Training: offline, slow, restartable. Nobody is waiting on it.
Inference: online, inside the latency budget of a user request.
TrainingInference
RunsOn a schedule, minutes to daysOn every request, milliseconds
ReadsAll history, from a warehouseOne row, from fast stores
HardwareBursty: big machines or GPUs, then nothingSteady: replicas behind a load balancer
Optimised forThroughput and costTail latency and uptime
On failureRerun the jobFallback answer, alert
Usually owned byML engineers, data scientistsBackend and platform engineers

Features and labels

Ideas and data

A feature is one input column. The label is the answer the model learns to predict. This file invents 40,000 transfers: the data is synthetic and the "hidden rule" inside it stands in for real fraud behaviour.

  • X is the feature matrix (rows × 6), y the label vector. Every example below imports this file, so the blocks are one project, not standalone scripts.
  • Only 2.6% of rows are risky. That imbalance drives the whole metrics part.
  • Real labels arrive late (a chargeback weeks later) and are often wrong. Ask the ML team where the labels come from.

Train, validation, test

Ideas and data

A model is judged on rows it never saw. Three piles, three jobs.

Look at the test set many times and it becomes a second validation set.

Time matters: a random split is fine for this invented data. For real transfers split by date (train on January to June, test on July), because production always predicts the future from the past.

Data leakage

Ideas and data

Leakage is training on information that will not exist at prediction time. The second half of split.py adds a refunded column that is only filled in after fraud is confirmed.

The leaked model looks better offline (0.975 against 0.910) and is worse live (0.807), where the column is still empty.

LeakExampleGuard
Column from the futurerefunded, account_closedFor each feature ask: known at request time?
Statistics from all rowsScaling with the mean of train + testFit scalers on train only (see logistic.py)
Same entity on both sidesOne customer's transfers in train and testSplit by customer or by date
DuplicatesRetried requests stored twiceDeduplicate before splitting

Smell: a result that is too good. Backend engineers catch leaks often, because they know when each column is written.

Training a model

Part 2 of 5 · loss, gradient descent, and fitting too well

A linear model and gradient descent

Training a model

The model is fee = w × amount + b. Training means finding the w and b that make the loss (the average squared error) small, by repeating four steps.

The gradient says which way each parameter should move to lower the loss.
  • The loss falls from 325 to 0.81 and stops: 0.81 is the noise that no line can remove. The data was made with w=2.5, b=4.0 and the loop finds 2.486 and 3.981.
  • Learning rate too high and the loss explodes; too low and training crawls. It is a hyperparameter: a setting you choose, not one the model learns.
  • Neural networks train the same way with millions or billions of parameters, on a small random batch of rows per step (stochastic gradient descent).

Logistic regression

Training a model

For yes or no questions, pass the linear score through a sigmoid to get a probability between 0 and 1, and use log loss, which punishes confident wrong answers.

  • The hand-written loop lands on almost the same weights as scikit-learn: a library is this loop with a better optimiser.
  • Weights are readable. Positive raises risk (amount, new payee); hour is negative because the risky hours in this data are the small ones.
  • A linear model adds signals up. It cannot say "new payee and at night" unless someone builds that combined feature. Trees can.

Underfitting and overfitting

Training a model

A model that is too simple misses the pattern. One that is too flexible memorises the training rows, noise included. The demo grows a decision tree and compares training rows with validation rows.

Rows aboveTrainValidationFix
Underfit (high bias)depth 1, 2PoorPoorMore capacity, better features
About rightdepth 4, 6GoodClose to trainStop here
Overfit (high variance)depth 8 and upKeeps improvingGetting worseLess capacity, more data, regularise

Read it as: training error always falls as the model grows. Validation error falls, then rises. The unlimited tree scores AUC 1.000 on rows it has seen and 0.637 on rows it has not.

Regularisation

Training a model

Regularisation is any limit that stops a model fitting noise. In the last output row the tree has no depth limit but each leaf must hold 200 rows: validation AUC returns to 0.896.

FamilyKnobWhat it does
LinearL2 (ridge), L1 (lasso)Penalty on large weights; L1 pushes some to exactly zero
TreesMax depth, min rows per leafFewer, larger leaves
BoostingLearning rate, tree count, early stoppingStop adding trees when validation stops improving
Neural networksWeight decay, dropout, early stoppingSmaller weights, random units switched off in training
AnyMore dataThe most reliable one, and often a backend task

Cross-validation

Training a model

One validation split can be lucky. K-fold cross-validation trains K times, each time validating on a different fifth, and reports the mean and the spread.

Each run trains on the other four folds. Every row is validated on exactly once.

Depth 6 wins (0.893), but its folds range from 0.882 to 0.918. A difference smaller than that spread is not a real improvement.

Model families

Training a model

FamilyHow it predictsUsed forCost
Linear, logisticWeighted sum of featuresBaselines, regulated decisions that must be explained, very high request ratesTiny, CPU
Decision treeChain of if / else splitsExplaining; rarely aloneTiny
Random forestAverage of many independent treesTabular data, few settings to tuneCPU, larger file
Gradient boostingTrees added one by one, each fixing the last one's errorsTabular data: the usual first choice for rows and columns (fraud, credit, ranking)CPU
Neural networkLayers of weighted sums and non-linear stepsText, images, audio, sequences, very large dataGPUs, much data

Honest reading: on six clean invented columns the families finish within 0.03 of each other, so this run shows cost more than quality. Times are from one laptop run and change every run. On messy real tables boosting usually leads; do not take that from this output.

Measuring a model

Part 3 of 5 · one test set, many numbers

Accuracy, and why it lies

Measuring a model

Accuracy is the share of correct answers. With 2.6% risky rows, a program that flags nothing is 97.4% accurate and catches no fraud. The file scores the 8,000 test transfers and counts every outcome for several decisions.

  • The most accurate row (t=0.5, 97.72%) misses 138 of 207 risky transfers. The cheapest row (t=0.02) is only 86.41% accurate.
  • The one-line rule holds up well, partly because the data was generated with that pattern in it. At t=0.1 the model catches 18 more for 15 more false alarms.

Confusion matrix, precision, recall, F1, ROC AUC

Measuring a model

The four counts for the model at threshold 0.1, from the output above.

FlaggedNot flagged
Really risky (207)128 true positives79 false negatives (missed)
Really safe (7,793)235 false positives (false alarms)7,558 true negatives
MetricFormulaHereQuestion it answers
PrecisionTP / (TP + FP)128 / 363 = 0.35Of the flagged, how many were risky?
RecallTP / (TP + FN)128 / 207 = 0.62Of the risky, how many did we catch?
F12PR / (P + R)0.45One number that is low if either is low
ROC AUCChance a random risky row outscores a random safe one0.91How well do scores rank, before any threshold? 0.5 is a coin, 1.0 is perfect.

Know: precision and recall pull against each other. ROC AUC needs no threshold, which makes it good for comparing models and useless for telling the support team how many alerts to expect. On very rare positives, teams often prefer the precision-recall curve.

The threshold is a business decision

Measuring a model

The model outputs a score. Where to cut it depends on what a miss and a false alarm cost, and that is not an ML question. The cost column above uses invented prices: 5,000 per missed risky transfer, 100 per manual review. It is lowest at 0.02, with 1,216 reviews per 8,000 transfers.

Two thresholds give three actions. The numbers belong in config, not in the model file.

For the backend: the review team's capacity is a hard limit. If they can handle 400 reviews, the threshold is 0.1 (363 reviews) whatever the cost column says. Changing a threshold needs no retraining.

Regression metrics

Measuring a model

When the prediction is a number, measure how far off it is. Values are the last line of the gd_linear.py output.

MetricMeaningThereNote
MAEAverage absolute error0.712Same unit as the target, easy to explain
RMSERoot of the average squared error0.898Punishes large misses more
R2Share of variance explained0.9841 is perfect, 0 is "always predict the mean"

Neural networks and LLMs

Part 4 of 5 · one diagram each, nothing run

A neural network

Neural networks and LLMs · not run for this page

A unit is a small logistic regression: a weighted sum, then a non-linear step. A layer is many units side by side; a network is layers in a row, trained by the same gradient descent.

Every arrow is one weight. Hidden units build the combined features a linear model lacks.
  • Backpropagation is the method that computes the gradient for every weight in one backward pass.
  • Weights are matrices and the work is matrix multiplication, which is why GPUs help.

A transformer

Neural networks and LLMs · simplified, not run for this page

A transformer is a neural network for sequences. Its key layer is attention: each token's vector is updated using the tokens around it. Text models of this kind produce one token at a time.

A decoder-style text model, with many details left out. Each new token is another pass.

Why it matters to you: output arrives token by token, so latency and cost grow with output length. That is why LLM APIs stream and bill per token.

Where an LLM fits

Neural networks and LLMs · general description

A large language model is a very large transformer trained to predict the next token. The three stages are the same as for any model on this page; only the scale changes.

Most teams only ever do the last box.
StageWhat happensWho does it
PretrainingSelf-supervised next-token prediction on a huge corpusA few labs with very large GPU clusters
Fine-tuningMore training on a smaller, task-specific datasetSome product teams, when prompting is not enough
InferenceSend text, receive text; no weights changeYou, through an API

The rest of this group is about that last row, starting with LLM APIs and Prompting. What carries over from this page: hold out a test set, pick metrics before you look, watch for drift.

Models in production

Part 5 of 5 · where backend engineers do most of the work

The ML lifecycle

Models in production

A model is never finished. It decays as the world moves away from its training data, so the loop is the product.

MLOps is this loop automated: the same ideas as CI/CD, with data as a second input.

Batch and online prediction

Models in production

Batch scores everything on a schedule and stores the answers. Online scores one request as it arrives, as in the inference diagram.

Batch prediction: the request path never touches the model.
BatchOnline
FreshnessHours oldThis request
FitsMonthly credit score, churn listRisk of this transfer, right now
If the model is downYesterday's scores still workNeeds a fallback (rules) and a timeout
Cost per rowLowestHigher: per-call overhead

A single-row call costs about half a millisecond here; in one batch call a row costs thousands of times less. Timings are from one laptop run and vary a lot with load. If latency allows, collect requests into small batches.

Feature store, skew and versioning

Models in production

Training-serving skew means a feature is computed one way for training and another way in the service. The last output line above is one case: the same transfer with the amount sent in thousands scores 0.009, not 0.409, and nothing raises an error.

The feature store idea: define a feature once, read it from two stores.
Version thisWhyIn the JSON above
Model fileRoll back in one stepversion
Feature list and orderA swapped column is silent skewfeatures
Training dataReproduce or audit a decisiontrain_data_sha256, train_rows
Library versionsA pickled model may not load in another versionsklearn
ThresholdIt changes behaviour as much as the weightsthreshold

Also: log the model version with every prediction. A model file loaded with pickle or joblib can run code on load, so load only files your own pipeline wrote.

Drift

Models in production

Drift is the world moving away from the training data. Here one frozen model scores six later months while the generator's drift setting shifts amounts, new payees and the fraud pattern itself.

KindWhat changedSeen in
Data driftThe inputs: larger amounts, more new payeesPSI and flagged share, at once and without labels
Concept driftThe link from inputs to label: fraud moved to burstsAccuracy, recall, AUC, only when labels arrive
  • Accuracy falls from 95.7% to 82.2% with no deploy and no error. The flagged share triples, so the review queue fills first.
  • A common rule of thumb for PSI: under 0.1 stable, above 0.25 investigate. Treat the cut-offs as approximate.
  • Left of the bar is what you can alert on today. Right of it needs labels, which may be weeks late.

What backend engineers own

Models in production

AreaYour jobGoes wrong as
Data pipelinesEvents and labels arrive complete, once, with timestampsSilent nulls, duplicates, leaks
Serving APIValidate input, load the model once, time out, fall back to rulesModel reloaded per request; no fallback
LatencyBudget for feature lookups plus scoring; watch p99Three sequential lookups before the model runs
Prediction logStore input, score, model version, request idNobody can explain or replay a decision
MonitoringScore distribution, null rates, drift, then accuracy when labels landOnly CPU and 5xx are on the dashboard
RolloutShadow, canary, one-step rollbackModel and feature code deployed out of step

Vocabulary

Models in production

They sayIt means
Feature, label (target)Input column, answer column
Ground truthThe real outcome, once known
Parameter (weight)A number the training finds
HyperparameterA setting a person or a search chooses: depth, learning rate
LossThe number training minimises; not always the metric you report
Epoch, batch, stepOne pass over the data; a slice of rows; one update
BaselineThe simple thing to beat: a rule, or the current model
EmbeddingA list of numbers that stands for a word, item or user
Checkpoint, artifactA saved model file
CalibrationA score of 0.2 really means 20% of such rows are positive
Shadow, canary, A/BNew model scores traffic unused; decides for a small share; two models compared on a business metric
Offline, online metricMeasured on a test set; measured on live traffic

Cheat sheet

Models in production

SituationRemember
New prediction problemRule baseline first, then the simplest model
Rows and columnsGradient boosting; logistic regression if it must be explained
Text, images, audioA neural network, usually a pretrained one
Train score high, validation lowOverfitting: regularise or add data
Both scores lowUnderfitting: better features, more capacity
Result too good to be trueLeakage until shown otherwise
Rare positivesNot accuracy: precision, recall, cost
Comparing two modelsSame test set, look at the spread
Too many or too few alertsMove the threshold; no retraining
Good offline, bad liveTraining-serving skew or a leak
Slowly getting worseDrift: monitor inputs, retrain
Answer not needed this secondBatch prediction

Interview questions

Models in production

QuestionShort answer
When would you not use ML?When a few clear rules do the job, when there are no labels, or when every decision must be explained exactly.
Why do training and inference need different infrastructure?Training is a bursty, restartable batch job tuned for throughput. Inference is an always-on request path tuned for tail latency.
What is data leakage?Training on information that is missing at prediction time, such as a column written after the outcome. Great offline, poor live.
How do you spot overfitting?Training error keeps falling while validation error rises. Fix with regularisation, a simpler model or more data.
99% accuracy on fraud. Good?Unknown. If 1% is fraud, flagging nothing scores 99%. Ask for precision, recall and the cost of each error.
Who chooses the threshold?The business: error costs and review capacity. Engineering makes it configurable and logged.
What is training-serving skew?The same feature computed differently offline and online. Prevent with one shared definition and by comparing logged serving features with training data.
Data drift or concept drift?Inputs changed, or the input-to-label relation changed. The first shows without labels, the second only with them.
The model service is down. What happens to transfers?Short timeout, then a rule-based fallback and an alert. Decide in advance whether to fail open or closed.
How does an LLM relate to all this?It is a very large neural network, pretrained by next-token prediction. Most teams only do inference through an API, and still need test sets and monitoring.

Back to AI Engineering.