All lessons
AIBeginner12 min readWorth knowing

Machine learning basics

How computers learn patterns from examples — the ideas behind every AI feature.

  • Supervised
  • Training vs inference
  • Overfitting
  • Metrics
Step 1/5
Supervised learning starts with labelled examples: photos tagged “cat” or “dog”. A few are locked away as a test set. No peeking.

In 30 seconds

Machine learning means writing a program that learns rules from examples instead of having a person write the rules. You show a model many inputs with the right answers, it adjusts itself to make fewer mistakes, and then it makes predictions on new data. Knowing a few core ideas — training vs inference, overfitting and the right metrics — lets you judge any AI feature sensibly.

Not in my daily stack — I know the concepts and would learn the details when a project needs it.

Why it matters

  • Every AI feature, from spam filters to large language models, rests on the same basics; understanding them helps you ask the right questions about data, quality and risk.
  • Many business problems — churn prediction, demand forecasting, fraud scoring — are still solved better and cheaper by classic ML on tabular data than by an LLM.
  • Engineers increasingly integrate models built by others; knowing metrics and failure modes lets you test them and explain their limits to clients.
  • A team needs ML when the rules are too complex to write by hand but there are plenty of past examples with known outcomes.

How it works

01The idea: learning rules from examples

In normal programming you write the rules: if the email contains 'free money', mark it as spam. In machine learning you provide examples — thousands of emails, each labelled spam or not — and an algorithm finds the rules itself. Think of how a child learns what a dog is: nobody gives them a definition; they see many dogs and non-dogs and build an intuition. A model is a mathematical function with adjustable numbers called parameters (or weights). Training means adjusting those parameters so the model's outputs match the known answers as closely as possible. Each input is described by features — measurable properties such as an order's amount, time of day or the customer's history — and the answer we want to predict is the label or target.

  • Feature: an input property (price, word count, pixel values)
  • Label / target: the answer to learn (spam, price, category)
  • Model: a function with parameters adjusted during training

02Types of learning

Supervised learning uses labelled examples. If the label is a category (spam / not spam, which product category), it is classification; if it is a number (house price, delivery time), it is regression. Unsupervised learning has no labels and finds structure on its own: clustering customers into segments, detecting unusual transactions, or compressing data. Reinforcement learning learns by trial and error from rewards, as in game-playing agents and robot control. Self-supervised learning creates labels from the data itself — for example, hiding the next word in a sentence and predicting it. That is how large language models are pre-trained on huge amounts of text, before being refined with human feedback. For most business problems, supervised learning on tabular data is where you start.

03Training vs inference

Training is the learning phase: the model sees examples, makes predictions, measures how wrong it is with a loss function, and nudges its parameters to reduce that loss — usually with gradient descent, which repeatedly takes small steps 'downhill' on the error surface. It is computationally heavy and happens occasionally. Inference is the using phase: the trained model, now frozen, receives new inputs and returns predictions. It happens constantly, in production, and must be fast and cheap. This split matters for engineering: training needs data pipelines, experiments and often GPUs; inference needs an API, monitoring and latency budgets. When you call an LLM API, you are doing inference on a model someone else trained.

python
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
 
X, y = load_orders_features()  # features and labels (1 = fraud, 0 = ok)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42
)
 
model = RandomForestClassifier(n_estimators=300, random_state=42)
model.fit(X_train, y_train)            # training
 
pred = model.predict(X_test)           # inference on unseen data
print(classification_report(y_test, pred))

04Train, validation and test sets

A model that is tested on the same data it learned from will look brilliant and fail in real life — like a student who memorised last year's exam answers. So you split data into three parts. The training set is for learning. The validation set is for choices you make: which algorithm, which settings (hyperparameters), which features. The test set is locked away and used once at the end to estimate real-world performance honestly. Typical splits are 70/15/15 or 80/10/10. Cross-validation rotates the validation part across several folds to get a more stable estimate on smaller datasets. For time-based data — sales, prices, churn — split by time: train on the past, test on the future, because that is how the model will be used.

05Overfitting and underfitting

Overfitting means the model learned the noise and quirks of the training data instead of the general pattern: excellent training scores, poor scores on new data. Underfitting is the opposite: the model is too simple to capture the pattern and does badly everywhere. Picture fitting a curve through points: a straight line may underfit, a wildly wiggly line through every point overfits, and a smooth curve generalises. Signs of overfitting: a big gap between training and validation scores. Remedies: more and more varied data, a simpler model, regularisation (penalising extreme parameters), early stopping, dropout in neural networks, and removing features that leak the answer. The goal is always generalisation — doing well on data the model has never seen.

  • High train, low validation score → overfitting
  • Low train and low validation score → underfitting
  • Fix with data, simpler models, regularisation, early stopping

06Metrics: choosing what 'good' means

