Machine learning essentials

Loss, optimisation, generalisation and honest evaluation, before neural networks make everything bigger.

Beginner about 6 h

The picture

  1. 01

    Data split

    train / val / test

  2. 02

    Model + loss

    what to minimise

  3. 03

    Optimiser

    SGD, Adam

  4. 04

    Regularise

    stop overfitting

  5. 05

    Evaluate

    the right metric

The loop every model shares

Pick a model fθf_\theta, a loss L\mathcal{L} and data. Adjust θ\theta to reduce the loss on training data, then check it on data the model has never seen. Everything in generative AI is this loop at scale.

Splits and leakage

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.datasets import load_breast_cancer

X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)
clf = LogisticRegression(max_iter=5000).fit(X_tr, y_tr)
print(classification_report(y_te, clf.predict(X_te)))

Leakage is the silent killer: fitting a scaler on all the data, duplicate rows across splits, or tuning hyper-parameters on the test set. For LLM work the equivalent is benchmark contamination: test questions that appeared in training data.

Reading the two curves

  • Train loss high, validation loss high: underfitting. Use a bigger model, train longer, or improve the features.
  • Train loss low, validation loss high and rising: overfitting. Get more data, regularise, or stop early.
  • Both low: fine. Check the test set once.

Optimisers

SGD follows the gradient; Adam adds momentum and per-parameter scaling and is the default for transformers (usually its decoupled-weight-decay version, AdamW). The learning rate matters more than almost any other choice, and schedules with a short warm-up then decay are standard.

Pick the metric that matches the cost

Accuracy hides imbalance. If missing a positive costs ten times a false alarm, optimise recall at a threshold, not accuracy. For generation, no single number is enough: you will build task-specific evals in a later stage.

Common mistakes

  • Reporting the best of many runs on the test set.
  • Tuning on the test split.
  • Comparing models that used different tokenisers by perplexity alone.

Exercises

  1. Plot train and validation accuracy against model size for a decision tree depth sweep, and mark where overfitting starts.
  2. Move a StandardScaler outside and then inside a Pipeline and measure how the cross-validation score changes.

You are done when you can…

  • Split data without leakage and explain why a test set is touched once
  • Diagnose overfitting versus underfitting from two loss curves
  • Choose a metric that matches the cost of each kind of error