主要借鉴此博客代码:http://blog.csdn.net/sherry_gp/article/details/50560003

但是这个博主的代码达不到我想要的效果,所以修改了一下

我想要实现的效果是:给定一列的预测标签,以及这一列标签的哪一部分理应属于哪一部分标签。

此代码实现的功能是:

给定条件:给定预测标签为A=[1 2 1 1 2 2 3 2 3 3 3 3 4 4 1 4];

每一类标签总数为num=[4 4 4 4](这里可以看出总共四类标签,每类标签的样本数为4);

四个类名:第一类、第二类、第三类、第四类

原始标签为:A=[1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4];

实现结果:每一类预测的准确率【也就是看A与B的差别在哪里】

代码【我修改的是compute_confusion_matrix.m,其余和借鉴的博主提供的代码一样】:

rotateXLabels.m

function hh = rotateXLabels( ax, angle, varargin )
%rotateXLabels: rotate any xticklabels
%
%   hh = rotateXLabels(ax,angle) rotates all XLabels on axes AX by an angle
%   ANGLE (in degrees). Handles to the resulting text objects are returned
%   in HH.
%
%   hh = rotateXLabels(ax,angle,param,value,...) also allows one or more
%   optional parameters to be specified. Possible parameters are:
%     'MaxStringLength'   The maximum length of label to show (default inf)
%
%   Examples:
%   >> bar( hsv(5)+0.05 )
%   >> days = {'Monday','Tuesday','Wednesday','Thursday','Friday'};
%   >> set( gca(), 'XTickLabel', days )
%   >> rotateXLabels( gca(), 45 )
%
%   See also: GCA
%             BAR%   Copyright 2006-2010 The MathWorks Ltd.
%   $Revision: 52 $
%   $Date: 2010-09-30 11:19:49 +0100 (Thu, 30 Sep 2010) $error( nargchk( 2, inf, nargin ) );
if ~isnumeric( angle ) || ~isscalar( angle )error( 'RotateXLabels:BadAngle', 'Parameter ANGLE must be a scalar angle in degrees' )
end
angle = mod( angle, 360 );[maxStringLength] = parseInputs( varargin{:} );% Get the existing label texts and clear them
[vals, labels] = findAndClearExistingLabels( ax, maxStringLength );% Create the new label texts
h = createNewLabels( ax, vals, labels, angle );% Reposition the axes itself to leave space for the new labelsrepositionAxes( ax );% If an X-label is present, move it too
repositionXLabel( ax );% Store angle
setappdata( ax, 'RotateXLabelsAngle', angle );% Only send outputs if requested
if nargouthh = h;
end%-------------------------------------------------------------------------%function [maxStringLength] = parseInputs( varargin )% Parse optional inputsmaxStringLength = inf;if nargin > 0params = varargin(1:2:end);values = varargin(2:2:end);if numel( params ) ~= numel( values )error( 'RotateXLabels:BadSyntax', 'Optional arguments must be specified as parameter-value pairs.' );endif any( ~cellfun( 'isclass', params, 'char' ) )error( 'RotateXLabels:BadSyntax', 'Optional argument names must be specified as strings.' );endfor pp=1:numel( params )switch upper( params{pp} )case 'MAXSTRINGLENGTH'maxStringLength = values{pp};otherwiseerror( 'RotateXLabels:BadParam', 'Optional parameter ''%s'' not recognised.', params{pp} );endendendend % parseInputs
%-------------------------------------------------------------------------%function [vals,labels] = findAndClearExistingLabels( ax, maxStringLength )% Get the current tick positions so that we can place our new labelsvals = get( ax, 'XTick' );% Now determine the labels. We look first at for previously rotated labels% since if there are some the actual labels will be empty.ex = findall( ax, 'Tag', 'RotatedXTickLabel' );if isempty( ex )% Store the positions and labelslabels = get( ax, 'XTickLabel' );if isempty( labels )% No labels!returnelseif ~iscell(labels)labels = cellstr(labels);endend% Clear existing labels so that xlabel is in the right positionset( ax, 'XTickLabel', {}, 'XTickMode', 'Manual' );setappdata( ax, 'OriginalXTickLabels', labels );else% Labels have already been rotated, so capture themlabels = getappdata( ax, 'OriginalXTickLabels' );delete(ex);end% Limit the length, if requestedif isfinite( maxStringLength )for ll=1:numel( labels )if length( labels{ll} ) > maxStringLengthlabels{ll} = labels{ll}(1:maxStringLength);endendendend % findAndClearExistingLabels%-------------------------------------------------------------------------%function textLabels = createNewLabels( ax, vals, labels, angle )% Work out the ticklabel positions
%         ylim = get(ax,'YLim');
%         y = ylim(1);zlim = get(ax,'ZLim');z = zlim(1);% We want to work% in normalised coords, but switch to normalised after setting% position causes positions to be rounded to the nearest pixel.% Instead we can do the calculation by hand.xlim = get( ax, 'XLim' );normVals = (vals-xlim(1))/(xlim(2)-xlim(1));y = 0;% Now create new text objects in similar positions. textLabels = -1*ones( numel( vals ), 1 );for ll=1:numel(vals)textLabels(ll) = text( ...'Units', 'Normalized', ...'Position', [normVals(ll), y, z], ...'String', labels{ll}, ...'Parent', ax, ...'Clipping', 'off', ...'Rotation', angle, ...'Tag', 'RotatedXTickLabel', ...'UserData', vals(ll) );end% Now copy font properties into the textsupdateFont();% Depending on the angle, we may need to change the alignment. We change% alignments within 5 degrees of each 90 degree orientation.if 0 <= angle && angle < 5set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Top' );elseif 5 <= angle && angle < 85set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Top' );elseif 85 <= angle && angle < 95set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Middle' );elseif 95 <= angle && angle < 175set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Bottom' );elseif 175 <= angle && angle < 185set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Bottom' );elseif 185 <= angle && angle < 265set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Bottom' );elseif 265 <= angle && angle < 275set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Middle' );elseif 275 <= angle && angle < 355set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Top' );else % 355-360set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Top' );endend % createNewLabels%-------------------------------------------------------------------------%function repositionAxes( ax )% Reposition the axes so that there's room for the labels% Note that we only do this if the OuterPosition is the thing being% controlledif ~strcmpi( get( ax, 'ActivePositionProperty' ), 'OuterPosition' )return;end% Work out the maximum height required for the labelstextLabels = findall( ax, 'Tag', 'RotatedXTickLabel' );maxHeight = 0;for ii=1:numel(vals)ext = get( textLabels(ii), 'Extent' );if ext(4) > maxHeightmaxHeight = ext(4);endend% Remove listeners while we mess around with things, otherwise we'll% trigger redraws recursivelyremoveListeners( ax );% Change to normalized units for the position calculationoldUnits = get( ax, 'Units' );set( ax, 'Units', 'Normalized' );% Not sure why, but the extent seems to be proportional to the height of the axes.% Correct that now.set( ax, 'ActivePositionProperty', 'Position' );pos = get( ax, 'Position' );axesHeight = pos(4);% Make sure we don't adjust away the axes entirely!heightAdjust = min( (axesHeight*0.9), maxHeight*axesHeight );% Move the axesif isappdata( ax, 'OriginalAxesPosition' )pos = getappdata( ax, 'OriginalAxesPosition' );elsepos = get(ax,'Position');setappdata( ax, 'OriginalAxesPosition', pos );endsetappdata( ax, 'PreviousYLim', get( ax, 'YLim' ) );set( ax, 'Position', pos+[0 heightAdjust 0 -heightAdjust] )set( ax, 'Units', oldUnits );set( ax, 'ActivePositionProperty', 'OuterPosition' );% Make sure we find out if axes properties are changedaddListeners( ax );end % repositionAxes%-------------------------------------------------------------------------%function repositionXLabel( ax )% Try to work out where to put the xlabelremoveListeners( ax );textLabels = findall( ax, 'Tag', 'RotatedXTickLabel' );maxHeight = 0;for ll=1:numel(vals)ext = get( textLabels(ll), 'Extent' );if ext(4) > maxHeightmaxHeight = ext(4);endend% Use the new max extent to move the xlabelxlab = get(ax,'XLabel');set( xlab, 'Units', 'Normalized', 'Position', [0.5 -maxHeight 0] );addListeners( ax );end % repositionXLabel%-------------------------------------------------------------------------%function updateFont()% Update the rotated text fonts when the axes font changesproperties = {'FontName''FontSize''FontAngle''FontWeight''FontUnits'};propertyValues = get( ax, properties );textLabels = findall( ax, 'Tag', 'RotatedXTickLabel' );set( textLabels, properties, propertyValues );end % updateFont%-------------------------------------------------------------------------%function onAxesFontChanged()updateFont();repositionAxes( ax );repositionXLabel( ax );end % onAxesFontChanged%-------------------------------------------------------------------------%function onAxesPositionChanged()% We need to accept the new position, so remove the appdata before% redrawingif isappdata( ax, 'OriginalAxesPosition' )rmappdata( ax, 'OriginalAxesPosition' );endif isappdata( ax, 'OriginalXLabelPosition' )rmappdata( ax, 'OriginalXLabelPosition' );endrepositionAxes( ax );repositionXLabel( ax );end % onAxesPositionChanged%-------------------------------------------------------------------------%function onAxesLimitsChanged()% The limits have moved, so make sure the labels are still oktextLabels = findall( ax, 'Tag', 'RotatedXTickLabel' );xlim = get( ax, 'XLim' );for tt=1:numel( textLabels )xval = get( textLabels(tt), 'UserData' );pos(1) = (xval-xlim(1)) / (xlim(2)-xlim(1));pos(2) = 0;% If the tick is off the edge, make it invisibleif xval<xlim(1) || xval>xlim(2)set( textLabels(tt), 'Visible', 'off', 'Position', pos )elseif ~strcmpi( get( textLabels(tt), 'Visible' ), 'on' )set( textLabels(tt), 'Visible', 'on', 'Position', pos )else% Just set the positionset( textLabels(tt), 'Position', pos );endendrepositionXLabel( ax );%         xlab = get(ax,'XLabel');
%         if ~strcmpi( get( xlab, 'Units' ), 'Data' )
%             set( xlab, 'Units', 'data' );
%         end
%         pos = get( xlab, 'Position' );
%         orig_yrange = diff( orig_ylim );
%         new_yrange = diff( ylim );
%         offset = (pos(2)-orig_ylim(1)) / orig_yrange;
%         pos(2) = offset * new_yrange + ylim(1);
%         pos(1) = mean( xlim );
%         set( xlab, 'Position', pos );
%         setappdata( ax, 'PreviousYLim', ylim );end % onAxesPositionChanged%-------------------------------------------------------------------------%function addListeners( ax )% Create listeners. We store the array of listeners in the axes to make% sure that they have the same life-span as the axes they are listening to.axh = handle( ax );listeners = [handle.listener( axh, findprop( axh, 'FontName' ), 'PropertyPostSet', @onAxesFontChanged )handle.listener( axh, findprop( axh, 'FontSize' ), 'PropertyPostSet', @onAxesFontChanged )handle.listener( axh, findprop( axh, 'FontWeight' ), 'PropertyPostSet', @onAxesFontChanged )handle.listener( axh, findprop( axh, 'FontAngle' ), 'PropertyPostSet', @onAxesFontChanged )handle.listener( axh, findprop( axh, 'FontUnits' ), 'PropertyPostSet', @onAxesFontChanged )handle.listener( axh, findprop( axh, 'OuterPosition' ), 'PropertyPostSet', @onAxesPositionChanged )handle.listener( axh, findprop( axh, 'XLim' ), 'PropertyPostSet', @onAxesLimitsChanged )handle.listener( axh, findprop( axh, 'YLim' ), 'PropertyPostSet', @onAxesLimitsChanged )];setappdata( ax, 'RotateXLabelsListeners', listeners );end % addListeners%-------------------------------------------------------------------------%function removeListeners( ax )% Rempove any property listeners whilst we are fiddling with the axesif isappdata( ax, 'RotateXLabelsListeners' )delete( getappdata( ax, 'RotateXLabelsListeners' ) );rmappdata( ax, 'RotateXLabelsListeners' );endend % removeListenersend % EOF

