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
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.
| Rules | Learned model | |
|---|---|---|
| Logic lives in | Code you can read | Numbers (parameters) in a file |
| Needs | A domain expert | Many labelled examples |
| Output | Yes or no | A score, usually a probability |
| When the world changes | Edit the rule | Retrain on new data |
| Explaining one decision | Easy | Harder, sometimes much harder |
| Good for | Few clear conditions, legal limits | Many 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
The kinds differ in what the training data contains. Most business ML is supervised.
| Kind | Learns from | Predicts | Bank example |
|---|---|---|---|
| Supervised: classification | Inputs with a known category | A category | Risky or safe transfer |
| Supervised: regression | Inputs with a known number | A number | Next month's balance |
| Unsupervised | Inputs only, no answers | Groups, outliers, compressed form | Customer segments, odd accounts |
| Reinforcement | Rewards for actions over time | The next action | Rare here; games, robotics, some pricing |
| Self-supervised | Labels made from the data itself | The hidden part | Next word of a text: how LLMs are pretrained |
Training and inference
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 | Inference | |
|---|---|---|
| Runs | On a schedule, minutes to days | On every request, milliseconds |
| Reads | All history, from a warehouse | One row, from fast stores |
| Hardware | Bursty: big machines or GPUs, then nothing | Steady: replicas behind a load balancer |
| Optimised for | Throughput and cost | Tail latency and uptime |
| On failure | Rerun the job | Fallback answer, alert |
| Usually owned by | ML engineers, data scientists | Backend and platform engineers |
Features and labels
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
A model is judged on rows it never saw. Three piles, three jobs.
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
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.
| Leak | Example | Guard |
|---|---|---|
| Column from the future | refunded, account_closed | For each feature ask: known at request time? |
| Statistics from all rows | Scaling with the mean of train + test | Fit scalers on train only (see logistic.py) |
| Same entity on both sides | One customer's transfers in train and test | Split by customer or by date |
| Duplicates | Retried requests stored twice | Deduplicate 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
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 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
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);
houris 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
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 above | Train | Validation | Fix | |
|---|---|---|---|---|
| Underfit (high bias) | depth 1, 2 | Poor | Poor | More capacity, better features |
| About right | depth 4, 6 | Good | Close to train | Stop here |
| Overfit (high variance) | depth 8 and up | Keeps improving | Getting worse | Less 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
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.
| Family | Knob | What it does |
|---|---|---|
| Linear | L2 (ridge), L1 (lasso) | Penalty on large weights; L1 pushes some to exactly zero |
| Trees | Max depth, min rows per leaf | Fewer, larger leaves |
| Boosting | Learning rate, tree count, early stopping | Stop adding trees when validation stops improving |
| Neural networks | Weight decay, dropout, early stopping | Smaller weights, random units switched off in training |
| Any | More data | The most reliable one, and often a backend task |
Cross-validation
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.
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
| Family | How it predicts | Used for | Cost |
|---|---|---|---|
| Linear, logistic | Weighted sum of features | Baselines, regulated decisions that must be explained, very high request rates | Tiny, CPU |
| Decision tree | Chain of if / else splits | Explaining; rarely alone | Tiny |
| Random forest | Average of many independent trees | Tabular data, few settings to tune | CPU, larger file |
| Gradient boosting | Trees added one by one, each fixing the last one's errors | Tabular data: the usual first choice for rows and columns (fraud, credit, ranking) | CPU |
| Neural network | Layers of weighted sums and non-linear steps | Text, images, audio, sequences, very large data | GPUs, 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
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
The four counts for the model at threshold 0.1, from the output above.
| Flagged | Not flagged | |
|---|---|---|
| Really risky (207) | 128 true positives | 79 false negatives (missed) |
| Really safe (7,793) | 235 false positives (false alarms) | 7,558 true negatives |
| Metric | Formula | Here | Question it answers |
|---|---|---|---|
| Precision | TP / (TP + FP) | 128 / 363 = 0.35 | Of the flagged, how many were risky? |
| Recall | TP / (TP + FN) | 128 / 207 = 0.62 | Of the risky, how many did we catch? |
| F1 | 2PR / (P + R) | 0.45 | One number that is low if either is low |
| ROC AUC | Chance a random risky row outscores a random safe one | 0.91 | How 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
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.
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
When the prediction is a number, measure how far off it is. Values are the last line of the gd_linear.py output.
| Metric | Meaning | There | Note |
|---|---|---|---|
| MAE | Average absolute error | 0.712 | Same unit as the target, easy to explain |
| RMSE | Root of the average squared error | 0.898 | Punishes large misses more |
| R2 | Share of variance explained | 0.984 | 1 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.
- 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.
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.
| Stage | What happens | Who does it |
|---|---|---|
| Pretraining | Self-supervised next-token prediction on a huge corpus | A few labs with very large GPU clusters |
| Fine-tuning | More training on a smaller, task-specific dataset | Some product teams, when prompting is not enough |
| Inference | Send text, receive text; no weights change | You, 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
A model is never finished. It decays as the world moves away from its training data, so the loop is the product.
Batch and online prediction
Batch scores everything on a schedule and stores the answers. Online scores one request as it arrives, as in the inference diagram.
| Batch | Online | |
|---|---|---|
| Freshness | Hours old | This request |
| Fits | Monthly credit score, churn list | Risk of this transfer, right now |
| If the model is down | Yesterday's scores still work | Needs a fallback (rules) and a timeout |
| Cost per row | Lowest | Higher: 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
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.
| Version this | Why | In the JSON above |
|---|---|---|
| Model file | Roll back in one step | version |
| Feature list and order | A swapped column is silent skew | features |
| Training data | Reproduce or audit a decision | train_data_sha256, train_rows |
| Library versions | A pickled model may not load in another version | sklearn |
| Threshold | It changes behaviour as much as the weights | threshold |
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
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.
| Kind | What changed | Seen in |
|---|---|---|
| Data drift | The inputs: larger amounts, more new payees | PSI and flagged share, at once and without labels |
| Concept drift | The link from inputs to label: fraud moved to bursts | Accuracy, 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
| Area | Your job | Goes wrong as |
|---|---|---|
| Data pipelines | Events and labels arrive complete, once, with timestamps | Silent nulls, duplicates, leaks |
| Serving API | Validate input, load the model once, time out, fall back to rules | Model reloaded per request; no fallback |
| Latency | Budget for feature lookups plus scoring; watch p99 | Three sequential lookups before the model runs |
| Prediction log | Store input, score, model version, request id | Nobody can explain or replay a decision |
| Monitoring | Score distribution, null rates, drift, then accuracy when labels land | Only CPU and 5xx are on the dashboard |
| Rollout | Shadow, canary, one-step rollback | Model and feature code deployed out of step |
Vocabulary
| They say | It means |
|---|---|
| Feature, label (target) | Input column, answer column |
| Ground truth | The real outcome, once known |
| Parameter (weight) | A number the training finds |
| Hyperparameter | A setting a person or a search chooses: depth, learning rate |
| Loss | The number training minimises; not always the metric you report |
| Epoch, batch, step | One pass over the data; a slice of rows; one update |
| Baseline | The simple thing to beat: a rule, or the current model |
| Embedding | A list of numbers that stands for a word, item or user |
| Checkpoint, artifact | A saved model file |
| Calibration | A score of 0.2 really means 20% of such rows are positive |
| Shadow, canary, A/B | New model scores traffic unused; decides for a small share; two models compared on a business metric |
| Offline, online metric | Measured on a test set; measured on live traffic |
Cheat sheet
| Situation | Remember |
|---|---|
| New prediction problem | Rule baseline first, then the simplest model |
| Rows and columns | Gradient boosting; logistic regression if it must be explained |
| Text, images, audio | A neural network, usually a pretrained one |
| Train score high, validation low | Overfitting: regularise or add data |
| Both scores low | Underfitting: better features, more capacity |
| Result too good to be true | Leakage until shown otherwise |
| Rare positives | Not accuracy: precision, recall, cost |
| Comparing two models | Same test set, look at the spread |
| Too many or too few alerts | Move the threshold; no retraining |
| Good offline, bad live | Training-serving skew or a leak |
| Slowly getting worse | Drift: monitor inputs, retrain |
| Answer not needed this second | Batch prediction |
Interview questions
| Question | Short 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.