A confusion matrix is a useful tool for evaluating the performance of a classification algorithm. In MATLAB, we can create a confusion matrix using the confusionmat()
function.
C = confusionmat(target,output)
The code above will take the following parameters:
target
is a vector of true class labels.output
is a vector of predicted class labels.Here’s an example of how to use the confusionmat()
function:
// Example ground truth and predicted labelsgroundTruth = [1 1 0 1 0 0 1 0 1 0];predictedLabels = [1 0 1 1 0 1 0 1 1 0];// Create confusion matrixC = confusionmat(groundTruth, predictedLabels)// Visualize confusion matrixconfusionchart(C)
In the example code above, we have ground truth labels in the groundTruth
variable and predicted labels in the predictedLabels
variable. We use these two variables as input to the confusionmat()
function to create a confusion matrix. To visualize the confusion matrix, we can use the confusionchart()
function, which creates a heatmap of the confusion matrix.
This will output the following confusion matrix:
True False
True 3 3
False 2 2
The output of the confusionmat()
function is a 2x2 matrix C
, where each row corresponds to the actual class and each column corresponds to the predicted class. The diagonal elements of the matrix represent the number of correctly classified samples, while the off-diagonal elements represent the number of misclassified samples.
// Example ground truth and predicted labels for three classesgroundTruth = [1 2 3 1 2 3 1 2 3];predictedLabels = [1 2 3 2 1 3 3 2 1];// Create confusion matrixC = confusionmat(groundTruth, predictedLabels)// Visualize confusion matrixlabels = {'Class 1', 'Class 2', 'Class 3'};confusionchart(C, labels)
In this example, we have ground truth and predicted labels for three classes. We create the confusion matrix using the confusionmat()
function and then visualize it using the confusionchart()
function, specifying the class labels.
This will output the following confusion matrix:
C =
1 1 1
1 2 0
1 0 2
The confusion matrix is displayed as a 3x3 matrix, where the rows represent the true classes (ground truth) and the columns represent the predicted classes. For example, the value at C(1,1)
represents the number of instances where the true class is 1 and it was correctly predicted as class 1 (true positive). Similarly, the value at C(2,3)
represents the number of instances where the true class is 2, but it was incorrectly predicted as class 3 (false negative).
Free Resources