AbstractIn this vignette, we learn how to create and plot a confusion matrix from a set of classification predictions. The functions of interest are
When inspecting a classification model’s performance, a confusion matrix tells you the distribution of the predictions and targets.
If we have two classes (0, 1), we have these 4 possible combinations of predictions and targets:
* Given that
1 is the positive class.
For each combination, we can count how many times the model made that prediction for an observation with that target. This is often more useful than the various metrics, as it reveals any class imbalances and tells us which classes the model tend to confuse.
An accuracy score of 90% may, for instance, seem very high. Without the context though, this is impossible to judge. It may be, that the test set is so highly imbalanced that simply predicting the majority class yields such an accuracy. When looking at the confusion matrix, we discover many of such problems and gain a much better intuition about our model’s performance.
In this vignette, we will learn three approaches to making and plotting a confusion matrix. First, we will manually create it with the
table() function. Then, we will use the
evaluate() function from
cvms. This is our recommended approach in most use cases. Finally, we will use the
confusion_matrix() function from
cvms. All approaches result in a data frame with the counts for each combination. We will plot these with
plot_confusion_matrix() and make a few tweaks to the plot.
We will start with a binary classification example. For this, we create a data frame with targets and predictions:
Before taking the recommended approach, let’s first create the confusion matrix manually. Then, we will simplify the process with first
evaluate() and then
confusion_matrix(). In most cases, we recommend that you use
Given the simplicity of our data frame, we can quickly get a confusion matrix table with
In order to plot it with
ggplot2, we convert it to a data frame with
We can now plot it with
In the middle of each tile, we have the normalized count (overall percentage) and, beneath it, the count.
At the bottom, we have the column percentage. Of all the observations where
1, 63.2% of them were predicted to be
1 and 36.8%
At the right side of each tile, we have the row percentage. Of all the observations where
1, 71.7% of them were actually
1, while 28.3% were
Note that the color intensity is based on the counts.
Now, let’s use the
evaluate() function to evaluate the predictions and get the confusion matrix tibble:
eval <- evaluate(d_binomial, target_col = "target", prediction_cols = "prediction", type = "binomial") eval #> # A tibble: 1 x 19 #> `Balanced Accur… Accuracy F1 Sensitivity Specificity `Pos Pred Value` #> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> #> 1 0.551 0.580 0.672 0.632 0.469 0.717 #> # … with 13 more variables: `Neg Pred Value` <dbl>, AUC <dbl>, `Lower #> # CI` <dbl>, `Upper CI` <dbl>, Kappa <dbl>, MCC <dbl>, `Detection #> # Rate` <dbl>, `Detection Prevalence` <dbl>, Prevalence <dbl>, #> # Predictions <list>, ROC <named list>, `Confusion Matrix` <list>, #> # Process <list>
The output contains the confusion matrix tibble:
Compared to the manually created version, we have two extra columns,
Pos_1. These describe whether the row is the True Positive, True Negative, False Positive, or False Negative, depending on which class (0 or 1) is the positive class.
Once again, we can plot it with
A third approach is to use the
confusion_matrix() function. It is a lightweight alternative to
evaluate() with fewer features. As a matter of fact,
evaluate() uses it internally! Let’s try it on a multiclass classification task.
Create a data frame with targets and predictions:
evaluate() takes a data frame as input,
confusion_matrix() takes a vector of targets and a vector of predictions:
conf_mat <- confusion_matrix(targets = d_multi$target, predictions = d_multi$prediction) conf_mat #> # A tibble: 1 x 15 #> `Confusion Matr… Table `Class Level Re… `Overall Accura… `Balanced Accur… #> <list> <lis> <list> <dbl> <dbl> #> 1 <tibble [9 × 3]> <tab… <tibble [3 × 14… 0.34 0.502 #> # … with 10 more variables: F1 <dbl>, Sensitivity <dbl>, Specificity <dbl>, #> # `Pos Pred Value` <dbl>, `Neg Pred Value` <dbl>, Kappa <dbl>, MCC <dbl>, #> # `Detection Rate` <dbl>, `Detection Prevalence` <dbl>, Prevalence <dbl>
The output includes the confusion matrix tibble and related metrics.
Let’s plot the multiclass confusion matrix:
If we are interested in the overall distribution of predictions and targets, we can add a column to the right side of the plot with the row sums and a row at the bottom with the column sums. We refer to these as the sum tiles.
The tile in the corner contains the total count of data points.
Let’s explore how we can tweak the plot.
While the defaults of
plot_confusion_matrix() should (hopefully) be useful in most cases, it is very flexible. For instance, you may prefer to have the “Target” label at the bottom of the plot:
If we only want the counts in the middle of the tiles, we can disable the normalized counts (overall percentages):
We can choose one of the other available color palettes.
You can find the available sequential palettes at
When we have the sum tiles enabled, we can change the label to
Total, add a border around the total count tile and change the palette responsible for the color of the sum tiles. Here we use
sum_tile_settings() to quickly choose the settings we want:
Finally, let’s try tweaking the font settings for the counts. For this, we use the
font() helper function.
Let’s disable all the percentages and make the counts big, red and angled 45 degrees:
We could have chosen those settings as the defaults, but chose against it with a coin flip!
Now you know how to create and plot a confusion matrix with