Bitpath

Classic Machine Learning

Machine learning before neural networks, and still the right tool for most tables of numbers: regression, trees, forests, clustering and PCA, each built small enough to check by hand in NumPy. Half the roadmap is about measuring a model honestly, because a wrong number is worse than no number.

  • Intermediate
  • 4 units, 12 lessons, 152 exercises
  • Python with NumPy
  • Builds on Math for ML

Unit 01 · 3 lessons

Fitting lines

Fit linear and logistic models, and spot one that fits too well

  1. > start01Linear regression
  2. 02Logistic regression
  3. BOSSThe polynomial that fit too well
Unit prize
  1. 01
    Linear regression

    Residuals, least squares and what one outlier does

  2. 02
    Logistic regression

    Squash a score into a probability, then pick a threshold

  3. BOSS
    The polynomial that fit too well

    Ten points, three polynomials and the price of a perfect fit

Read the unit guide

A model is a formula with knobs, and training turns the knobs until the formula's outputs match the data. In this roadmap every snippet is Python with NumPy, and import numpy as np is left out to save space: np is always NumPy.

Linear regression predicts a number as a dot product of features and weights, plus a bias. A residual is target minus prediction, and least squares picks the weights with the smallest sum of squared residuals. For a line that minimum can be solved for exactly (np.linalg.lstsq, with a column of ones for the intercept), and gradient descent arrives at the same place. Squaring means one outlier can swing the whole line.

Logistic regression is for yes/no targets. It keeps the linear score z = w·x + b and squashes it with the sigmoid, 1 / (1 + e^(-z)), into a probability. Its loss is log loss: minus the log of the probability given to the true class, which punishes confident mistakes hardest. The boundary between the classes is where z = 0, a straight line. The threshold that turns a probability into a decision is yours to choose, by what each kind of mistake costs.

A model with enough knobs can fit anything, noise included. Training error only ever falls as a model grows; error on fresh points falls and then climbs. Low training error with high test error is overfitting; both high is underfitting.

Regularisation adds a price on large weights to the loss. L2 (ridge) adds lambda × the sum of squared weights and shrinks them all; L1 (lasso) adds lambda × the sum of absolute weights and drives many to exactly 0. Lambda is tuned on held-out data: too little changes nothing, too much flattens the model into underfitting.

The classic pitfall is judging a model by the data it was fitted on. A second one: weights are only comparable, and new rows only make sense, after the same scaling the training rows got.

Unit 02 · 3 lessons

Neighbours and trees

Classify by nearest neighbours, by a tree of questions, and by a vote of many trees

  1. 01Nearest neighbours
  2. 02Decision trees
  3. BOSSMany weak models
Unit prize
  1. 01
    Nearest neighbours

    Predict by a vote of the closest rows

  2. 02
    Decision trees

    Pick the question that leaves the purest groups

  3. BOSS
    Many weak models

    Build a forest and a boosted model out of small trees

Read the unit guide

Not every model draws a line. (As before, snippets are Python and np is NumPy, already imported.) k-nearest neighbours (kNN) stores the labelled rows and, for a new point, lets the k closest ones vote (or averages their targets, for regression). There is no training, and every prediction measures a distance to every stored row. Small k follows every noisy point; large k blurs everything into the majority. Because it runs on distances, kNN needs scaled features and suffers when there are many irrelevant ones: in high dimensions everything is about equally far from everything.

A decision tree asks yes/no questions about one feature at a time. It scores a group of rows by Gini impurity, 1 minus the sum of squared class shares: 0 for a pure group, 0.5 for an even two-class mix. At each node it tries every feature and threshold and keeps the split with the highest gain: impurity before, minus the size-weighted impurity after. Then it repeats inside each child.

Trees need no scaling and are easy to read, but they are greedy (a split that only pays off together with a second one is invisible to them) and, grown to the end, they memorise the table. Depth limits and a minimum number of rows per leaf hold them back.

Ensembles fix the instability of a single tree by combining many. Bagging trains each tree on a bootstrap sample (rows drawn with replacement; about 63% of rows appear in each) and votes. A random forest also restricts each split to a random handful of features, so the trees disagree more and their vote helps more. Boosting builds small trees in sequence, each fitted to the errors the previous ones left, added with a learning rate; it can overfit if it runs for too many rounds, so it is stopped when validation error stops falling.

The pitfalls: a vote only helps when the voters make different mistakes, and feature importance tells you what the model used, never what causes the outcome.

Unit 03 · 3 lessons

Measuring honestly

Split data, pick metrics and choose a model without fooling yourself

  1. 01Train, validation, test
  2. 02Metrics
  3. BOSSChoose a model
Unit prize
  1. 01
    Train, validation, test

    Hold rows back, and keep them truly unseen

  2. 02
    Metrics

    Confusion matrix, F1, AUC and errors for numbers

  3. BOSS
    Choose a model

    From a baseline to one honest test score

Read the unit guide

Snippets are Python, and np is NumPy, already imported. A score only predicts real use when it is measured on rows the model has never seen. So the rows are shuffled once and cut into three: the training set fits the weights, the validation set compares models and settings, and the test set is touched once, at the end, to report the result. With little data, k-fold cross-validation replaces the single validation set: each fold takes a turn as validation while the rest train, and the scores are averaged.

Leakage is any way that information from held-out rows reaches training. The common routes: fitting a scaler or choosing features on all rows before splitting; near-duplicates (burst photos, several scans of one patient) on both sides of the split; a feature recorded after the outcome it predicts; shuffling time-ordered data so the model trains on the future. The cure is always the same: split first, in the way the model will really be used, and learn everything from the training side only.

A yes/no model's predictions fall into four boxes: true and false positives, true and false negatives. Precision is TP / (TP + FP): when it says yes, is it right? Recall is TP / (TP + FN): of the real positives, how many were found? F1 is their harmonic mean. Accuracy counts all correct rows and looks excellent on imbalanced data even when every positive is missed. AUC ignores the threshold and grades the ranking: the chance that a random positive outscores a random negative.

For numeric targets, MAE averages absolute errors, RMSE punishes large ones, and R² compares the model with always predicting the mean (1 is perfect, 0 is no better than the mean).

Choosing a model: start with a baseline, tune hyperparameters on validation data only, read the validation curve for the point where more flexibility stops helping, refit the winner on all non-test rows and score it once.

The pitfall of this unit is quiet: every decision made by looking at a set of rows fits the model to those rows a little. Reuse the test set to choose, and its number stops being honest.

Unit 04 · 3 lessons

Without labels, and in practice

Find structure without labels, then take a messy table all the way to a score

  1. 01Clustering
  2. 02Fewer dimensions
  3. BOSSA table from the real world
Unit prize
  1. 01
    Clustering

    k-means by hand: assign, move, repeat

  2. 02
    Fewer dimensions

    Keep the directions where the data varies most

  3. BOSS
    A table from the real world

    Gaps, categories, scaling and one honest score

Read the unit guide

Unsupervised learning looks for structure in data that nobody labelled. Clustering groups similar rows; dimensionality reduction describes each row with fewer numbers. (Snippets are Python, and np is NumPy, already imported.)

k-means finds k cluster centres by repeating two steps: assign every point to its nearest centre, then move every centre to the mean of its points. Each step lowers the inertia (the total squared distance from points to their centres), so the loop always settles, but only at a local best that depends on where the centres started. It is run from several random starts, and k is chosen at the elbow where extra clusters stop buying much. It assumes round blobs of similar size and needs scaled features.

PCA finds the directions along which the data varies most. Centre the columns, build the covariance matrix, and take its eigenvectors: those are the principal components, and each eigenvalue is the variance along one. Projecting onto the first few (a dot product per component) keeps most of the spread in far fewer columns. PCA never sees labels, so the direction of most variance is not guaranteed to be the useful one, and without scaling it simply finds the column with the biggest units.

A real table needs preparing before any of this. Missing cells are filled (the median resists outliers), categories become one 0/1 column per value (one-hot), and numeric columns are scaled for models that use distances or penalties. Every one of those steps learns numbers from data, so each is fitted on the training rows and only applied to the test rows.

Which model? Few rows, or a need to explain each prediction: a linear model. A sizeable table of mixed columns with thresholds and interactions: boosted trees, usually the model to beat on tabular data. Images, audio and text: neural networks.

The pitfall is the pipeline, not the model: a median, a scaler or a feature choice computed on all rows before the split quietly inflates the score you report.

Learn Classic Machine Learning on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy