Machine learning: regression and classification
Supervised learning fits a function from examples: given feature vectors and targets , learn with for new . When is a number the problem is regression; when it is a category it is classification. The aim is not to fit the training data, which a flexible enough model can always do, but to generalise: to predict well on data the model has not seen. Every method in this chapter has a knob that trades flexibility against stability (a penalty, a number of neighbours, a depth, a kernel width), and choosing it well matters more than the choice of method.
Background: bias, variance and generalisation
The first central question below, and many entries in this and later chapters, rest on one decomposition of prediction error. Suppose the data obey , where is the true function and the noise has mean zero and variance , independent of everything else. A method turns a random training set into a fitted function , so is itself a random quantity: a different training sample would have produced a different fit. Fix a point and take expectations over both the training sets and the noise in a new observation . Because is independent of , the cross term vanishes:
Now add and subtract the average fit inside the first term. Again the cross term has mean zero, and what is left is
Bias is the systematic error: how far the average fit is from the truth, caused by a model too rigid to represent . Variance is the sensitivity to the particular sample: how much the fit moves from one training set to the next. The noise cannot be reduced by any method. A flexible model has low bias and high variance, a rigid one the reverse, and the best predictor balances the two.
A case that can be solved exactly. Estimate an unknown mean from independent observations of variance , using the shrunken average for a constant . Its expectation is and its variance , so
With , and the plain average () has no bias and variance , for total . Shrinking to introduces a bias of but cuts the variance to , for a total of : adding bias halved the error. Minimising over gives , which here is exactly . The optimum depends on the unknown , which is why the knob has to be tuned on held-out data rather than computed. This is the mechanism behind ridge regression, whose penalty shrinks coefficients towards zero.
A case that shows the trade-off along a knob. The -nearest-neighbour regressor averages the nearest targets. The noise in the average has variance , so variance falls as grows. But the neighbours used lie further and further from , so the average of over them drifts away from and the bias grows. The best lies between (all variance) and (all bias).
The same trade-off appears whenever a method has a smoothing knob:
| Method | Turning the knob towards… | …raises bias | …lowers variance |
|---|---|---|---|
| Ridge, lasso | a larger penalty | yes | yes |
| -nearest neighbours | larger | yes | yes |
| Decision tree | shallower depth, more pruning | yes | yes |
| Boosting, neural network | fewer rounds or earlier stopping | yes | yes |
| Kernel density estimate | a larger bandwidth | yes | yes |
| Welch’s spectrum estimate | shorter segments (more averaged) | yes (coarser resolution) | yes |
Training error always falls as flexibility grows, so it cannot locate the optimum; error on data the model has not seen can. That is the job of cross-validation.
The central questions
- Bias or variance? (See the background section above.) A rigid model misses real structure (bias); a flexible one fits the noise (variance). Penalties, averaging and early stopping control the trade-off, and held-out data measure it.
- What shape can the decision boundary take? Linear models (least squares, logistic regression, linear SVMs) draw hyperplanes; kernels, neighbours and trees draw curved or piecewise boundaries.
- Generative or discriminative? Naive Bayes models how each class generates its features; logistic regression models the class probabilities directly. The first learns faster from little data, the second is more accurate with plenty.
- Are the features on comparable scales? Penalties, distances and kernels all depend on the units of the features, so standardise them first.
Testing the library
Each fitted model was checked against the optimality conditions of its own objective. The gradient of least squares, ridge and logistic regression and the subgradient conditions of the lasso and elastic net vanish to the solver tolerance:
Table 11.1. Optimality conditions of the fitted models.
| model | optimality condition | largest violation |
|---|---|---|
| least squares | (relative to ) | 5.2e-17 |
| ridge, | (relative) | 6.4e-17 |
| lasso, | subgradient: | 9.6e-11 (6 of 8 weights non-zero) |
| elastic net, , | subgradient: | 9.4e-11 (7 of 8 weights non-zero) |
| logistic regression, | gradient of the penalised log-loss | 6.7e-8 (15 L-BFGS iterations) |
Against SciPy
Each model’s objective was reproduced with SciPy 1.17.1’s linear algebra, optimisers and distributions (book/generator/data/make_machine_learning_refs.py), so the references are the same mathematical solutions computed independently:
Table 11.2. Supervised models against SciPy.
| model (SciPy reference) | largest difference |
|---|---|
least squares with intercept (linalg.lstsq) | 1e-14 |
ridge, alpha = 10 (linalg.solve of the centred normal equations) | 5e-16 |
lasso, alpha = 0.2 (optimize.minimize, L-BFGS-B on split weights) | 1e-10 |
elastic net, alpha = 0.2, rho = 0.5 (optimize.minimize, L-BFGS-B on split weights) | 5e-9 |
logistic regression, L2 penalty 0.01: log-odds coefficients (optimize.minimize, BFGS) | 9e-9; probabilities 9e-11 |
Gaussian naive Bayes, posterior probabilities (stats.norm.logpdf) | 4e-16 |
linear discriminant analysis: Fisher ratios and unit directions (linalg.eigh(S_b, S_w)) | ratios 1e-12, directions 2e-13 |
The closed-form fits agree to rounding. The lasso, elastic net and logistic regression are solved iteratively on both sides, and agree to the stopping tolerances of the optimisers.
Comparing classifiers
Table 11.3. Test accuracy of the classifiers on three data sets.
| classifier | three Gaussian classes, 4D | moons | circles | fit time (moons) |
|---|---|---|---|---|
| logistic regression | 0.910 | 0.870 | 0.407 | 88 µs |
| Gaussian naive Bayes | 0.907 | 0.883 | 0.997 | 2 µs |
| k-nearest neighbours, k = 15 | 0.907 | 0.950 | 0.997 | 1 µs |
| decision tree, depth 6 | 0.827 | 0.937 | 0.983 | 69 µs |
| random forest, 100 trees | 0.900 | 0.937 | 0.987 | 6.3 ms |
| SVM, RBF kernel γ = 1, C = 1 | 0.893 | 0.950 | 1.000 | 272 µs |
Test accuracy with half of each data set for training (standardised features); the fit time is for 300 points in 2D.
No method wins everywhere. Linear logistic regression fails on the concentric circles, where Gaussian naive Bayes succeeds only because the two rings have different spreads; neighbours, forests and kernel machines adapt to curved boundaries; a single tree is the least accurate on the smooth Gaussian problem.
In the library
The crate is lib_jsl_machine_learning (API reference). Feature matrices are
ndarray arrays with one sample per row; models implement Regressor or Classifier.
| You need | Use | Entry |
|---|---|---|
| Train/test splits, scaling, metrics, synthetic data | preprocessing, metrics, datasets | Foundations |
| A linear fit, possibly penalised or weighted | LinearRegression, Ridge, ElasticNet, GeneralLeastSquares | Linear regression |
| Class probabilities from a linear model | LogisticRegression | Logistic regression |
| A fast probabilistic classifier, text classification | GaussianNaiveBayes, MultinomialNaiveBayes | Naive Bayes |
| A classifier with no training | KNearestNeighbors | Nearest neighbours |
| Interpretable rules, or a strong default | DecisionTree, RandomForest | Decision trees and random forests |
| Nonlinear boundaries or robust regression with kernels | SupportVectorMachine, SupportVectorRegression, Kernel | Support vector machines |