draw_cm.m

function draw_cm(mat,tick,num_class)
%%
%  Matlab code for visualization of confusion matrix;
%  Parameters:mat: confusion matrix;
%              tick: name of each class, e.g. 'class_1' 'class_2'...
%              num_class: number of class
%
%  Author: Page( 丕子)
%           Blog: www.shamoxia.com;
%           QQ:379115886;
%           Email: peegeelee@gmail.com
%%
imagesc(1:num_class,1:num_class,mat);            %# in color
colormap(flipud(gray));  %# for gray; black for large value.textStrings = num2str(mat(:),'%0.2f');
textStrings = strtrim(cellstr(textStrings));
[x,y] = meshgrid(1:num_class);
hStrings = text(x(:),y(:),textStrings(:), 'HorizontalAlignment','center');
midValue = mean(get(gca,'CLim'));
textColors = repmat(mat(:) > midValue,1,3);
set(hStrings,{'Color'},num2cell(textColors,2));  %# Change the text colorsset(gca,'xticklabel',tick,'XAxisLocation','top');
set(gca, 'XTick', 1:num_class, 'YTick', 1:num_class);
set(gca,'yticklabel',tick);
rotateXLabels(gca, 315 );% rotate the x tick

compute_confusion_matrix.m

function [confusion_matrix]=compute_confusion_matrix(predict_label,num_in_class,name_class)%预测标签,每一类的数目,类别数目
%predict_label为一维行向量
%num_in_class代表每一类的个数
%name_class代表类名
num_class=length(num_in_class);
num_in_class=[0 num_in_class];
confusion_matrix=size(num_class,num_class);for ci=1:num_classfor cj=1:num_classsummer=0;%统计对应标签个数c_start=sum(num_in_class(1:ci))+1;c_end=sum(num_in_class(1:ci+1));summer=size(find(predict_label(c_start:c_end)==cj),2);confusion_matrix(ci,cj)=summer/num_in_class(ci+1);end
enddraw_cm(confusion_matrix,name_class,num_class);end