Accuracy — the share of correct predictions — is misleading when classes are imbalanced. If 1% of transactions are fraud, a model that always says 'not fraud' is 99% accurate and useless. So you use better metrics. Precision: of everything flagged as fraud, how much really was fraud? Recall: of all real fraud, how much did we catch? F1 combines both. ROC-AUC and PR-AUC measure how well the model ranks positives above negatives across all thresholds. For regression, MAE (mean absolute error) is easy to explain in real units, and RMSE punishes big errors more. Always tie the metric to business cost: in fraud, a missed fraud may cost far more than a false alarm, so you tune the decision threshold accordingly, often favouring recall.

python
from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score
 
proba = model.predict_proba(X_test)[:, 1]
pred = (proba >= 0.3).astype(int)   # threshold chosen from business costs
 
print("precision", precision_score(y_test, pred))
print("recall   ", recall_score(y_test, pred))
print("f1       ", f1_score(y_test, pred))
print("roc_auc  ", roc_auc_score(y_test, proba))

Use it when

  • Predicting outcomes from historical data with known results: churn, fraud, demand, delivery time.
  • Problems where hand-written rules become endless exceptions, such as spam or image recognition.
  • Ranking and recommendation, where small quality gains matter across millions of decisions.
  • Detecting anomalies in metrics, logs or transactions when 'normal' is easier to learn than to describe.

Skip it when

  • When simple rules work well and must be fully explainable — a clear business rule beats a black box.
  • When you have very little data or no reliable labels, and cannot get them.
  • When a mistake is unacceptable and cannot be reviewed, without strong safeguards and human oversight.

Alternatives

  • Rules and heuristics

    Transparent, instant to change and often good enough for a first version.

  • LLM APIs

    Zero-shot classification or extraction with a prompt, no training data needed; higher per-call cost and latency.

  • Managed AutoML

    Cloud services that try many models on your tabular data; fast baseline, less control.

  • Statistics

    Regression analysis, A/B tests and simple forecasting methods answer many business questions without ML pipelines.

Best practices

  1. Start with a simple baseline (rules, logistic regression, gradient boosting) before deep learning.
  2. Keep a locked test set and split by time for time-dependent data.
  3. Choose metrics that reflect business cost, and tune the decision threshold explicitly.
  4. Check for data leakage: no feature may contain information unavailable at prediction time.
  5. Version data, code and models together so any result can be reproduced.
  6. Monitor production inputs and predictions for drift and retrain on fresh data.
  7. Check performance per subgroup (region, device, customer type) to catch unfair or broken segments.

Common mistakes

  • Reporting accuracy on an imbalanced dataset.
  • Tuning on the test set until it looks good, which turns it into a second validation set.
  • Random splits on time-series data, letting the model 'see the future'.
  • Features that leak the label, such as a 'refund_processed' flag used to predict refunds.
  • Deploying once and never monitoring, while customer behaviour slowly changes.

Deep dive

07Gradient descent and how neural networks learn

Training is an optimisation problem. The loss function turns 'how wrong is the model' into a single number — cross-entropy for classification, mean squared error for regression. The gradient is the direction in which the loss increases fastest with respect to each parameter; gradient descent moves parameters a small step the other way. The step size is the learning rate: too high and training diverges or bounces around, too low and it crawls. In practice we use mini-batches (stochastic gradient descent) and adaptive optimisers such as Adam, which adjust the step size per parameter. Neural networks compute gradients through all layers with backpropagation, an efficient application of the chain rule. Large models add tricks — learning-rate warm-up and decay, normalisation layers, gradient clipping — but the core loop is the same: predict, measure loss, compute gradients, update.

python
import numpy as np
 
# Linear regression y ≈ w*x + b with plain gradient descent
x = np.array([1, 2, 3, 4, 5], dtype=float)
y = np.array([3, 5, 7, 9, 11], dtype=float)   # true: w=2, b=1
w, b, lr = 0.0, 0.0, 0.05
 
for epoch in range(500):
    pred = w * x + b
    err = pred - y
    loss = (err ** 2).mean()
    w -= lr * 2 * (err * x).mean()   # gradient of loss w.r.t. w
    b -= lr * 2 * err.mean()         # gradient of loss w.r.t. b
 
print(round(w, 2), round(b, 2), round(loss, 4))

08Bias–variance trade-off and regularisation

Prediction error has three parts: bias (error from wrong assumptions — a model too simple to capture the pattern), variance (error from sensitivity to the particular training sample — a model so flexible it changes a lot with small data changes) and irreducible noise. Simple models have high bias and low variance; complex models the reverse. Regularisation deliberately adds a little bias to reduce variance: L2 (ridge) shrinks all weights, L1 (lasso) pushes some to exactly zero and selects features, tree models limit depth or leaf size, and neural networks use weight decay, dropout and early stopping. Ensembles reduce variance too: random forests average many decorrelated trees, while gradient boosting adds small trees that correct previous errors. Modern deep learning complicates the classic picture — very large networks can generalise well despite enormous capacity — but on everyday tabular problems the trade-off is a reliable guide.

