Machine learning from scratch

Features, labels, logistic regression, overfitting, and how to measure a classifier

Epigenetics

About this lecture

Many recent papers in epigenomics train a model to predict something: is this region open, is this site bound, how old is this blood sample. This unit teaches the ideas behind all of them, from scratch, with one running example: can we tell open from closed chromatin in GM12878 from the DNA sequence alone?

  • Supervised learning: examples, features, labels, and a model with parameters.
  • Logistic regression: the linear model you know, for a yes/no outcome; fitting it by walking downhill on a loss.
  • Overfitting, held-out data, regularisation and cross-validation.
  • Measuring a classifier: confusion matrix, precision and recall, ROC and PR curves, class imbalance, baselines.

Learning from examples

  • Supervised learning: we have examples with known answers (labels), turn each example into numbers (features), and choose a model’s parameters so that it reproduces the labels.
  • Then we use the model on examples it has never seen, and check its answers against the truth.
  • Different words for things you know: features = covariates / predictors; labels = response; fitting = estimation.

The running example: open or closed?

  • Label 1 (open): 500 bp around the summit of a GM12878 ATAC-seq peak. Label 0 (closed): random 500-bp windows at least 500 bp from any peak.
  • 20 000 of each, on chr1–22, blacklist and runs of N removed.
  • The question: how much of “open in a B cell line” can be read from the sequence of the window alone?

Features: turning a window into numbers

  • One row per example, one column per feature, plus the label: the same layout as a design matrix.
  • Here 5 hand-made features: GC, CpG o/e (CpG islands are open at promoters), and motif counts for CTCF, PU.1 (SPI1) and EBF1, TFs that open chromatin in B cells.
  • Choosing features is where biology enters the model. (A CNN learns its own: How a CNN reads DNA.)

Look at the data first

  • Open windows are GC-richer (mean 0.50 vs 0.41) and more CpG-rich (0.34 vs 0.20).
  • 26% of open windows contain a CTCF match, against 5% of closed ones; PU.1 28% vs 16%, EBF1 12% vs 5%.
  • Every feature separates the classes a little, none cleanly: the distributions overlap.

Why not a straight line?

  • A linear model open ~ gc predicts values below 0 and above 1: not probabilities.
  • The fraction open (circles) rises in an S-shape with GC. The logistic curve has that shape and stays between 0 and 1.

Logistic regression: a linear model for yes/no

\text{score} = b_0 + b_1 x_1 + \dots + b_p x_p, \qquad P(\text{open}) = \frac{1}{1 + e^{-\text{score}}}

  • The score is linear in the features, exactly like lm. The logistic function squeezes it into (0, 1).
  • The score is the log-odds; e^{b} is an odds ratio. In R: glm(open ~ gc + ..., family = binomial).

Two features: a straight decision boundary

  • With two features, the points with equal predicted probability lie on straight lines. The P = 0.5 line is the decision boundary.
  • Here the lines are steep: the model leans mostly on GC; once GC is known, CpG o/e adds little.
  • A linear model can only draw straight boundaries; more flexible models (and neural networks) can bend them.

How wrong is a prediction? The loss

  • For each window, log-loss = -\log p if it is open, -\log(1-p) if it is closed, where p is the predicted P(open).
  • Confident and right: near 0. Confident and wrong: large. The model’s loss is the mean over the training windows.
  • Minimising log-loss = maximising the likelihood: what glm does.

Fitting = walking downhill

  • Colours: the mean log-loss for every pair of parameters (b_0, b_1) of the GC model. The best pair is at the bottom of the valley.
  • Gradient descent: start anywhere, compute the slope of the loss, take a small step downhill, repeat. The red path is 2000 such steps.
  • It ends where glm ends (−4.57, 10.28). Neural networks are fitted the same way, with millions of parameters.

In R

test  <- dat$chrom %in% c("chr8", "chr9")        # hold out two whole chromosomes
train <- dat[!test, ]; tst <- dat[test, ]

m <- glm(open ~ gc + cpg_oe + ctcf + spi1 + ebf1, family = binomial, data = train)
round(summary(m)$coefficients, 2)
#             Estimate Std. Error z value Pr(>|z|)
# (Intercept)    -4.20       0.07  -62.11        0
# gc              8.04       0.17   47.60        0
# cpg_oe          0.97       0.08   12.74        0
# ctcf            1.41       0.04   36.62        0
# spi1            0.60       0.02   26.18        0
# ebf1            0.24       0.03    8.06        0

p <- predict(m, newdata = tst, type = "response")  # P(open) for unseen windows
  • Fit on training chromosomes, predict on test chromosomes (36 317 and 3683 windows).

A model can fit the training data too well

  • Features: counts of every k-mer (k = 1…4: 4 to 256 features). With 500 training windows, 256 features fit the training data perfectly (AUC 1.00) but do worst on the test chromosomes (0.62).
  • With 5000 windows the same 256 features generalise (test 0.82). Overfitting = many parameters relative to data.

Three sets, three jobs

  • Training fits the parameters; validation (or cross-validation) chooses between models and settings; test is used once, at the end.
  • In genomics, split by chromosome, so that neighbouring and overlapping windows cannot sit on both sides.

Regularisation: penalise large coefficients

  • Minimise loss + λ × penalty. L2 (ridge): penalty \sum b_j^2, all coefficients shrink. L1 (lasso): \sum |b_j|, many become exactly 0: feature selection.
  • Elastic net mixes both. λ is a hyperparameter: not fitted from the training loss, chosen on held-out data.

Cross-validation

  • Split the training data into k folds; fit on k − 1, evaluate on the held-out fold; rotate; average.
  • Every training window is used for evaluation once, and the test set is never touched.
  • In genomics, make folds from groups of chromosomes, for the same reason as the test split.

Choosing λ by cross-validation

  • Blue: cross-validated AUC on the 500 training windows, for each λ of the lasso. Red: AUC on the test chromosomes, shown only for illustration.
  • Strong penalty: too simple. Weak penalty: overfits. The CV curve finds the useful middle, and tracks the test curve.

From probabilities to calls

  • A model gives a score or probability. A threshold turns it into calls, and the calls into a confusion matrix.
  • GC model, threshold 0.5, test chromosomes: TP 936, FN 756, FP 550, TN 1441: accuracy 0.65, precision 0.63, recall 0.55.

The threshold is a choice

  • Predicted P(open) from all five features, for open and closed test windows. The two distributions overlap.
  • A low threshold finds more open regions (higher TPR) but calls more closed ones open (higher FPR); a high threshold the reverse.

The ROC curve, by hand

  • Sort by score; walk down the list. Each open window moves the curve up (one more TP), each closed window right (one more FP).
  • AUC (area under the ROC curve) = the probability that a random open window scores higher than a random closed one: here 21 of the 25 (open, closed) pairs are ordered correctly.

ROC curves on real data

  • GC alone: 0.71. Three motif counts: 0.67. All five features: 0.76. Lasso on 256 4-mers: 0.83; plus the five features: 0.86. Coin flip: 0.51.
  • The ROC curve does not depend on a threshold or on how many open vs closed windows there are.

Precision–recall curves

  • Precision against recall over all thresholds. A random model sits at the fraction of positives (0.46 here), not at 0.5.
  • PR AUC (average precision) answers: when the model calls something open, how often is it right?

Class imbalance

  • In the genome, open regions are a few per cent, not half. Keep all closed test windows and only 10% of open ones (8% open): ROC AUC barely moves (0.86 → 0.87); PR AUC falls from 0.83 to 0.41.
  • Always predicting “closed” now has 92% accuracy. Accuracy is useless when classes are imbalanced.

Always compare with a baseline

  • A number like “AUC 0.86” means nothing alone. Compare with: a coin flip (0.5), the majority class, and the simplest sensible model (here GC alone: 0.71).
  • The question is never “is the AUC high?” but “how much does the model add over the simple explanation?”

What do the coefficients say about biology?

  • Odds ratios from the five-feature model: each CTCF match ×4.1 odds of being open, PU.1 ×1.8, EBF1 ×1.3, +0.1 GC ×2.2.
  • These are associations given the other features, not causal effects: a coefficient changes when correlated features are added or removed.

Summary

idea key fact
supervised learning examples with labels → features → model parameters fitted to reproduce labels
logistic regression linear score = log-odds; P = 1/(1+e^{-\text{score}}); e^b is an odds ratio
loss, fitting log-loss = −log likelihood; gradient descent walks downhill; glm finds the same minimum
overfitting many parameters, few examples: perfect on training, poor on new data
train / validation / test fit / choose / report once; split by chromosome in genomics
regularisation L2 shrinks, L1 selects (elastic net: both); λ chosen by cross-validation
confusion matrix precision = TP/(TP+FP), recall = TPR = TP/P, FPR = FP/N
ROC AUC P(random positive outranks random negative); 0.5 = chance; insensitive to class balance
PR AUC baseline = fraction of positives; drops with imbalance; closer to real genome-wide use
baselines always report the simple model (coin flip, GC, motif) next to the fancy one

Key papers (optional further reading)

Not required reading and not examined. For those who want the primary literature.