dave
dave

Reputation: 151

Plot confusion matrix

I want to plot a confusion matrix in MATLAB. Here's my code;

data = rand(3, 3)
imagesc(data) 
colormap(gray) 
colorbar 

When I run this, a confusion matrix with a color bar is shown. But usually, I have seen confusion matrix in MATLAB will give counts as well as probabilities. How can I get them? How can I change the class labels which will be shown as 1,2,3, etc.?

I want a matrix like this:

Confusion matrix example

Upvotes: 1

Views: 9389

Answers (2)

Vahe Tshitoyan
Vahe Tshitoyan

Reputation: 1439

If you do not have the neural network toolbox, you can use plotConfMat. It gets you the following result.

Example Confusion Matrix

I have also included an independent example below without the need for the function:

% sample data
confmat = magic(3);
labels = {'Dog', 'Cat', 'Horse'};

numlabels = size(confmat, 1); % number of labels

% calculate the percentage accuracies
confpercent = 100*confmat./repmat(sum(confmat, 1),numlabels,1);

% plotting the colors
imagesc(confpercent);
title('Confusion Matrix');
ylabel('Output Class'); xlabel('Target Class');

% set the colormap
colormap(flipud(gray));

% Create strings from the matrix values and remove spaces
textStrings = num2str([confpercent(:), confmat(:)], '%.1f%%\n%d\n');
textStrings = strtrim(cellstr(textStrings));

% Create x and y coordinates for the strings and plot them
[x,y] = meshgrid(1:numlabels);
hStrings = text(x(:),y(:),textStrings(:), ...
    'HorizontalAlignment','center');

% Get the middle value of the color range
midValue = mean(get(gca,'CLim'));

% Choose white or black for the text color of the strings so
% they can be easily seen over the background color
textColors = repmat(confpercent(:) > midValue,1,3);
set(hStrings,{'Color'},num2cell(textColors,2));

% Setting the axis labels
set(gca,'XTick',1:numlabels,...
    'XTickLabel',labels,...
    'YTick',1:numlabels,...
    'YTickLabel',labels,...
    'TickLength',[0 0]);

Upvotes: 2

gregswiss
gregswiss

Reputation: 1456

If you have the neural network toolbox you can use the function plotconfusion. You can create a copy and edit it to customise it further, for example to print custom labels.

Upvotes: 0

Related Questions