09Data leakage and evaluation traps

Leakage is the most common reason a model looks great offline and fails in production. Target leakage: a feature encodes the outcome, like 'account_closed_date' when predicting churn. Temporal leakage: aggregates computed over the whole dataset, including the future, or random splits on time-ordered data. Group leakage: the same customer or patient appears in both train and test sets, so the model recognises individuals rather than patterns — use group-aware splits. Pre-processing leakage: scaling, imputing or selecting features on the full dataset before splitting; fit these steps inside a pipeline on training data only. A quick test: if performance seems too good to be true, inspect feature importance and ask, for each top feature, 'would I really know this value at prediction time?'

python
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GroupKFold, cross_val_score
 
# Scaling is fitted inside each fold -> no pre-processing leakage
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
 
# Same customer never in both train and validation folds
scores = cross_val_score(pipe, X, y, groups=customer_ids,
                         cv=GroupKFold(n_splits=5), scoring="roc_auc")
print(scores.mean(), scores.std())

10From notebook to production (MLOps essentials)

A model in a notebook is an experiment; a model in production is a service with dependencies. Essentials: reproducible training (versioned data snapshot, code commit, random seeds, environment), a model registry storing artefacts with their metrics, and the exact same feature logic in training and serving — mismatches here (training–serving skew) are a classic silent bug, which feature stores aim to prevent. Serve models behind an API or batch job with input validation, latency budgets and a fallback rule. Monitor three layers: system (latency, errors), data (feature distributions, missing values, drift) and outcome (real metrics once labels arrive). Roll out with shadow mode or canaries, compare against the current model, and keep rollback simple. Retrain on a schedule or trigger, and re-check fairness and subgroup performance each time.

Real-world scenarios

01

A fraud model with 99% accuracy

Problem

A team proudly reports 99% accuracy for a new fraud model. Fraud is about 1% of transactions, and the payments team says it barely catches anything.

How to solve it

Accuracy is meaningless at this imbalance — 'never fraud' scores 99%. Re-evaluate with precision, recall and PR-AUC on a time-based test set. Plot precision and recall across thresholds and choose one with the payments team based on costs: an average fraud loss versus the cost of a manual review. Use class weights or resampling during training if recall is low. Report results per merchant type and amount band. In production, send high-score transactions to review rather than auto-blocking, and feed review outcomes back as fresh labels.

02

Great offline, poor in production

Problem

A churn model scored 0.93 ROC-AUC offline, but after launch its predictions barely beat random. Nothing obvious changed.

How to solve it

Suspect leakage and skew first. List the top features and check whether each is known at prediction time — a 'cancellation_reason' or post-churn activity field is a red flag. Check that the split was by time, not random, and that the same customers were not in both sets. Compare feature distributions between the training data and live inputs; differences often come from serving code computing features differently. Rebuild with a time-based split and a shared feature pipeline, then validate in shadow mode before switching.

03

Do we need ML or an LLM for ticket routing?

Problem

A support team wants tickets routed automatically to one of 12 queues. They have 40,000 historical tickets already routed by agents.

How to solve it

With plenty of labelled data and a fixed label set, a classic text classifier (TF-IDF plus logistic regression, or a small fine-tuned model) is a strong, cheap baseline with millisecond inference. Compare it on a held-out, time-based test set against an LLM prompt with the queue descriptions and a few examples. Measure accuracy per queue and the cost of each misroute. Often the classic model handles the bulk cheaply, and an LLM or a human handles low-confidence tickets. Monitor drift when new products launch.

Cheat sheet

Install the classic ML toolkit
pip install scikit-learn pandas numpy
Stratified train/test split
train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
Time-ordered cross-validation
from sklearn.model_selection import TimeSeriesSplit
Leak-free preprocessing
make_pipeline(StandardScaler(), LogisticRegression())
Precision
TP / (TP + FP)
Recall
TP / (TP + FN)
F1 score
2 · precision · recall / (precision + recall)
Full classification report
print(classification_report(y_test, pred))
Overfitting check
compare train score vs validation score; big gap = overfit

Questions & answers

Q1What is the difference between AI, machine learning and deep learning?

AI is the broad goal of making computers do tasks that seem to need intelligence; it includes rule-based systems too. Machine learning is the subset where systems learn patterns from data instead of following hand-written rules. Deep learning is a subset of ML using neural networks with many layers, which excel at images, audio and text. Large language models are deep learning models trained on huge amounts of text. For a typical business problem on spreadsheet-like data, classic ML such as gradient boosting is often still the best choice.

Q2What is overfitting and how do you prevent it?

