3.4. Metrics and scoring: quantifying the quality of predictions
3.4.1. Which scoring function should I use?
Before we take a closer look into the details of the many scores and
evaluation metrics, we want to give some guidance, inspired by statistical
decision theory, on the choice of scoring functions for supervised learning,
see [Gneiting2009]:
Which scoring function should I use?
Which scoring function is a good one for my task?
In a nutshell, if the scoring function is given, e.g. in a kaggle competition
or in a business context, use that one.
If you are free to choose, it starts by considering the ultimate goal and application
of the prediction. It is useful to distinguish two steps:
Predicting
Decision making
Predicting:
Usually, the response variable Y is a random variable, in the sense that there
is function of the features .
Instead, there is a probability distribution of .
One can aim to predict the whole distribution, known as ,
or—more the focus of scikit-learn—issue a (or point forecast)
by choosing a property or functional of that distribution .
Typical examples are the mean (expected value), the median or a quantile of the
response variable (conditionally on ).
no deterministic
Y=g(X)
X
F
Y
probabilistic prediction
point prediction
F
Y
X
Once that is settled, use a strictly consistent scoring function for that
(target) functional, see [Gneiting2009].
This means using a scoring function that is aligned with measuring the distance
between predictionsy_predand the true target functional using observations ofY, i.e. y_true.
For classification strictly proper scoring rules, see
Wikipedia entry for Scoring rule
and [Gneiting2007], coincide with strictly consistent scoring functions.
The table further below provides examples.
One could say that consistent scoring functions act as truth serum in that
they guarantee “that truth telling […] is an optimal strategy in
expectation”[Gneiting2014].
Once a strictly consistent scoring function is chosen, it is best used for both: as
loss function for model training and as metric/score in model evaluation and model
comparison.
Note that for regressors, the prediction is done with predict while for
classifiers it is usually predict_proba.
Decision Making:
The most common decisions are done on binary classification tasks, where the result of
predict_proba is turned into a single outcome, e.g., from the predicted
probability of rain a decision is made on how to act (whether to take mitigating
measures like an umbrella or not).
For classifiers, this is what predict returns.
See also Tuning the decision threshold for class prediction.
There are many scoring functions which measure different aspects of such a
decision, most of them are covered with or derived from the
metrics.confusion_matrix.
List of strictly consistent scoring functions:
Here, we list some of the most relevant statistical functionals and corresponding
strictly consistent scoring functions for tasks in practice. Note that the list is not
complete and that there are more of them.
For further criteria on how to select a specific one, see [Fissler2022].
1 The Brier score is just a different name for the squared error in case of
classification with one-hot encoded targets.
2 The zero-one loss is only consistent but not strictly consistent for the mode.
The zero-one loss is equivalent to one minus the accuracy score, meaning it gives
different score values but the same ranking.
3 R² gives the same ranking as squared error.
Fictitious Example:
Let’s make the above arguments more tangible. Consider a setting in network reliability
engineering, such as maintaining stable internet or Wi-Fi connections.
As provider of the network, you have access to the dataset of log entries of network
connections containing network load over time and many interesting features.
Your goal is to improve the reliability of the connections.
In fact, you promise your customers that on at least 99% of all days there are no
connection discontinuities larger than 1 minute.
Therefore, you are interested in a prediction of the 99% quantile (of longest
connection interruption duration per day) in order to know in advance when to add
more bandwidth and thereby satisfy your customers. So the target functional is the
99% quantile. From the table above, you choose the pinball loss as scoring function
(fair enough, not much choice given), for model training (e.g.
HistGradientBoostingRegressor(loss="quantile",quantile=0.99)) as well as model
evaluation (mean_pinball_loss(...,alpha=0.99) - we apologize for the different
argument names, quantile and alpha) be it in grid search for finding
hyperparameters or in comparing to other models like
QuantileRegressor(quantile=0.99).
There are 3 different APIs for evaluating the quality of a model’s
predictions:
Estimator score method: Estimators have a score method providing a
default evaluation criterion for the problem they are designed to solve.
Most commonly this is accuracy for classifiers and the
coefficient of determination (R2) for regressors.
Details for each estimator can be found in its documentation.
For the most common use cases, you can designate a scorer object with the
scoring parameter via a string name; the table below shows all possible values.
All scorer objects follow the convention that higher return values are better
than lower return values. Thus metrics which measure the distance between
the model and the data, like metrics.mean_squared_error, are
available as ‘neg_mean_squared_error’ which return the negated value
of the metric.
Scoring string name
Function
Comment
3.4.3.2. Callable scorers
For more complex use cases and more flexibility, you can pass a callable to
the scoring parameter. This can be done by:
3.4.3.2.1. Adapting predefined metrics via make_scorer
The following metric functions are not implemented as named scorers,
sometimes because they require additional parameters, such as
fbeta_score. They cannot be passed to the scoring
parameters; instead their callable needs to be passed to
together with the value of the user-settable
parameters.
3.4.3.3. Using multiple metric evaluation
Scikit-learn also permits evaluation of multiple metrics in GridSearchCV,
RandomizedSearchCV and cross_validate.
There are three ways to specify multiple scoring metrics for the scoring
parameter:
As an iterable of string metrics:
>>> scoring=['accuracy','precision']
As a mapping the scorer name to the scoring function:
3.4.4. Classification metrics
The sklearn.metrics module implements several loss, score, and utility functions
to measure classification performance. Some metrics might require probability estimates
of the positive class or non-thresholded decision values (as returned by
decision_function on some classifiers). Most implementations allow each sample
to provide a weighted contribution to the overall score, through the sample_weight
parameter.
Some of these are restricted to the binary classification case:
Compute average precision (AP) from prediction scores.
In the following sub-sections, we will describe each of those functions,
preceded by some notes on common API and metric definition.
3.4.4.1. From binary to multiclass and multilabel
Some metrics are essentially defined for binary classification tasks (e.g.
f1_score, roc_auc_score). In these cases, by default
only the positive label is evaluated, assuming by default that the positive
class is labelled 1 (though this may be configurable through the
pos_label parameter).
In extending a binary metric to multiclass or multilabel problems, the data
is treated as a collection of binary problems, one for each class.
There are then a number of ways to average binary metric calculations across
the set of classes, each of which may be useful in some scenario.
Where available, you should select among these using the average parameter.
simply calculates the mean of the binary metrics,
giving equal weight to each class. In problems where infrequent classes
are nonetheless important, macro-averaging may be a means of highlighting
their performance. On the other hand, the assumption that all classes are
equally important is often untrue, such that macro-averaging will
over-emphasize the typically low performance on an infrequent class.
3.4.4.2. Accuracy score
The accuracy_score function computes the
accuracy, either the fraction
(default) or the count (normalize=False) of correct predictions.
In multilabel classification, the function returns the subset accuracy. If
the entire set of predicted labels for a sample strictly match with the true
set of labels, then the subset accuracy is 1.0; otherwise it is 0.0.
If y^i is the predicted value of
the -th sample and is the corresponding true value,
then the fraction of correct predictions over is
defined as
3.4.4.3. Top-k accuracy score
The top_k_accuracy_score function is a generalization of
accuracy_score. The difference is that a prediction is considered
correct as long as the true label is associated with one of the k highest
predicted scores. accuracy_score is the special case of k=1.
The function covers the binary and multiclass classification cases but not the
multilabel case.
If f^i,j is the predicted class for the -th sample
corresponding to the -th largest predicted score and is the
corresponding true value, then the fraction of correct predictions over
is defined as
3.4.4.4. Balanced accuracy score
The balanced_accuracy_score function computes the balanced accuracy, which avoids inflated
performance estimates on imbalanced datasets. It is the macro-average of recall
scores per class or, equivalently, raw accuracy where each sample is weighted
according to the inverse prevalence of its true class.
Thus for balanced datasets, the score is equal to accuracy.
In the binary case, balanced accuracy is equal to the arithmetic mean of
sensitivity
(true positive rate) and specificity (true negative
rate), or the area under the ROC curve with binary predictions rather than
scores:
balanced-accuracy=21(TP+FNTP+TN+FPTN)
3.4.4.5. Cohen’s kappa
The function cohen_kappa_score computes Cohen’s kappa statistic.
This measure is intended to compare labelings by different human annotators,
not a classifier versus a ground truth.
The kappa score is a number between -1 and 1.
Scores above .8 are generally considered good agreement;
zero or lower means no agreement (practically random labels).
Kappa scores can be computed for binary or multiclass problems,
but not for multilabel problems (except by manually computing a per-label score)
and not for more than two annotators.
The confusion_matrix function evaluates
classification accuracy by computing the confusion matrix with each row corresponding
to the true class (Wikipedia and other references may use different convention
for axes).
By definition, entry i,j in a confusion matrix is
the number of observations actually in group i, but
predicted to be in group j. Here is an example:
3.4.4.7. Classification report
The classification_report function builds a text report showing the
main classification metrics. Here is a small example with custom target_names
and inferred labels:
If y^i,j is the predicted value for the j-th label of a
given sample , is the corresponding true value,
is the number of samples and
is the number of labels, then the Hamming loss is defined
as:
3.4.4.9. Precision, recall and F-measures
Intuitively, precision is the ability
of the classifier not to label as positive a sample that is negative, and
recall is the
ability of the classifier to find all the positive samples.
The F-measure
(Fβ and F1 measures) can be interpreted as a weighted
harmonic mean of the precision and recall. A
measure reaches its best value at 1 and its worst score at 0.
With , and
are equivalent, and the recall and the precision are equally important.
The Jaccard similarity coefficient with a ground truth label set y and
predicted label set y^, is defined as
J(y,y^)=∣y∪y^∣∣y∩y^∣.
3.4.4.11. Hinge loss
The hinge_loss function computes the average distance between
the model and the data using
hinge loss, a one-sided metric
that considers only prediction errors. (Hinge
loss is used in maximal margin classifiers such as support vector machines.)
If the true label yi of a binary classification task is encoded as
yi={−1,+1} for every sample ; and
is the corresponding predicted decision (an array of shape (,) as
output by the method), then the hinge loss is defined as:
3.4.4.12. Log loss
Log loss, also called logistic regression loss or
cross-entropy loss, is defined on probability estimates. It is
commonly used in (multinomial) logistic regression and neural networks, as well
as in some variants of expectation-maximization, and can be used to evaluate the
probability outputs (predict_proba) of a classifier instead of its
discrete predictions.
For binary classification with a true label y∈{0,1}
and a probability estimate p^≈Pr(y=1),
the log loss per sample is the negative log-likelihood
of the classifier given the true label:
“The Matthews correlation coefficient is used in machine learning as a
measure of the quality of binary (two-class) classifications. It takes
into account true and false positives and negatives and is generally
regarded as a balanced measure which can be used even if the classes are
of very different sizes. The MCC is in essence a correlation coefficient
value between -1 and +1. A coefficient of +1 represents a perfect
prediction, 0 an average random prediction and -1 an inverse prediction.
The statistic is also known as the phi coefficient.”
In the binary (two-class) case, tp, tn, fp and
fn are respectively the number of true positives, true negatives, false
positives and false negatives, the MCC is defined as
In the multiclass case, the Matthews correlation coefficient can be defined in terms of a
for classes. To simplify the
definition consider the following intermediate variables:
3.4.4.14. Multi-label confusion matrix
The multilabel_confusion_matrix function computes class-wise (default)
or sample-wise (samplewise=True) multilabel confusion matrix to evaluate
the accuracy of a classification. multilabel_confusion_matrix also treats
multiclass data as if it were multilabel, as this is a transformation commonly
applied to evaluate multiclass problems with binary classification metrics
(such as precision, recall, etc.).
When calculating class-wise multilabel confusion matrix C, the
count of true negatives for class i is C_{i,0,0}, false
negatives is C_{i,1,0}, true positives is C_{i,1,1}
and false positives is C_{i,0,1}.
“A receiver operating characteristic (ROC), or simply ROC curve, is a
graphical plot which illustrates the performance of a binary classifier
system as its discrimination threshold is varied. It is created by plotting
the fraction of true positives out of the positives (TPR = true positive
rate) vs. the fraction of false positives out of the negatives (FPR = false
positive rate), at various threshold settings. TPR is also known as
sensitivity, and FPR is one minus the specificity or true negative rate.”
This function requires the true binary value and the target scores, which can
either be probability estimates of the positive class or non-thresholded decision values
(as returned by decision_function on some classifiers). Here is a small example
of how to use the roc_curve function:
3.4.4.16. Detection error tradeoff (DET)
The function det_curve computes the
detection error tradeoff curve (DET) curve [WikipediaDET2017].
Quoting Wikipedia:
“A detection error tradeoff (DET) graph is a graphical plot of error rates
for binary classification systems, plotting false reject rate vs. false
accept rate. The x- and y-axes are scaled non-linearly by their standard
normal deviates (or just by logarithmic transformation), yielding tradeoff
curves that are more linear than ROC curves, and use most of the image area
to highlight the differences of importance in the critical operating region.”
DET curves are a variation of receiver operating characteristic (ROC) curves
where False Negative Rate is plotted on the y-axis instead of True Positive
Rate.
DET curves are commonly plotted in normal deviate scale by transformation with
\phi^{-1} (with \phi being the cumulative distribution
function).
The resulting performance curves explicitly visualize the tradeoff of error
types for given classification algorithms.
See [Martin1997] for examples and further motivation.
This figure compares the ROC and DET curves of two example classifiers on the
same classification task:
3.4.4.17. Zero one loss
The zero_one_loss function computes the sum or the average of the 0-1
classification loss (L_{0-1}) over n_{\text{samples}}. By
default, the function normalizes over the sample. To get the sum of the
L_{0-1}, set normalize to False.
In multilabel classification, the zero_one_loss scores a subset as
one if its labels strictly match the predictions, and as a zero if there
are any errors. By default, the function returns the percentage of imperfectly
predicted subsets. To get the count of such subsets instead, set
normalize to .
3.4.4.18. Brier score loss
The brier_score_loss function computes the Brier score for binary and multiclass
probabilistic predictions and is equivalent to the mean squared error.
Quoting Wikipedia:
“The Brier score is a strictly proper scoring rule that measures the accuracy of
probabilistic predictions. […] [It] is applicable to tasks in which predictions
must assign probabilities to a set of mutually exclusive discrete outcomes or
classes.”
Let the true labels for a set of N data points be encoded as a 1-of-K binary
indicator matrix Y, i.e., y_{i,k} = 1 if sample i has
label k taken from a set of K labels. Let \hat{P} be a matrix
of probability estimates with elements \hat{p}_{i,k} \approx \operatorname{Pr}(y_{i,k} = 1).
Following the original definition by , the Brier score is given by:
3.4.4.19. Class likelihood ratios
The class_likelihood_ratios function computes the positive and negative
likelihood ratiosLR_\pm for binary classes, which can be interpreted as the ratio of
post-test to pre-test odds as explained below. As a consequence, this metric is
invariant w.r.t. the class prevalence (the number of samples in the positive
class divided by the total number of samples) and can be extrapolated between
populations regardless of any possible class imbalance.
The LR_\pm metrics are therefore very useful in settings where the data
available to learn and evaluate a classifier is a study population with nearly
balanced classes, such as a case-control study, while the target application,
i.e. the general population, has very low prevalence.
The positive likelihood ratio LR_+ is the probability of a classifier to
correctly predict that a sample belongs to the positive class divided by the
probability of predicting the positive class for a sample belonging to the
negative class:
LR_+ = \frac{\text{PR}(P+|T+)}{\text{PR}(P+|T-)}.
The notation here refers to predicted (P) or true (T) label and
the sign and refer to the positive and negative class,
respectively, e.g. stands for “predicted positive”.
3.4.4.20. D² score for classification
The D² score computes the fraction of deviance explained.
It is a generalization of R², where the squared error is generalized and replaced
by a classification deviance of choice \text{dev}(y, \hat{y})
(e.g., Log loss, Brier score,). D² is a form of a skill score.
It is calculated as
Where y_{\text{null}} is the optimal prediction of an intercept-only model
(e.g., the per-class proportion of y_true in the case of the Log loss and Brier score).
Like R², the best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse). A constant model that always predicts
y_{\text{null}}, disregarding the input features, would get a D² score
of 0.0.
D2 log loss score
The function implements the special case
of D² with the log loss, see , i.e.:
3.4.5. Multilabel ranking metrics
In multilabel learning, each sample can have any number of ground truth labels
associated with it. The goal is to give high scores and better rank to
the ground truth labels.
3.4.5.1. Coverage error
The coverage_error function computes the average number of labels that
have to be included in the final prediction such that all true labels
are predicted. This is useful if you want to know how many top-scored-labels
you have to predict in average without missing any true one. The best value
of this metric is thus the average number of true labels.
Formally, given a binary indicator matrix of the ground truth labels
y \in \left\{0, 1\right\}^{n_\text{samples} \times n_\text{labels}} and the
score associated with each label
\hat{f} \in \mathbb{R}^{n_\text{samples} \times n_\text{labels}},
the coverage is defined as
with \text{rank}_{ij} = \left|\left\{k: \hat{f}_{ik} \geq \hat{f}_{ij} \right\}\right|.
Given the rank definition, ties in y_scores are broken by giving the
maximal rank that would have been assigned to all tied values.
Here is a small example of usage of this function:
The label_ranking_average_precision_score function
implements label ranking average precision (LRAP). This metric is linked to
the average_precision_score function, but is based on the notion of
label ranking instead of precision and recall.
Label ranking average precision (LRAP) averages over the samples the answer to
the following question: for each ground truth label, what fraction of
higher-ranked labels were true labels? This performance measure will be higher
if you are able to give better rank to the labels associated with each sample.
The obtained score is always strictly greater than 0, and the best value is 1.
If there is exactly one relevant label per sample, label ranking average
precision is equivalent to the mean
reciprocal rank.
Formally, given a binary indicator matrix of the ground truth labels
y \in \left\{0, 1\right\}^{n_\text{samples} \times n_\text{labels}}
and the score associated with each label
\hat{f} \in \mathbb{R}^{n_\text{samples} \times n_\text{labels}},
the average precision is defined as
The label_ranking_loss function computes the ranking loss which
averages over the samples the number of label pairs that are incorrectly
ordered, i.e. true labels have a lower score than false labels, weighted by
the inverse of the number of ordered pairs of false and true labels.
The lowest achievable ranking loss is zero.
Formally, given a binary indicator matrix of the ground truth labels
y \in \left\{0, 1\right\}^{n_\text{samples} \times n_\text{labels}} and the
score associated with each label
\hat{f} \in \mathbb{R}^{n_\text{samples} \times n_\text{labels}},
the ranking loss is defined as
where |\cdot| computes the cardinality of the set (i.e., the number of
elements in the set) and ||\cdot||_0 is the \ell_0 “norm”
(which computes the number of nonzero elements in a vector).
Here is a small example of usage of this function:
3.4.5.4. Normalized Discounted Cumulative Gain
Discounted Cumulative Gain (DCG) and Normalized Discounted Cumulative Gain
(NDCG) are ranking metrics implemented in dcg_score
and ndcg_score ; they compare a predicted order to
ground-truth scores, such as the relevance of answers to a query.
From the Wikipedia page for Discounted Cumulative Gain:
“Discounted cumulative gain (DCG) is a measure of ranking quality. In
information retrieval, it is often used to measure effectiveness of web search
engine algorithms or related applications. Using a graded relevance scale of
documents in a search-engine result set, DCG measures the usefulness, or gain,
of a document based on its position in the result list. The gain is accumulated
from the top of the result list to the bottom, with the gain of each result
discounted at lower ranks.”
DCG orders the true targets (e.g. relevance of query answers) in the predicted
order, then multiplies them by a logarithmic decay and sums the result. The sum
can be truncated after the first K results, in which case we call it
DCG@K.
NDCG, or NDCG@K is DCG divided by the DCG obtained by a perfect prediction, so
that it is always between 0 and 1. Usually, NDCG is preferred to DCG.
Compared with the ranking loss, NDCG can take into account relevance scores,
rather than a ground-truth ranking. So if the ground-truth consists only of an
ordering, the ranking loss should be preferred; if the ground-truth consists of
actual usefulness scores (e.g. 0 for irrelevant, 1 for relevant, 2 for very
relevant), NDCG can be used.
These functions have a multioutput keyword argument which specifies the
way the scores or losses for each individual target should be averaged. The
default is 'uniform_average', which specifies a uniformly weighted mean
over outputs. If an ndarray of shape (n_outputs,) is passed, then its
entries are interpreted as weights and an according weighted average is
returned. If multioutput is 'raw_values', then all unaltered
individual scores or losses will be returned in an array of shape
(n_outputs,).
The r2_score and explained_variance_score accept an additional
value 'variance_weighted' for the multioutput parameter. This option
leads to a weighting of each individual score by the variance of the
corresponding target variable. This setting quantifies the globally captured
unscaled variance. If the target variables are of different scale, then this
score puts more importance on explaining the higher variance variables.
3.4.6.1. R² score, the coefficient of determination
It represents the proportion of variance (of y) that has been explained by the
independent variables in the model. It provides an indication of goodness of
fit and therefore a measure of how well unseen samples are likely to be
predicted by the model, through the proportion of explained variance.
As such variance is dataset dependent, R^2 may not be meaningfully comparable
across different datasets. Best possible score is 1.0 and it can be negative
(because the model can be arbitrarily worse). A constant model that always
predicts the expected (average) value of y, disregarding the input features,
would get an R^2 score of 0.0.
Note: when the prediction residuals have zero mean, the R^2 score and
the Explained variance score are identical.
If \hat{y}_i is the predicted value of the i-th sample
and is the corresponding true value for total samples,
the estimated is defined as:
3.4.6.2. Mean absolute error
The mean_absolute_error function computes mean absolute
error, a risk
metric corresponding to the expected value of the absolute error loss or
l1-norm loss.
If \hat{y}_i is the predicted value of the i-th sample,
and y_i is the corresponding true value, then the mean absolute error
(MAE) estimated over n_{\text{samples}} is defined as
The mean_squared_error function computes mean squared
error, a risk
metric corresponding to the expected value of the squared (quadratic) error or
loss.
If \hat{y}_i is the predicted value of the i-th sample,
and y_i is the corresponding true value, then the mean squared error
(MSE) estimated over n_{\text{samples}} is defined as
The mean_squared_log_error function computes a risk metric
corresponding to the expected value of the squared logarithmic (quadratic)
error or loss.
If \hat{y}_i is the predicted value of the i-th sample,
and y_i is the corresponding true value, then the mean squared
logarithmic error (MSLE) estimated over n_{\text{samples}} is
defined as
Where \log_e (x) means the natural logarithm of x. This metric
is best to use when targets having exponential growth, such as population
counts, average sales of a commodity over a span of years etc. Note that this
metric penalizes an under-predicted estimate greater than an over-predicted
estimate.
Here is a small example of usage of the
function:
3.4.6.5. Mean absolute percentage error
The mean_absolute_percentage_error (MAPE), also known as mean absolute
percentage deviation (MAPD), is an evaluation metric for regression problems.
The idea of this metric is to be sensitive to relative errors. It is for example
not changed by a global scaling of the target variable.
If \hat{y}_i is the predicted value of the i-th sample
and y_i is the corresponding true value, then the mean absolute percentage
error (MAPE) estimated over n_{\text{samples}} is defined as
where \epsilon is an arbitrary small yet strictly positive number to
avoid undefined results when y is zero.
The function supports multioutput.
3.4.6.6. Median absolute error
The median_absolute_error is particularly interesting because it is
robust to outliers. The loss is calculated by taking the median of all absolute
differences between the target and the prediction.
If \hat{y}_i is the predicted value of the i-th sample
and y_i is the corresponding true value, then the median absolute error
(MedAE) estimated over n_{\text{samples}} is defined as
The max_error function computes the maximum residual error , a metric
that captures the worst case error between the predicted value and
the true value. In a perfectly fitted single output regression
model, max_error would be 0 on the training set and though this
would be highly unlikely in the real world, this metric shows the
extent of error that the model had when it was fitted.
If \hat{y}_i is the predicted value of the i-th sample,
and y_i is the corresponding true value, then the max error is
defined as
If \hat{y} is the estimated target output, y the corresponding
(correct) target output, and Var is Variance, the square of the standard deviation,
then the explained variance is estimated as follow:
explained\_{}variance(y, \hat{y}) = 1 - \frac{Var\{ y - \hat{y}\}}{Var\{y\}}
The best possible score is 1.0, lower values are worse.
In the particular case where the true target is constant, the Explained
Variance score is not finite: it is either NaN (perfect predictions) or
-Inf (imperfect predictions). Such non-finite scores may prevent correct
model optimization such as grid-search cross-validation to be performed
correctly. For this reason the default behaviour of
is to replace them with 1.0 (perfect
predictions) or 0.0 (imperfect predictions). You can set the
parameter to to prevent this fix from happening and fallback on the
original Explained Variance score.
3.4.6.9. Mean Poisson, Gamma, and Tweedie deviances
The D² score computes the fraction of deviance explained.
It is a generalization of R², where the squared error is generalized and replaced
by a deviance of choice \text{dev}(y, \hat{y})
(e.g., Tweedie, pinball or mean absolute error). D² is a form of a skill score.
It is calculated as
Where y_{\text{null}} is the optimal prediction of an intercept-only model
(e.g., the mean of y_true for the Tweedie case, the median for absolute
error and the alpha-quantile for pinball loss).
Like R², the best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse). A constant model that always predicts
y_{\text{null}}, disregarding the input features, would get a D² score
of 0.0.
D² Tweedie score
The function implements the special case of D²
where is the Tweedie deviance, see .
It is also known as D² Tweedie and is related to McFadden’s likelihood ratio index.
3.4.6.12. Visual evaluation of regression models
Among methods to assess the quality of regression models, scikit-learn provides
the PredictionErrorDisplay class. It allows to
visually inspect the prediction errors of a model in two different manners.
The plot on the left shows the actual values vs predicted values. For a
noise-free regression task aiming to predict the (conditional) expectation of
y, a perfect regression model would display data points on the diagonal
defined by predicted equal to actual values. The further away from this optimal
line, the larger the error of the model. In a more realistic setting with
irreducible noise, that is, when not all the variations of y can be explained
by features in X, then the best model would lead to a cloud of points densely
arranged around the diagonal.
Note that the above only holds when the predicted values is the expected value
of given . This is typically the case for regression models that
minimize the mean squared error objective function or more generally the
for any value of its
“power” parameter.
When doing supervised learning, a simple sanity check consists of comparing
one’s estimator against simple rules of thumb. DummyClassifier
implements several such simple strategies for classification:
stratified generates random predictions by respecting the training
set class distribution.
most_frequent always predicts the most frequent label in the training set.
prior always predicts the class that maximizes the class prior
(like most_frequent) and predict_proba returns the class prior.
uniform generates predictions uniformly at random.
constant always predicts a constant label that is provided by the user.
A major motivation of this method is F1-scoring, when the positive class
is in the minority.
Note that with all these strategies, the predict method completely ignores
the input data!
To illustrate DummyClassifier, first let’s create an imbalanced
dataset:
We see that the accuracy was boosted to almost 100%. A cross validation
strategy is recommended for a better estimate of the accuracy, if it
is not too CPU costly. For more information see the Cross-validation: evaluating estimator performance
section. Moreover if you want to optimize over the parameter space, it is highly
recommended to use an appropriate methodology; see the Tuning the hyper-parameters of an estimator
section for details.
More generally, when the accuracy of a classifier is too close to random, it
probably means that something went wrong: features are not helpful, a
hyperparameter is not correctly tuned, the classifier is suffering from class
imbalance, etc…
DummyRegressor also implements four simple rules of thumb for regression:
mean always predicts the mean of the training targets.
median always predicts the median of the training targets.
quantile always predicts a user provided quantile of the training targets.
constant always predicts a constant value that is provided by the user.
In all these strategies, the predict method completely ignores
the input data.
One typical use case is to wrap an existing metric function from the library
with non-default values for its parameters, such as the beta parameter for
the fbeta_score function:
The module sklearn.metrics also exposes a set of simple functions
measuring a prediction error given ground truth and prediction:
functions ending with _score return a value to
maximize, the higher the better.
functions ending with _error, _loss, or _deviance return a
value to minimize, the lower the better. When converting
into a scorer object using make_scorer, set
the greater_is_better parameter to False (True by default; see the
parameter description below).
3.4.3.2.2. Creating a custom scorer object
You can create your own custom scorer object using
make_scorer.
Custom scorer objects using make_scorer
You can build a completely custom scorer object
from a simple python function using make_scorer, which can
take several parameters:
the python function you want to use (my_custom_loss_func
in the example below)
whether the python function returns a score (greater_is_better=True,
the default) or a loss (greater_is_better=False). If a loss, the output
of the python function is negated by the scorer object, conforming to
the cross validation convention that scorers return higher values for better models.
for classification metrics only: whether the python function you provided requires
continuous decision certainties. If the scoring function only accepts probability
estimates (e.g. metrics.log_loss), then one needs to set the parameter
response_method="predict_proba". Some scoring
functions do not necessarily require probability estimates but rather non-thresholded
decision values (e.g. metrics.roc_auc_score). In this case, one can provide a
list (e.g., response_method=["decision_function","predict_proba"]),
and scorer will use the first available method, in the order given in the list,
to compute the scores.
any additional parameters of the scoring function, such as beta or labels.
Here is an example of building custom scorers, and of using the
greater_is_better parameter:
Using custom scorers in functions where n_jobs > 1
While defining the custom scoring function alongside the calling function
should work out of the box with the default joblib backend (loky),
importing it from another module will be a more robust approach and work
independently of the joblib backend.
For example, to use n_jobs greater than 1 in the example below,
custom_scoring_function function is saved in a user-created module
(custom_scorer_module.py) and imported:
D2 score function, fraction of log loss explained.
"macro"
"weighted" accounts for class imbalance by computing the average of
binary metrics in which each class’s score is weighted by its presence in the
true data sample.
"micro" gives each sample-class pair an equal contribution to the overall
metric (except as a result of sample-weight). Rather than summing the
metric per class, this sums the dividends and divisors that make up the
per-class metrics to calculate an overall quotient.
Micro-averaging may be preferred in multilabel settings, including
multiclass classification where a majority class is to be ignored.
"samples" applies only to multilabel problems. It does not calculate a
per-class measure, instead calculating the metric over the true and predicted
classes for each sample in the evaluation data, and returning their
(sample_weight-weighted) average.
Selecting average=None will return an array with the score for each
class.
While multiclass data is provided to the metric, like binary targets, as an
array of class labels, multilabel data is specified as an indicator matrix,
in which cell [i,j] has value 1 if sample i has label j and value
0 otherwise.
where k is the number of guesses allowed and 1(x) is the
indicator function.
>>> importnumpyasnp>>> fromsklearn.metricsimporttop_k_accuracy_score>>> y_true=np.array([0,1,2,2])>>> y_score=np.array([[0.5,0.2,0.2],... [0.3,0.4,0.2],... [0.2,0.4,0.3],... [0.7,0.2,0.1]])>>> top_k_accuracy_score(y_true,y_score,k=2)0.75>>> # Not normalizing gives the number of "correctly" classified samples>>> top_k_accuracy_score(y_true,y_score,k=2,normalize=False)3.0
If the classifier performs equally well on either class, this term reduces to
the conventional accuracy (i.e., the number of correct predictions divided by
the total number of predictions).
In contrast, if the conventional accuracy is above chance only because the
classifier takes advantage of an imbalanced test set, then the balanced
accuracy, as appropriate, will drop to n_classes1.
The score ranges from 0 to 1, or when adjusted=True is used, it is rescaled to
the range 1−n_classes1 to 1, inclusive, with
performance at random scoring 0.
If yi is the true value of the i-th sample, and wi
is the corresponding sample weight, then we adjust the sample weight to:
w^i=∑j1(yj=yi)wjwi
where 1(x) is the indicator function.
Given predicted y^i for sample i, balanced accuracy is
defined as:
With adjusted=True, balanced accuracy reports the relative increase from
balanced-accuracy(y,0,w)=n_classes1. In the binary case, this is also known as
Youden’s J statistic,
or informedness.
I. Guyon, K. Bennett, G. Cawley, H.J. Escalante, S. Escalera, T.K. Ho, N. Macià,
B. Ray, M. Saeed, A.R. Statnikov, E. Viegas, Design of the 2015 ChaLearn AutoML Challenge, IJCNN 2015.
The parameter normalize allows to report ratios instead of counts. The
confusion matrix can be normalized in 3 different ways: 'pred', 'true',
and 'all' which will divide the counts by the sum of each columns, rows, or
the entire matrix, respectively.
The precision_recall_curve computes a precision-recall curve
from the ground truth label and a score given by the classifier
by varying a decision threshold.
The average_precision_score function computes the
average precision
(AP) from prediction scores. The value is between 0 and 1 and higher is better.
AP is defined as
AP=n∑(Rn−Rn−1)Pn
where Pn and Rn are the precision and recall at the
nth threshold. With random predictions, the AP is the fraction of positive
samples.
References [Manning2008] and [Everingham2010] present alternative variants of
AP that interpolate the precision-recall curve. Currently,
average_precision_score does not implement any interpolated variant.
References [Davis2006] and [Flach2015] describe why a linear interpolation of
points on the precision-recall curve provides an overly-optimistic measure of
classifier performance. This linear interpolation is used when computing area
under the curve with the trapezoidal rule in auc. [Chen2024]
benchmarks different interpolation strategies to demonstrate the effects.
Several functions allow you to analyze the precision, recall and F-measures
score:
Note that the precision_recall_curve function is restricted to the
binary case. The average_precision_score function supports multiclass
and multilabel formats by computing each class score in a One-vs-the-rest (OvR)
fashion and averaging them or not depending of its average argument value.
In a binary classification task, the terms ‘’positive’’ and ‘’negative’’ refer
to the classifier’s prediction, and the terms ‘’true’’ and ‘’false’’ refer to
whether that prediction corresponds to the external judgment (sometimes known
as the ‘’observation’’). Given these definitions, we can formulate the
following table:
Actual class (observation)
Predicted class
(expectation)
tp (true positive)
Correct result
fp (false positive)
Unexpected result
fn (false negative)
Missing result
tn (true negative)
Correct absence of result
In this context, we can define the notions of precision and recall:
precision=tp+fptp,
recall=tp+fntp,
(Sometimes recall is also called ‘’sensitivity’’)
F-measure is the weighted harmonic mean of precision and recall, with precision’s
contribution to the mean weighted by some parameter β:
Fβ=(1+β2)β2precision+recallprecision×recall
To avoid division by zero when precision and recall are zero, Scikit-Learn calculates F-measure with this
otherwise-equivalent formula:
Fβ=(1+β2)tp+fp+β2fn(1+β2)tp
Note that this formula is still undefined when there are no true positives, false
positives, or false negatives. By default, F-1 for a set of exclusively true negatives
is calculated as 0, however this behavior can be changed using the zero_division
parameter.
Here are some small examples in binary classification:
If all labels are included, “micro”-averaging in a multiclass setting will produce
precision, recall and F that are all identical to accuracy.
“weighted” averaging may produce an F-score that is not between precision and recall.
“macro” averaging for F-measures is calculated as the arithmetic mean over
per-label/class F-measures, not the harmonic mean over the arithmetic precision and
recall means. Both calculations can be seen in the literature but are not equivalent,
see [OB2019] for details.
To make this more explicit, consider the following notation:
The jaccard_score (like precision_recall_fscore_support) applies
natively to binary targets. By computing it set-wise it can be extended to apply
to multilabel and multiclass through the use of average (see
above).
If there are more than two labels, hinge_loss uses a multiclass variant
due to Crammer & Singer.
Here is
the paper describing it.
In this case the predicted decision is an array of shape (n_samples,
n_labels). If wi,yi is the predicted decision for the true label
yi of the i-th sample; and
w^i,yi=max{wi,yj∣yj=yi}
is the maximum of the
predicted decisions for all the other labels, then the multi-class hinge loss
is defined by:
This extends to the multiclass case as follows.
Let the true labels for a set of samples
be encoded as a 1-of-K binary indicator matrix Y,
i.e., yi,k=1 if sample i has label k
taken from a set of K labels.
Let P^ be a matrix of probability estimates,
with elements p^i,k≈Pr(yi,k=1).
Then the log loss of the whole set is
To see how this generalizes the binary log loss given above,
note that in the binary case,
\hat{p}_{i,0} = 1 - \hat{p}_{i,1} and y_{i,0} = 1 - y_{i,1},
so expanding the inner sum over y_{i,k} \in \{0,1\}
gives the binary log loss.
The log_loss function computes log loss given a list of ground-truth
labels and a probability matrix, as returned by an estimator’s predict_proba
method.
When there are more than two labels, the value of the MCC will no longer range
between -1 and +1. Instead the minimum value will be somewhere between -1 and 0
depending on the number and distribution of ground truth labels. The maximum
value is always +1.
For additional information, see [WikipediaMCC2021].
Here is a small example illustrating the usage of the matthews_corrcoef
function:
Wikipedia contributors. Phi coefficient.
Wikipedia, The Free Encyclopedia. April 21, 2021, 12:21 CEST.
Available at: https://en.wikipedia.org/wiki/Phi_coefficient
Accessed April 21, 2021.
Here are some examples demonstrating the use of the
multilabel_confusion_matrix function to calculate recall
(or sensitivity), specificity, fall out and miss rate for each class in a
problem with multilabel indicator matrix input.
Calculating
recall
(also called the true positive rate or the sensitivity) for each class:
Compared to metrics such as the subset accuracy, the Hamming loss, or the
F1 score, ROC doesn’t require optimizing a threshold for each label.
The roc_auc_score function, denoted by ROC-AUC or AUROC, computes the
area under the ROC curve. By doing so, the curve information is summarized in
one number.
The following figure shows the ROC curve and ROC-AUC score for a classifier
aimed to distinguish the virginica flower from the rest of the species in the
Iris plants dataset:
In the binary case, you can either provide the probability estimates, using
the classifier.predict_proba() method, or the non-thresholded decision values
given by the classifier.decision_function() method. In the case of providing
the probability estimates, the probability of the class with the
“greater label” should be provided. The “greater label” corresponds to
classifier.classes_[1] and thus classifier.predict_proba(X)[:,1].
Therefore, the y_score parameter is of size (n_samples,).
Otherwise, we can use the non-thresholded decision values
>>> roc_auc_score(y,clf.decision_function(X))0.99
3.4.4.15.2. Multi-class case
The roc_auc_score function can also be used in multi-class
classification. Two averaging strategies are currently supported: the
one-vs-one algorithm computes the average of the pairwise ROC AUC scores, and
the one-vs-rest algorithm computes the average of the ROC AUC scores for each
class against all other classes. In both cases, the predicted labels are
provided in an array with values from 0 to n_classes, and the scores
correspond to the probability estimates that a sample belongs to a particular
class. The OvO and OvR algorithms support weighting uniformly
(average='macro') and by prevalence (average='weighted').
One-vs-one Algorithm
Computes the average AUC of all possible pairwise
combinations of classes. [HT2001] defines a multiclass AUC metric weighted
uniformly:
where c is the number of classes and \text{AUC}(j | k) is the
AUC with class j as the positive class and class k as the
negative class. In general,
\text{AUC}(j | k) \neq \text{AUC}(k | j) in the multiclass
case. This algorithm is used by setting the keyword argument multiclass
to 'ovo' and average to 'macro'.
The [HT2001] multiclass AUC metric can be extended to be weighted by the
prevalence:
where c is the number of classes. This algorithm is used by setting
the keyword argument multiclass to 'ovo' and average to
'weighted'. The 'weighted' option returns a prevalence-weighted average
as described in [FC2009].
One-vs-rest Algorithm
Computes the AUC of each class against the rest
[PD2000]. The algorithm is functionally the same as the multilabel case. To
enable this algorithm set the keyword argument multiclass to 'ovr'.
Additionally to 'macro'[F2006] and 'weighted'[F2001] averaging, OvR
supports 'micro' averaging.
In applications where a high false positive rate is not tolerable the parameter
max_fpr of can be used to summarize the ROC curve up
to the given limit.
3.4.4.15.3. Multi-label case
In multi-label classification, the roc_auc_score function is
extended by averaging over the labels as above. In this case,
you should provide a y_score of shape (n_samples,n_classes). Thus, when
using the probability estimates, one needs to select the probability of the
class with the greater label for each output.
DET curves form a linear curve in normal deviate scale if the detection
scores are normally (or close-to normally) distributed.
It was shown by [Navratil2007] that the reverse is not necessarily true and
even more general distributions are able to produce linear DET curves.
The normal deviate scale transformation spreads out the points such that a
comparatively larger space of plot is occupied.
Therefore curves with similar classification performance might be easier to
distinguish on a DET plot.
With False Negative Rate being “inverse” to True Positive Rate the point
of perfection for DET curves is the origin (in contrast to the top left
corner for ROC curves).
Applications and limitations
DET curves are intuitive to read and hence allow quick visual assessment of a
classifier’s performance.
Additionally DET curves can be consulted for threshold analysis and operating
point selection.
This is particularly helpful if a comparison of error types is required.
On the other hand DET curves do not provide their metric as a single number.
Therefore for either automated evaluation or comparison to other
classification tasks metrics like the derived area under ROC curve might be
better suited.
Examples
See Detection error tradeoff (DET) curve
for an example comparison between receiver operating characteristic (ROC)
curves and Detection error tradeoff (DET) curves.
J. Navratil and D. Klusacek,
“On Linear DETs”,
2007 IEEE International Conference on Acoustics,
Speech and Signal Processing - ICASSP ‘07, Honolulu,
HI, 2007, pp. IV-229-IV-232.
False
If \hat{y}_i is the predicted value of
the i-th sample and y_i is the corresponding true value,
then the 0-1 loss L_{0-1} is defined as:
The Brier score lies in the interval [0, 2] and the lower the value the
better the probability estimates are (the mean squared difference is smaller).
Actually, the Brier score is a strictly proper scoring rule, meaning that it
achieves the best score only when the estimated probabilities equal the
true ones.
Note that in the binary case, the Brier score is usually divided by two and
ranges between [0,1]. For binary targets y_i \in \{0, 1\} and
probability estimates \hat{p}_i \approx \operatorname{Pr}(y_i = 1)
for the positive class, the Brier score is then equal to:
The brier_score_loss function computes the Brier score given the
ground-truth labels and predicted probabilities, as returned by an estimator’s
predict_proba method. The scale_by_half parameter controls which of the
two above definitions to follow.
Analogously, the negative likelihood ratio LR_- is the probability of a
sample of the positive class being classified as belonging to the negative class
divided by the probability of a sample of the negative class being correctly
classified:
LR_- = \frac{\text{PR}(P-|T+)}{\text{PR}(P-|T-)}.
For classifiers above chance LR_+ above 1 higher is better, while
LR_- ranges from 0 to 1 and lower is better.
Values of LR_\pm\approx 1 correspond to chance level.
Notice that probabilities differ from counts, for instance
\operatorname{PR}(P+|T+) is not equal to the number of true positive
counts tp (see the wikipedia page for
the actual formulas).
On a given population, the pre-test probability is given by the prevalence. By
converting odds to probabilities, the likelihood ratios can be translated into a
probability of truly belonging to either class before and after a classifier
prediction:
The positive likelihood ratio (LR+) is undefined when fp=0, meaning the
classifier does not misclassify any negative labels as positives. This condition can
either indicate a perfect identification of all the negative cases or, if there are
also no true positive predictions (tp=0), that the classifier does not predict
the positive class at all. In the first case, LR+ can be interpreted as np.inf, in
the second case (for instance, with highly imbalanced data) it can be interpreted as
np.nan.
The negative likelihood ratio (LR-) is undefined when tn=0. Such
divergence is invalid, as LR_- > 1.0 would indicate an increase in the odds of
a sample belonging to the positive class after being classified as negative, as if the
act of classifying caused the positive condition. This includes the case of a
DummyClassifier that always predicts the positive class
(i.e. when tn=fn=0).
Both class likelihood ratios (LR+andLR-) are undefined when tp=fn=0, which
means that no samples of the positive class were present in the test set. This can
happen when cross-validating on highly imbalanced data and also leads to a division by
zero.
If a division by zero occurs and raise_warning is set to True (default),
class_likelihood_ratios raises an UndefinedMetricWarning and returns
np.nan by default to avoid pollution when averaging over cross-validation folds.
Users can set return values in case of a division by zero with the
replace_undefined_by param.
For a worked-out demonstration of the class_likelihood_ratios function,
see the example below.
Brenner, H., & Gefeller, O. (1997).
Variation of sensitivity, specificity, likelihood ratios and predictive
values with disease prevalence. Statistics in medicine, 16(9), 981-991.
where
\mathcal{L}_{ij} = \left\{k: y_{ik} = 1, \hat{f}_{ik} \geq \hat{f}_{ij} \right\},
\text{rank}_{ij} = \left|\left\{k: \hat{f}_{ik} \geq \hat{f}_{ij} \right\}\right|,
|\cdot| computes the cardinality of the set (i.e., the number of
elements in the set), and ||\cdot||_0 is the \ell_0 “norm”
(which computes the number of nonzero elements in a vector).
Here is a small example of usage of this function:
>>> importnumpyasnp>>> fromsklearn.metricsimportlabel_ranking_loss>>> y_true=np.array([[1,0,0],[0,0,1]])>>> y_score=np.array([[0.75,0.5,1],[1,0.2,0.1]])>>> label_ranking_loss(y_true,y_score)0.75>>> # With the following prediction, we have perfect and minimal loss>>> y_score=np.array([[1.0,0.1,0.2],[0.1,0.2,0.9]])>>> label_ranking_loss(y_true,y_score)0.0
References
Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In
Data mining and knowledge discovery handbook (pp. 667-685). Springer US.
For one sample, given the vector of continuous ground-truth values for each
target y \in \mathbb{R}^{M}, where M is the number of outputs, and
the prediction \hat{y}, which induces the ranking function f, the
DCG score is
Jarvelin, K., & Kekalainen, J. (2002).
Cumulated gain-based evaluation of IR techniques. ACM Transactions on
Information Systems (TOIS), 20(4), 422-446.
Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May).
A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th
Annual Conference on Learning Theory (COLT 2013)
McSherry, F., & Najork, M. (2008, March). Computing information retrieval
performance measures efficiently in the presence of tied scores. In
European conference on information retrieval (pp. 414-421). Springer,
Berlin, Heidelberg.
where \bar{y} = \frac{1}{n} \sum_{i=1}^{n} y_i and \sum_{i=1}^{n} (y_i - \hat{y}_i)^2 = \sum_{i=1}^{n} \epsilon_i^2.
Note that r2_score calculates unadjusted R^2 without correcting for
bias in sample variance of y.
In the particular case where the true target is constant, the R^2 score is
not finite: it is either NaN (perfect predictions) or -Inf (imperfect
predictions). Such non-finite scores may prevent correct model optimization
such as grid-search cross-validation to be performed correctly. For this reason
the default behaviour of r2_score is to replace them with 1.0 (perfect
predictions) or 0.0 (imperfect predictions). If force_finite
is set to False, this score falls back on the original R^2 definition.
Here is a small example of usage of the r2_score function:
See Gradient Boosting regression
for an example of mean squared error usage to evaluate gradient boosting regression.
Taking the square root of the MSE, called the root mean squared error (RMSE), is another
common metric that provides a measure in the same units as the target variable. RMSE is
available through the root_mean_squared_error function.
In above example, if we had used mean_absolute_error, it would have ignored
the small magnitude values and only reflected the error in prediction of highest
magnitude value. But that problem is resolved in case of MAPE because it calculates
relative percentage error with respect to actual output.
If \hat{y}_i is the predicted value of the i-th sample,
and y_i is the corresponding true value, then the mean Tweedie
deviance error (D) for power p, estimated over n_{\text{samples}}
is defined as
Tweedie deviance is a homogeneous function of degree 2-power.
Thus, Gamma distribution with power=2 means that simultaneously scaling
y_true and y_pred has no effect on the deviance. For Poisson
distribution power=1 the deviance scales linearly, and for Normal
distribution (power=0), quadratically. In general, the higher
power the less weight is given to extreme deviations between true
and predicted targets.
For instance, let’s compare the two predictions 1.5 and 150 that are both
50% larger than their corresponding true value.
The mean squared error (power=0) is very sensitive to the
prediction difference of the second point,:
It is also possible to build scorer objects for hyper-parameter tuning. The
sign of the loss must be switched to ensure that greater means better as
explained in the example linked below.
Examples
See Prediction Intervals for Gradient Boosting Regression
for an example of using the pinball loss to evaluate and tune the
hyper-parameters of quantile regression models on data with non-symmetric
noise and outliers.
The argument alpha defines the slope of the pinball loss as for
mean_pinball_loss (Pinball loss). It determines the
quantile level alpha for which the pinball loss and also D²
are optimal. Note that for alpha=0.5 (the default) d2_pinball_score
equals d2_absolute_error_score.
A scorer object with a specific choice of alpha can be built by:
When plotting the predictions of an estimator that predicts a quantile
of y given X, e.g. QuantileRegressor
or any other model minimizing the pinball loss, a
fraction of the points are either expected to lie above or below the diagonal
depending on the estimated quantile level.
All in all, while intuitive to read, this plot does not really inform us on
what to do to obtain a better model.
The right-hand side plot shows the residuals (i.e. the difference between the
actual and the predicted values) vs. the predicted values.
In particular, if the true distribution of y|X is Poisson or Gamma
distributed, it is expected that the variance of the residuals of the optimal
model would grow with the predicted value of E[y|X] (either linearly for
Poisson or quadratically for Gamma).
When fitting a linear least squares regression model (see
LinearRegression and
Ridge), we can use this plot to check
if some of the model assumptions
are met, in particular that the residuals should be uncorrelated, their
expected value should be null and that their variance should be constant
(homoschedasticity).
If this is not the case, and in particular if the residuals plot show some
banana-shaped structure, this is a hint that the model is likely misspecified
and that non-linear feature engineering or switching to a non-linear regression
model might be useful.
Refer to the example below to see a model evaluation that makes use of this
display.
The following figure shows the micro-averaged ROC curve and its corresponding
ROC-AUC score for a classifier aimed to distinguish the different species in
the Iris plants dataset: