Salta al contenuto
Note per Studenti Classification Metrics - Confusion Matrix, Precision, Recall and F1 Report

Classification Metrics - Confusion Matrix, Precision, Recall and F1

In questa pagina 4

How to judge the classifiers of Halfspaces and the Perceptron AlgorithmA perceptron computes h(x) = sign(w^T x) where x includes a constant coordinate x0 = 1 that absorbs the threshold into the bias weight w0; its decision boundary is the hyperplane w^T x = 0 (a line in the plane, x2 = -(w1/w2) x1 - w0/w2). The Perceptron Learning Algorithm scans the data and, on every misclassified point, replaces w by w + y x. A single perceptron cannot separate the exclusive-or pattern; two perceptrons feeding a third give a multilayer network.Halfspaces and the Perceptron Algorithm →, Logistic RegressionLogistic regression models the probability p of the positive class: the logit (log of the odds p/(1-p)) is assumed linear in the input, logit(p) = w^T x = z. Inverting it gives p = 1/(1 + e^(-z)), the logistic sigmoid; an object goes to class 1 when the sigmoid exceeds 0.5, i.e. when z > 0. The parameters are learned by maximising the Bernoulli log-likelihood, equivalently minimising the cost J = -y log(yhat) - (1 - y) log(1 - yhat), by gradient descent with gradient (1/m) X^T (h(x) - y).Logistic Regression → and 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 →. The notebooks compute the F1 score of six models on held-out data and in cross-validation (see 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 comparison of two models is in Model Selection and Validation - Hold-Out, k-Fold and Statistical TestsTo decide which of two models is better, fix their hyper-parameters, train each on a training set (this fits the parameters, the vector w or theta) and measure a performance score such as F1 on a separate test set; one split is too fragile, so the hold-out is repeated K times (or K-fold cross-validation is used) and the paired scores of the two models are compared with a statistical test. The null hypothesis H0 is that the two models perform equally; the significance level alpha is fixed before the experiment, and the p-value is the probability of observing the obtained differences under H0. Parametric test: t-test; non-parametric: Wilcoxon.Model Selection and Validation - Hold-Out, k-Fold and Statistical Tests →.

1. Target, hypothesis, actual and predicted output

The target function f(x)f(\mathbf{x}) gives the actual output (the "true output"); the hypothesis h(x)h(\mathbf{x}) gives the predicted output. Evaluating a classifier means comparing the two on the same objects: the vector y\mathbf{y} of the actual outputs against the vector y^\hat{\mathbf{y}} of the predictions. The classification can be binary or multi-class, and, as another distinction written in the notes, single-label or multi-label (the notes name this distinction; the material that follows is single-label).

2. Binary classification: the confusion matrix

Classes: positive and negative. Rows are the actual class, columns the predicted class:

                    predicted
                 Positive    Negative
  actual
  Positive         TP           FN
  Negative         FP           TN
  • TP (true positive): actual positive, predicted positive.
  • FN (false negative): actual positive, predicted negative.
  • FP (false positive): actual negative, predicted positive.
  • TN (true negative): actual negative, predicted negative.

The page builds it from two label vectors, entry by entry: y=1,y^=1y=1,\hat y=1 is a TP; y=0,y^=0y=0,\hat y=0 a TN; y=0,y^=1y=0,\hat y=1 an FP; y=1,y^=0y=1,\hat y=0 an FN.

3. Accuracy, recall, precision, F1

Accuracy=TP+TNTP+TN+FP+FN,Recall=TPTP+FN,Precision=TPTP+FP,\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN},\qquad \text{Recall}=\frac{TP}{TP+FN},\qquad \text{Precision}=\frac{TP}{TP+FP},

F1=2⋅Recall⋅PrecisionRecall+Precision.F_1=\frac{2\cdot\text{Recall}\cdot\text{Precision}}{\text{Recall}+\text{Precision}}.

(Accuracy is the share of correctly classified objects over all objects; on the page the terms TNTN in the numerator and TNTN, FNFN in the denominator are circled.) Recall asks: of all the actual positives, how many did we find? Precision asks: of all objects we called positive, how many are really positive?

Worked example of the lecture

A data set has 10 positive and 90 negative objects (100 in total).

Classifier A

              Pred P   Pred N
  Actual P       6        4
  Actual N       5       85

