Foundations: models, data, preprocessing and metrics
| Problem | Provide the common interface of the learning algorithms, reproducible data to try them on, feature scaling and splitting, and measures of how well a model predicts |
| Devised by | Mervyn Stone (1974) and Seymour Geisser (1975), held-out validation; Karl Pearson (1904), contingency tables; Cornelis van Rijsbergen (1979), the F-measure; Lawrence Hubert and Phipps Arabie (1985), the adjusted Rand index; Peter Rousseeuw (1987), silhouettes |
| Accuracy | Exact |
| Cost | Linear in the size of the data |
| Read first | Preliminaries: probability, Background: bias and variance |
| API | common (Regressor, Classifier, Clusterer, Transformer, MlRng), datasets, preprocessing (StandardScaler, MinMaxScaler, train_test_split, polynomial_features), metrics |
Overview
Every model in the crate follows the same pattern: create it with its settings, fit it to training data, and predict on
new data. Four traits express this: a Regressor maps rows to numbers, a Classifier maps rows to labels , a
Clusterer groups rows without labels, and a Transformer learns a mapping of the rows (a scaling, a projection). Data
are ndarray matrices with one sample per row. Around the models sit the tools of a sound workflow: synthetic data sets,
scaling, splitting into training and test sets, and metrics.
Where it is used
Before any algorithm is applied, data must be prepared and a measure of success chosen.
- Feature scaling. Standardising sensor readings with very different units so that distance-based methods and regularised models treat them fairly.
- Metrics. Accuracy, precision, recall and the confusion matrix for classifiers (a medical test, a fault detector), and error measures for regression.
- Reproducible experiments. Splitting data into training and test sets and generating synthetic data sets so that results can be repeated.
History
The idea of judging a prediction method on data held out from fitting goes back at least to the psychometricians of the 1930s; Mervyn Stone (1974) and Seymour Geisser (1975) formalised cross-validation. The confusion matrix descends from Karl Pearson’s contingency tables (1904); precision and recall come from information retrieval, where Cornelis van Rijsbergen (1979) combined them into the F-measure. For clusterings, Lawrence Hubert and Phipps Arabie (1985) corrected William Rand’s agreement index (1971) for chance, and Peter Rousseeuw (1987) introduced silhouettes. Synthetic benchmarks such as the “moons” and “circles” were popularised by scikit-learn (2011).
The idea
The model traits
/// A model mapping feature rows to real-valued predictions.
pub trait Regressor {
fn fit(&mut self, x: VR2D, y: VR1D) -> Result<(), ErrorsJSL>;
fn predict(&self, x: VR2D) -> Result<R1D, ErrorsJSL>;
}
/// A model mapping feature rows to class labels `0..classes`.
pub trait Classifier {
fn fit(&mut self, x: VR2D, labels: &[usize]) -> Result<(), ErrorsJSL>;
fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL>;
}
/// A model that groups rows without labels. Noise points (density-based methods) get `None`.
pub trait Clusterer {
fn fit_predict(&mut self, x: VR2D) -> Result<Vec<Option<usize>>, ErrorsJSL>;
}
/// A learned transformation of feature rows (scaling, projection, embedding).
pub trait Transformer {
fn fit(&mut self, x: VR2D) -> Result<(), ErrorsJSL>;
fn transform(&self, x: VR2D) -> Result<R2D, ErrorsJSL>;
fn fit_transform(&mut self, x: VR2D) -> Result<R2D, ErrorsJSL> {
self.fit(x)?;
self.transform(x)
}
}
Because the traits are object-safe, models can be stored as Box<dyn Classifier> and compared in a loop, as the
comparison table does.
Training and test data
A model’s error on its own training data is optimistic, often wildly so: a 1-nearest-neighbour classifier or a fully grown
tree has zero training error. train_test_split shuffles the sample indices and holds out a fraction for testing, and
select_rows and select_labels gather the pieces. Any step that learns from data, including scaling, must be fitted on the
training part only, or information leaks from the test set. Cross-validation, which averages over several splits, is covered with model selection in a
later chapter.
Scaling
Penalties, distances and kernels treat all features alike, so a feature measured in millimetres dominates one measured in
metres. StandardScaler subtracts each column’s mean and divides by its standard deviation (constant columns are only
centred); MinMaxScaler maps each column onto . Trees and naive Bayes do not need scaling; nearly everything else does.
polynomial_features expands one column into , turning linear regression into polynomial regression.
Synthetic data sets
Every generator takes a seed: make_blobs (Gaussian clusters), make_moons and make_circles (two classes with curved
boundaries), make_classification (three overlapping, correlated classes in four dimensions), make_regression (a linear
model with noise, returning the true weights), make_sine and make_swiss_roll (a manifold for
dimensionality reduction).
Metrics
For regression, the mean squared error, its root, the mean absolute error and the coefficient of determination , the fraction of variance explained (negative for a model worse than the mean). For classification, accuracy is the fraction correct; the confusion matrix counts true class predicted as ; and per class, precision (of the points predicted as , the fraction that are ), recall (of the points in , the fraction found) and their harmonic mean F1. For a random forest on the three-class problem:
Table 11.4. A confusion matrix.
| true class | predicted 0 | predicted 1 | predicted 2 | precision | recall | F1 |
|---|---|---|---|---|---|---|
| 0 | 86 | 14 | 5 | 0.896 | 0.819 | 0.856 |
| 1 | 5 | 80 | 0 | 0.842 | 0.941 | 0.889 |
| 2 | 5 | 1 | 104 | 0.954 | 0.945 | 0.950 |
Class 0, in the middle, is confused with both others. For clusterings, the silhouette compares each point’s mean distance to its own cluster with that to the nearest other cluster, and the adjusted Rand index compares two labellings, scoring 1 for identical partitions and about 0 for chance agreement.
Algorithm
train_test_split, with a test fraction and a seed:
- list the indices and shuffle them by the Fisher-Yates method, driven by a generator seeded from the seed: for from down to 1, swap position with a position chosen uniformly from ;
- take the last shuffled indices as the test set (at least one, and leaving at least one for training), and the rest as the training set;
- return the two lists of indices, from which
select_rowsandselect_labelsgather the data.
StandardScaler:
- fit: compute the mean and the population standard deviation of each column of the training data;
- transform: from each value subtract its column’s mean and divide by its column’s standard deviation; a column with zero standard deviation is only centred.
The same fitted means and standard deviations are applied to the test data. Fitting the scaler again on the test data would use information from it.
A classification metric from a confusion matrix: count , the number of points of true class predicted as . The accuracy is the sum of the diagonal divided by . For class , the precision is divided by the sum of column , the recall is divided by the sum of row , and F1 is their harmonic mean.
Implementation
MlRngwraps the xoshiro256++ generator of the random numbers chapter, with uniform, normal, shuffle and sampling helpers; every stochastic algorithm takes a seed.- Models return
Misconfigurationerrors when used before fitting andIncompatibleArraySizesfor mismatched inputs.
In practice
//! The workflow shared by every model: split, scale, fit, predict, score.
use lib_jsl_machine_learning::common::{Classifier, Transformer};
use lib_jsl_machine_learning::datasets::make_classification;
use lib_jsl_machine_learning::metrics::{accuracy, confusion_matrix, precision_recall_f1};
use lib_jsl_machine_learning::preprocessing::{StandardScaler, select_labels, select_rows, train_test_split};
use lib_jsl_machine_learning::supervised::classification::LogisticRegression;
fn main() {
let (x, labels) = make_classification(150, 1);
let (train, test) = train_test_split(x.nrows(), 0.3, 7).unwrap();
// Fit the scaler on the training rows only, then apply it to both sets.
let mut scaler = StandardScaler::new();
let x_train = scaler.fit_transform(select_rows(x.view(), &train).view()).unwrap();
let x_test = scaler.transform(select_rows(x.view(), &test).view()).unwrap();
let (y_train, y_test) = (select_labels(&labels, &train), select_labels(&labels, &test));
let mut model = LogisticRegression::new(1e-3);
model.fit(x_train.view(), &y_train).unwrap();
let predicted = model.predict(x_test.view()).unwrap();
println!("test accuracy {:.3} on {} points", accuracy(&y_test, &predicted).unwrap(), y_test.len());
for (c, row) in confusion_matrix(&y_test, &predicted, 3).unwrap().iter().enumerate() {
let (p, r, f1) = precision_recall_f1(&y_test, &predicted, 3).unwrap()[c];
println!("class {c}: {row:?} precision {p:.2} recall {r:.2} F1 {f1:.2}");
}
}
test accuracy 0.904 on 135 points
class 0: [34, 6, 1] precision 0.85 recall 0.83 F1 0.84
class 1: [4, 41, 0] precision 0.87 recall 0.91 F1 0.89
class 2: [2, 0, 47] precision 0.98 recall 0.96 F1 0.97
Strengths
- One interface for all models; reproducible data and splits.
Weaknesses
- Dense
f64matrices only: no sparse data, categorical encoding or missing-value handling. - No probability-based metrics (log-loss, ROC curves); compute them from
predict_proba.
Exercises
- Show that fitting a
StandardScaleron all the data before splitting leaks information, by constructing an example where it changes the test accuracy. - For a binary problem with 1% positives, what accuracy does always predicting “negative” achieve? What are its precision and recall?
- Show that F1 is the harmonic mean of precision and recall and lies between their minimum and their arithmetic mean.
- Compute the adjusted Rand index of two random labellings of 1000 points into 3 groups, over many trials.
Hints and answers
- Construct data in which the feature mean is very different in the test portion (for instance a drifting feature). Scaling with statistics from all the data moves the test points toward the training distribution, changing the test accuracy from what an unseen test set would give.
- Accuracy , recall , and precision is (undefined; conventionally 0), so F1 is also 0: accuracy is misleading on imbalanced data.
- is the harmonic mean. For , .
- The adjusted Rand index of independent random labellings has mean and standard deviation of order for 1000 points; values near zero (and sometimes slightly negative) are what the adjustment is for.
Further reading
- T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009 (free online).
- G. James, D. Witten, T. Hastie and R. Tibshirani, An Introduction to Statistical Learning, 2nd ed., Springer, 2021.
- F. Pedregosa et al., “Scikit-learn: machine learning in Python”, Journal of Machine Learning Research 12 (2011) 2825–2830.