Model Selection and Validation - Hold-Out, k-Fold and Statistical Tests
In questa pagina 7
The question of the last lectures: given two models (for instance KNN with and KNN with , see Nearest NeighbourK-nearest neighbours (KNN) has an almost empty training phase (the data are just stored) and does all the work at test time: given a point, compute its distance from all training points, sort the distances, keep the K shortest and predict the (weighted) majority class among them. The course source has one handwritten page on it; the notebooks use it as one of six scikit-learn classifiers, and the model-comparison example contrasts KNN with K=1 and K=5.Nearest Neighbour →), who is the best model? The scores come from the metrics of Classification Metrics - Confusion Matrix, Precision, Recall and F1The performance of a classifier is read from the confusion matrix, whose rows are the actual classes and columns the predicted ones: TP, FN / FP, TN for a binary problem. Accuracy = (TP + TN) / total; recall = TP / (TP + FN); precision = TP / (TP + FP); F1 = 2 recall precision / (recall + precision). With an unbalanced data set accuracy can look good while recall is poor (10 positive and 90 negative objects: accuracy 0.87, recall 0.10, precision 0.20). In multi-class problems the confusion matrix is square and recall and precision are computed class by class from the diagonal.Classification Metrics - Confusion Matrix, Precision, Recall and F1 →; the code is in Python Notebooks - scikit-learn Model Comparison and Wilcoxon TestTwo example notebooks compare six scikit-learn classifiers (logistic regression, perceptron, KNN, decision tree, SVC, random forest) on a real data set loaded from the UCI repository: hold-out split with train_test_split, F1 score, k-fold cross-validation with cross_validate and scoring f1_macro, box plots of the fold scores, and the Wilcoxon signed-rank test (scipy.stats.wilcoxon) on the paired fold scores; the second notebook adds a stratified test set, more folds on the best models and the final training and test of the chosen model. A separate short notebook draws two normal samples to see how often the Wilcoxon test rejects at the 0.05 level.Python Notebooks - scikit-learn Model Comparison and Wilcoxon Test →. The motivation (error on the samples is not the error on new data) is in The Statistical Learning Framework and Empirical Risk MinimizationA hypothesis is judged by an error function computed pointwise on the data and averaged: the in-sample (empirical) error E_in(h) = (1/N) sum of e(f(x_i), h(x_i)); with squared differences it is the sum of squared errors. The learning algorithms of the course all search the hypothesis set for the h with small in-sample error, but what matters is the error on new inputs drawn from the same input distribution, so the data must cover the regions where the inputs live, and part of the data must be held back to check the result.The Statistical Learning Framework and Empirical Risk Minimization →.
Source note. The pages below are the handwritten notes of the final lectures. Confidence intervals and maximum-likelihood estimation of a general parameter are in the official program but are not developed here (the Bernoulli example is in Bernoulli Distribution and Maximum Likelihood EstimationA binary outcome (heads = 1, tails = 0) is modelled by a Bernoulli distribution with parameter theta: P(x | theta) = theta^x (1 - theta)^(1 - x). For independent identically distributed observations the likelihood is the product of the single probabilities; with K heads in n tosses it is L(theta) = theta^K (1 - theta)^(n - K). Maximising the log-likelihood l(theta) = K log theta + (n - K) log(1 - theta) (maximum likelihood estimation) gives theta = K / n.Bernoulli Distribution and Maximum Likelihood Estimation →).
1. Parameters, hyper-parameters, training and test
Two models are defined by choosing their hyper-parameters (for KNN, the value of ). Each model is then trained on the training set: the training fixes the optimisation parameters (the vector , or ). The trained models are then evaluated on a test set, which gives a performance for each. Which is the best model?
2. Hold-out
The data set is split in two parts:
dataset D
+------------------+--------+
| Train | Test |
+------------------+--------+This is the hold-out approach. The split is arbitrary, so the score depends on which objects happened to land in the test part.
Repeat the hold-out times. Each repetition uses a different split (the page draws three: test part at the end, in the middle, near the end) and gives a performance :
run 1: [ Train .............. | Test ] -> performance k1
run 2: [ Train | Test | Train ........ ] -> performance k2
run 3: [ Train .............. | Te | Tr ] -> performance k3Running both models on the same splits gives paired scores: "Perf " of Model 1 is paired with "Perf " of Model 2, and so on. In the notation of the earlier example: experiment uses (Train, Test), experiment uses (Train, Test), ... and both models use the same training/test split in each experiment.
3. Comparing two models on paired scores
The first sketch places on an axis from to the -scores of the three experiments:
| experiment | Model 1 (KNN, ) | Model 2 (KNN, ) | difference Model 1 minus Model 2 |
|---|---|---|---|
| 0.75 | 0.78 | (computed here) | |
| 0.90 | 0.89 | (computed here) | |
| 0.65 | 0.68 | (computed here) |
(The numbers are read from the handwritten axis; the reading of the labels on the second axis is slightly uncertain.) The pairing is drawn as dotted lines joining the same experiment on the two axes ("pairing, paired test"). What matters is then the list of differences (written , , ...), which are plotted around the value .
If the models were equivalent, the differences would be spread around in a bell shape: a bump with crosses on both sides, the left side meaning , the right side . If the observed differences fall far on one side, in the tail of that distribution, equivalence becomes hard to believe.
4. Significance, and the p-value
The tails of the distribution of the differences are marked with two areas (left) and (right). The notes show the same bell curve with
- of the total distribution;
- a wider rejection region, ;
- a narrower one, (the tails are almost invisible).
This total tail area is the -value (the significance level). It is decided before the experiment. After the experiments, the differences obtained ( placed on the axis) are compared with these regions, and the p-value is defined on the page as the probability of observing the specific sequence of differences in the experiments. In the notebook (see below) the rule applied to the p-value is: if it is greater than the two samples are "probably the same distribution", otherwise "probably different distributions". Reading as the probability of a false alarm when the two models are equal follows from the tail-area picture (my remark): with , in about 5 comparisons out of 100 between two equivalent models a "significant" difference will appear by chance.
5. The test: null hypothesis, parametric and non-parametric
- Hypothesis (null, , the initial one): the two models perform equally. The test asks whether the data are compatible with it.
- Parametric tests: the page names the t-test; the sketch draws two bell curves (assumed shape) with samples under them. It assumes a distribution for the scores.
- Non-parametric tests: the Wilcoxon test, which does not assume a distribution.
Wilcoxon on the paired example. Scores of Model 1 on and of Model 2 on the same folds: the page lists the pairs and the differences
Next the absolute values are put in decreasing order and each is labelled with the model that was better in that run (the positive difference means Model 1, the negative one Model 2):
0.8 -> M1
0.3 -> M2
0.2 -> M1The drawing then stacks the ordered differences into two columns, one for and one for . The notes stop here: the exact statistic computed from the two columns is not written in the course source, and it is not reproduced from memory. In practice it is obtained with scipy.stats.wilcoxon(scores_1, scores_2) (see the notebooks), which returns the statistic and the p-value.
6. Cross-validation (k-fold)
Instead of repeating random hold-outs, the data set is divided once into folds. In the page's example :
split 1: fold1 fold2 fold3 Train = fold1 + fold2 Test = fold3
split 2: fold1 fold2 fold3 Train = fold1 + fold3 Test = fold2
split 3: fold1 fold2 fold3 Train = fold2 + fold3 Test = fold1Each fold plays the role of the test set exactly once, and the other folds are the training set; one performance is collected per fold. Usual values written in the notes: and .
Pipeline (the handwritten box):
- create the k-fold cross-validation data set;
- set the hyper-parameters, which defines the model (and repeat for each model or hyper-parameter value to compare);
- collect the performance measures for each fold (and repeat for each model);
- compare the models with the paired statistical test of section 5.
The numbers "1, 2, 3" on the page mark the steps and the loops "Repeat" in a way that the handwriting leaves a little ambiguous; the above is the reading that matches the notebook.
7. The procedure in the final notebook
- hold out a test set (20% of the data, stratified) that is not touched until the end;
- on the training set only, run k-fold cross-validation (3 folds, then 5 on the best models) for six models, scoring with macro ;
- compare the best models with the Wilcoxon test; the notebook says "stop here and decide the value" before reading the p-value;
- choose the best model, train it on the whole training set and evaluate it once on the test set.
The notebook also remarks that if the best model (random forest) is too expensive, a cheaper one (KNN) can be used instead.
Versione ripasso
Model Selection and Validation - Hold-Out, k-Fold and Statistical Tests
- Models differ by hyper-parameters (e.g. in KNN); training fixes the parameters (, ); performance (e.g. ) is measured on a separate test set. Question: who is the best model?
- Hold-out: split into Train | Test; fragile, so repeat times with different splits. Both models use the same splits: paired scores.
- Paired differences are compared with ; if the models were equivalent they would spread around in a bell shape.
- Null hypothesis : the two models perform equally. is the total tail area (, , in the notes), fixed before the experiment. p-value = probability of observing the obtained differences; notebook rule: means probably the same distribution.
- Parametric test: t-test (assumes a distribution). Non-parametric: Wilcoxon (no distribution assumed).
- Wilcoxon: differences , , ; sort the absolute values in decreasing order and label each with the better model (, , ). Statistic and p-value:
scipy.stats.wilcoxon; the exact statistic is not in the source. - k-fold cross-validation: divide the data once into folds; each fold is the test set once; one performance per fold. Usual or .
- Pipeline: 1) create the k-fold data set; 2) set the hyper-parameters (per model); 3) collect the performance of each fold; 4) compare with the paired test.
- Last notebook: stratified test set (20%) kept aside; 3-fold, then 5-fold on the best models, macro , six models; Wilcoxon; retrain the chosen model on the whole training set; evaluate once on the test set. Code: Python Notebooks - scikit-learn Model Comparison and Wilcoxon TestTwo example notebooks compare six scikit-learn classifiers (logistic regression, perceptron, KNN, decision tree, SVC, random forest) on a real data set loaded from the UCI repository: hold-out split with train_test_split, F1 score, k-fold cross-validation with cross_validate and scoring f1_macro, box plots of the fold scores, and the Wilcoxon signed-rank test (scipy.stats.wilcoxon) on the paired fold scores; the second notebook adds a stratified test set, more folds on the best models and the final training and test of the chosen model. A separate short notebook draws two normal samples to see how often the Wilcoxon test rejects at the 0.05 level.Python Notebooks - scikit-learn Model Comparison and Wilcoxon Test →.
- Metrics: Classification Metrics - Confusion Matrix, Precision, Recall and F1The performance of a classifier is read from the confusion matrix, whose rows are the actual classes and columns the predicted ones: TP, FN / FP, TN for a binary problem. Accuracy = (TP + TN) / total; recall = TP / (TP + FN); precision = TP / (TP + FP); F1 = 2 recall precision / (recall + precision). With an unbalanced data set accuracy can look good while recall is poor (10 positive and 90 negative objects: accuracy 0.87, recall 0.10, precision 0.20). In multi-class problems the confusion matrix is square and recall and precision are computed class by class from the diagonal.Classification Metrics - Confusion Matrix, Precision, Recall and F1 →; why held-out data: The Statistical Learning Framework and Empirical Risk MinimizationA hypothesis is judged by an error function computed pointwise on the data and averaged: the in-sample (empirical) error E_in(h) = (1/N) sum of e(f(x_i), h(x_i)); with squared differences it is the sum of squared errors. The learning algorithms of the course all search the hypothesis set for the h with small in-sample error, but what matters is the error on new inputs drawn from the same input distribution, so the data must cover the regions where the inputs live, and part of the data must be held back to check the result.The Statistical Learning Framework and Empirical Risk Minimization →; KNN example: Nearest NeighbourK-nearest neighbours (KNN) has an almost empty training phase (the data are just stored) and does all the work at test time: given a point, compute its distance from all training points, sort the distances, keep the K shortest and predict the (weighted) majority class among them. The course source has one handwritten page on it; the notebooks use it as one of six scikit-learn classifiers, and the model-comparison example contrasts KNN with K=1 and K=5.Nearest Neighbour →.
- Typical errors: different splits for the two models (not paired); choosing after seeing the p-value; selecting the model on the test set.
Teoria collegata
- Classification Metrics - Confusion Matrix, Precision, Recall and F1
- Introduction to Machine Learning - Program Map
- Nearest Neighbour
- PAC Learning and Hoeffding's Inequality
- Python Notebooks - scikit-learn Model Comparison and Wilcoxon Test
- The Statistical Learning Framework and Empirical Risk Minimization