%%生成混淆矩阵
%给定原有测试标签
test_label = [1 2 3 1 3 4 2 2 2 2 3 4 1 1];
%给定预测标签
presict_label = [1 2 3 1 1 1 2 2 2 2 3 4 1 3];
confusion_matrix = confusionmat( test_label ,presict_label);
%%绘制混淆矩阵
%%绘制混淆矩阵
sum = sum(confusion_matrix,2);
[m,n] = size(confusion_matrix);
for i =1: m
confusion_matrix(i,:)=confusion_matrix(i,:)/sum(i)
end
draw_cm(confusion_matrix);
xticks([1 2 3 4 5 ]);
yticks([1 2 3 4 5 ]);
function draw_cm(mat)
%%
% 参数:mat-矩阵;tick-要在坐标轴上显示的label向量,例如{‘label_1’,‘label_2’…}
%
%%
imagesc(mat); %# 绘彩色图
colormap(flipud(hot));
colorbar;
num_class = size(mat,1);
midValue = mean(get(gca, ‘CLim’ ));
[x,y] = meshgrid(0:num_class+1);
%% 画中间的虚线
% a = 180;
% for i=1:num_class+2
% hold on
% plot(x(i, ?, y(i, ?, ‘Color’, [a a a]/255, ‘LineStyle’, ‘–’); % ‘–’
% plot(y(i, ?, x(i, ?, ‘Color’, [a a a]/255, ‘LineStyle’, ‘–’);
% end文章来源:https://uudwc.com/A/d9W0
%% 写字
for i=1:num_class
for j=1:num_class
if not (isnan(mat(i, j)))
textStrings = num2str(mat(i, j), ‘%0.1f’);
if mat(i, j) < 1
textStrings = textStrings(2: 3);
elseif mat(i, j) > 90
textStrings = textStrings(2: 4);
else
textStrings = textStrings;
end
textStrings = strtrim(cellstr(textStrings));
hStrings = text(j,i,textStrings(?, ‘HorizontalAlignment’ , ‘center’, ‘FontSize’, 11, ‘FontWeight’, ‘normal’ );
textColors = repmat(mat(i, j) > midValue,1,3);
%改变test的颜色,在黑cell里显示白色
set(hStrings,{ ‘Color’ },num2cell(textColors,2)); %# Change the text colors
end
end
end文章来源地址https://uudwc.com/A/d9W0