Accuracy=6+85100=91100=0.91.\text{Accuracy}=\frac{6+85}{100}=\frac{91}{100}=0.91 .

Classifier B

              Pred P   Pred N
  Actual P       1        9
  Actual N       4       86

Accuracy=87100=0.87,Recall=11+9=110=0.10,Precision=11+4=15=0.20.\text{Accuracy}=\frac{87}{100}=0.87,\qquad \text{Recall}=\frac{1}{1+9}=\frac1{10}=0.10,\qquad \text{Precision}=\frac{1}{1+4}=\frac15=0.20 .

(Computed here from the formula, not on the page: F1=2⋅0.10⋅0.200.10+0.20=0.040.30≈0.13F_1=\dfrac{2\cdot0.10\cdot0.20}{0.10+0.20}=\dfrac{0.04}{0.30}\approx0.13.)

B has a high accuracy and nearly useless recall and precision, because 90 of the 100 objects are negative and most of them are classified correctly anyway. A second extreme case on the next page: a classifier that answers "positive" for every object gives

              Pred P   Pred N
  Actual P      10        0
  Actual N      90        0

with recall =1010+0=100%=\dfrac{10}{10+0}=100\% (it finds all the positives) and precision =10100=10%=\dfrac{10}{100}=10\% (it calls positive 100 objects, 10 of which are). The page also writes the percentages 0%0\% and 90%90\% on the right of these results; their meaning is not clear from the handwriting. The page also notes the figure 90/100=0.990/100=0.9 near the accuracy formula, which is the accuracy of a classifier that always answers "negative" on this data set (my reading: the matrix is not drawn).

Lesson of the example: accuracy alone is not enough when the classes are unbalanced; recall, precision and F1F_1 show what accuracy hides.

4. Multi-class classification

With more classes C1,C2,C3,C4,…C_1,C_2,C_3,C_4,\dots the per-class view is used: for each class CiC_i one looks at the classifier "class CiC_i against the rest" and computes its recalli_i and precisioni_i.

The confusion matrix becomes square: rows are the actual class y∈{0,1,2}y\in\{0,1,2\}, columns the predicted class y^∈{0,1,2}\hat y\in\{0,1,2\}. The page fills it from two label vectors of length ten (actual y\mathbf{y} and predicted y^\hat{\mathbf{y}}), with crosses for the errors. The diagonal entries are the true positives TP0,TP1,TP2TP_0,TP_1,TP_2 of each class; the row of class ii is "total class ii" (all objects whose actual class is ii); the column of class ii collects all the objects the classifier assigned to class ii. Then

accuracy=#correct answers#total answers,recalli=TPi#total class i,precisioni=TPi#total objects assigned to class i.\text{accuracy}=\frac{\#\text{correct answers}}{\#\text{total answers}},\qquad \text{recall}_i=\frac{TP_i}{\#\text{total class }i},\qquad \text{precision}_i=\frac{TP_i}{\#\text{total objects assigned to class }i}.

(The numerator of accuracy is the sum of the diagonal.) The same page draws three clouds C1,C2,C3C_1,C_2,C_3 in the plane (x1,x2)(x_1,x_2) with three lines, each with a hatched side, and test points marked "?" that fall on the hatched side of several lines or of none: with one linear classifier per class an object can be claimed by more than one class or by none (the notes do not name the scheme).

Versione ripasso

  • Target ff = actual output; hypothesis hh = predicted output. Compare the vector y\mathbf{y} of actual outputs with the vector y^\hat{\mathbf{y}} of predictions on the same objects.
  • Binary confusion matrix (rows actual, columns predicted): Actual P gives TP, FN; Actual N gives FP, TN. Entry by entry: y=1,y^=1y=1,\hat y=1 TP; y=0,y^=0y=0,\hat y=0 TN; y=0,y^=1y=0,\hat y=1 FP; y=1,y^=0y=1,\hat y=0 FN.

Accuracy=TP+TNTP+TN+FP+FN,    Recall=TPTP+FN,    Precision=TPTP+FP,    F1=2 Recall PrecisionRecall+Precision.\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN},\;\;\text{Recall}=\frac{TP}{TP+FN},\;\;\text{Precision}=\frac{TP}{TP+FP},\;\;F_1=\frac{2\,\text{Recall}\,\text{Precision}}{\text{Recall}+\text{Precision}}.

Teoria collegata