Overfitting is when a model memorises the training data, including its noise, and fails to generalise to new data. You spot it when training scores are much better than validation scores. To prevent it: get more and more varied data, use a simpler model or fewer features, apply regularisation, use early stopping when validation performance stops improving, use dropout or data augmentation for neural networks, and evaluate with cross-validation. Also check for leakage, since a model that looks too good is often cheating with a feature that contains the answer.

Q3Precision vs recall — which matters more?

It depends on the cost of each mistake. Precision answers: when the model says yes, how often is it right? Recall answers: of all real positives, how many did we find? For a spam filter, high precision matters, because hiding a real email is costly. For fraud detection or cancer screening, recall often matters more, because missing a case is expensive, and a human can review false alarms. You move between them by changing the decision threshold, so choose it with stakeholders based on real costs, and report both numbers.

Q4Why do we need a separate test set?

Every decision you make while looking at data — choosing features, models or hyperparameters — slightly fits your choices to that data. If you measure final performance on the same data, the estimate is optimistic. A test set that was never used for any decision gives an honest estimate of how the model will do on new data. The validation set is for making choices; the test set is for the final report. If you keep checking the test set and adjusting, it stops being a test set, and you need fresh data.

Q5What is the difference between training and inference?

Training is when the model learns: it processes labelled examples, measures its error with a loss function and updates its parameters, often for hours or days on specialised hardware. Inference is when the trained model is used: it receives new inputs and returns predictions, typically in milliseconds, many times per second in production. Training cost is paid occasionally; inference cost is paid on every request. That is why production concerns — latency, throughput, monitoring and cost per prediction — focus on inference.

Q6What is data drift?

Data drift is when the data the model sees in production changes compared with the training data. Feature distributions can shift — new customer segments, a new app version, seasonality — or the relationship between features and outcomes can change, which is called concept drift, for example when fraudsters change tactics. Performance then degrades silently. You handle it by monitoring input distributions and prediction rates, comparing predictions with real outcomes as labels arrive, setting alerts, and retraining regularly or when drift is detected.

Senior-level questions

S1How would you take a model from prototype to a reliable production service?

First make training reproducible: versioned data snapshot, pinned environment, seeds, and a pipeline that produces the model and its evaluation report from one command. Store the artefact in a registry with metrics and the data version. Implement features once and share them between training and serving to avoid skew. Serve behind an API with input validation, timeouts and a rule-based fallback, or as a batch job if real-time is not needed — batch is far simpler. Release in shadow mode, compare against the current approach, then canary. Monitor latency and errors, input drift, and real outcomes when labels arrive. Define retraining triggers and an owner. The trade-off is effort: a full MLOps stack is overkill for one model; start with scripts, a registry and good monitoring, and add tooling as models multiply.

S2Classic ML, fine-tuned small model or LLM prompting — how do you choose?

I compare them on the same held-out data, but a few rules of thumb guide the shortlist. Tabular data with good labels: gradient boosting almost always wins on cost, latency and accuracy. Text tasks with a fixed label set and thousands of labels: a classic or small fine-tuned classifier is cheap and fast at high volume. Few or no labels, many categories, or tasks needing reasoning and world knowledge: LLM prompting delivers quickly and can generate labels to bootstrap a smaller model later. Also weigh latency, cost per million predictions, data privacy, explainability and maintenance — prompts are easy to change, but per-call cost scales with volume. Hybrid setups are common: a cheap model handles confident cases and an LLM or human handles the rest.

S3How do you detect and handle unfair model behaviour?

Start by defining the groups that matter legally and ethically for the product, and whether you can measure them. Then evaluate per group: error rates, false positive and false negative rates, and calibration, not just overall accuracy. Look for causes: under-representation in training data, biased historical labels, or proxy features such as postcode standing in for protected attributes. Mitigations include collecting better data, reweighting, removing or constraining proxy features, per-group threshold review, and human review for borderline decisions. Different fairness definitions can conflict, so the choice is a product and legal decision, documented with stakeholders. Repeat the analysis on every retrain and monitor in production, because drift can introduce new disparities.

Glossary

Feature
A measurable input property the model uses, such as price, age or word count.
Label
The correct answer for a training example, which the model learns to predict.
Parameters (weights)
The numbers inside a model that training adjusts to reduce errors.
Loss function
A formula that measures how wrong the model's predictions are; training tries to minimise it.
Hyperparameter
A setting chosen before training, like tree depth or learning rate, tuned on validation data.
Overfitting
When a model memorises training data and performs poorly on new, unseen data.
Inference
Using a trained model to make predictions on new inputs.
Data leakage
When training data includes information that would not be available at prediction time.
Drift
Changes in production data or relationships over time that make a model less accurate.

Have a product in mind?Let's build it.

Tell me about your idea, your product or your team. I usually reply within one working day.