测试代码:

testm.m

addpath('./ConfusionMatrices')
A=[1 2 1 1 2 2 3 2 3 3 3 3 4 4 1 4];
num=[4 4 4 4];
name=cell(1,4);
name{1}='haha';name{2}='hehe';name{3}='nani';name{4}='ok';
compute_confusion_matrix(A,num,name)

【附】直接用我借鉴的博客的代码得到的结果如下:

【混淆矩阵】matlab画混淆矩阵相关推荐

  1. 用MATLAB画混淆矩阵 --2018/11/24

    今天在用SVM进行分类的时候,需要用到混淆矩阵对结果进行评价,于是上网搜了怎么画混淆矩阵,但是由于不怎么懂MATLAB代码,都看不懂他们写的代码,最后还是看了一下老师之前给的代码,我奔溃了,因为MAT ...

  2. Matlab画混淆矩阵(多分类)

    在神经网络和机器学习的结果分析中,常常会用混淆矩阵和ROC曲线来分析识别/分类结果的好坏,而且论文中也经常出现这种图.对于卷积神经网络来说画混淆矩阵很简单,要用到函数plotconfusion,格式为 ...

  3. matlab建立一个三维矩阵,matlab创建三维矩阵

    <matlab创建三维矩阵>由会员分享,可在线阅读,更多相关<matlab创建三维矩阵(6页珍藏版)>请在人人文库网上搜索. 1.创建三维矩阵的几种方法一下标法1.三维矩阵的创 ...

  4. matlab 怎么打矩阵,matlab怎么打印矩阵 matlab 如何输出矩阵?

    matlab 如何输出矩阵 a %注意变量a后面没有";"号,即可输出disp(a) Matlab常用生成矩阵函数: zeros(m,n) 生成一个 m 行 n 列的零矩阵,m=n ...

  5. 利用matlab画混淆矩阵(confusion matrix)

    写论文的过程中经常需要画一个混淆矩阵(confusion matrix)来验证分类结果的有效性.通常只需要两个步骤: - 保存混淆矩阵文本文件 - matlab中使用imagesc命令 例如: > ...

  6. matlab怎么导出矩阵,matlab 如何输出矩阵?

    a %注意变量a后面没有";"号,即可输出disp(a) Matlab常用生成矩阵函数: zeros(m,n) 生成一个 m 行 n 列的零矩阵,m=n 时可简写为 zeros(n ...

  7. matlab中数字除以矩阵,Matlab中的矩阵除法有问题???

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 x=rand(5) x = 0.5470    0.1835    0.9294    0.3063    0.6443 0.2963    0.3685 ...

  8. matlab 求取矩阵中值,matlab中取矩阵中指定列的值组成新矩阵

    matlab 矩阵中怎么加入冒号,比如我想矩阵A的第一列都为"1:" A(:,1)='1:';再问:不行的再答:用结构矩阵或者单元矩阵试试吧. 诚教:matlab中取矩阵的其中几行 ...

  9. MATLAB中复数矩阵的转置、共轭及共轭转置

    参考博客:https://blog.csdn.net/zhaozhichenghpu/article/details/79162287 MATLAB中生成一个复数矩阵 MATLAB中复数矩阵的共轭用c ...

最新文章

  1. 再见!人人影视...
  2. Oracle临时表和SQL Server临时表的不同点对比
  3. JavaEE5种常见的设计模式
  4. java intfilter_Java IntStream filter()用法及代码示例
  5. Npoi导出excel整理(附源码)
  6. XL, an extensible programming language, implements concept programming
  7. 【github相关】之h264bitstream
  8. escilpse 连接mysql,浅谈docker-compose网络设置之networks
  9. java pdfbox 提取pdf 标题_java – 使用pdfbox从PDF文件中提取文本
  10. TypeError: Fetch argument has invalid type class ‘numpy.float32‘, must be a string or Tensor
  11. pands 画图 调整大小_两个精品案例解释机械设计的步骤,有思路,再着手画图...
  12. 工程控制论 理论概况
  13. 计算机网络体系结构(详图)
  14. 弹幕助手连接不到服务器,小葫芦obs弹幕助手怎么用 OBS弹幕助手使用教程
  15. 7-1 愿天下有情人都是失散多年的兄妹 --DFS
  16. 分部积分出现积回去的情况
  17. 计算机专业毕业设计致谢,计算机专业毕业论文致谢范文
  18. python抓取小红书_小红书很难爬?最新爬取方法教给你啦~
  19. MySQL数据库字符串(单行)函数#concat、length、tirm、replace、strcmp、substr等函数总结
  20. 猫学习IOS(四)UI半小时就搞定Tom猫

热门文章

  1. 红帽linux配置apache,红帽linux9中Apache服务器的配置
  2. Ubuntu apt upgrade后黑屏问题
  3. oracle自带调优,oracle 参数调优
  4. 服务器位置缩写,服务器地区缩写
  5. 深度学习之循环神经网络(3)梯度传播
  6. mysql版本 hibernate_Mysql 不同版本 说明
  7. Cache超清晰逻辑详解(cache的三种映射)
  8. linux usb xhci ehci,ehci和xhci有什么区别
  9. Codeforce-Ozon Tech Challenge 2020-C. Kuroni and Impossible Calculation(鸽笼原理)
  10. 数学--数论--四大定理之威尔逊定理