【混淆矩阵】matlab画混淆矩阵

主要借鉴此博客代码: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)


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



本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/246697.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【caffe-Windows】mnist实例编译之model的生成

其实这个和cifar的实例基本相同&#xff0c;只不过数据转换的方法不一样 【说明&#xff0c;此博客按照我自己的路径设置的相关操作&#xff0c;读者如果自行选择其他路径&#xff0c;记得在bat和prototxt等文件修改路径】 第一步 下载数据集THE MNIST DATABASE of handwrit…

吉布斯采样——原理及matlab实现

原文来自&#xff1a;https://victorfang.wordpress.com/2014/04/29/mcmc-the-gibbs-sampler-simple-example-w-matlab-code/ 【注】评论区有同学指出译文理论编码有误&#xff0c;请参考更官方的文献&#xff0c;个人当时仅验证过红色字体部分理论与维基百科中二位随机变量吉…

【matlab知识补充】conv2、filter2、imfilter函数原理

原文地址&#xff1a;http://www.ilovematlab.cn/thread-293710-1-1.html -------------------------------------conv2函数---------------------------------------- 1、用法 Cconv2(A,B,shape); %卷积滤波 复制代码A:输入图像&#xff0c;B:卷积核假设输入图像A大…

显示mnist手写数字

前言 可视化什么的&#xff0c;总是好的 方法一 其实也就是用到了Ruslan Salakhutdinov and Geoff Hinton提供的工具包 % Version 1.000 % % Code provided by Ruslan Salakhutdinov and Geoff Hinton % % Permission is granted for anyone to copy, use, modify, or distr…

【caffe-Windows】mnist实例编译之model的使用-classification

仿照cifar10的模型使用&#xff0c;本文对mnist的训练方式做了部分修改 【注】本文caffe安装路径为E:\CaffeDev-GPU\caffe-master。请自行参考并修改相关路径(debug以及release参考你编译caffe时候采用的模式) 第一步 按照前面的model生成方法的前两步骤制作数据集&#xff…

误差error,偏置bias,方差variance的见解

更新日志&#xff1a;2020-3-10 谢谢ProQianXiao的指正。偏差-方差的确是在测试集中进行的。 之前的误解是&#xff0c;偏差和方差的计算是同一个模型对不同样本的预测结果的偏差和方差&#xff1b;而实际上是不同模型对同一个样本的预测结果的偏差和方差。 这时候就要祭出网…

【caffe-Windows】以mnist为例lmdb格式数据

前言 前面介绍的案例都是leveldb的格式&#xff0c;但是比较流行和实用的格式是lmdb&#xff0c;原因从此网站摘取 它们都是键/值对&#xff08;Key/Value Pair&#xff09;嵌入式数据库管理系统编程库。虽然lmdb的内存消耗是leveldb的1.1倍&#xff0c;但是lmdb的速度比level…

【caffe-Windows】mnist实例编译之model的使用-matlab

前言 针对上一个caffe文章留下的matlab手写数字识别的问题&#xff0c;感谢caffe中文社区的 ghgzh 的提示&#xff0c;原文请看&#xff1a;caffe中文社区 第一步 手写图片的制作方法我就不说了&#xff0c;直接把我自己画的几个数字放到云盘先&#xff1a; 三通道图像以及…

【caffe-Windows】训练自己数据——数据集格式转换

前言 看了mnist和cifar的实例&#xff0c;是不是想我们现实中一般都是一张张的图片&#xff0c;和实例里面都不一样呢&#xff1f;那么如何来进行训练呢&#xff1f;为了能够简便点&#xff0c;我们就不自己去采集数据集了&#xff0c;因为第一自己采集的数据集量可能不够&…

【caffe-windows】Linux至Windows平台的caffe移植

1、前言 主要参考两篇博客以及很多论坛解决细节问题&#xff1a; http://www.cnblogs.com/trantor/p/4570097.html https://initialneil.wordpress.com/2015/01/11/build-caffe-in-windows-with-visual-studio-2013-cuda-6-5-opencv-2-4-9/ 移植环境&#xff1a;Windows7…

【caffe-matlab】权重以及特征图的可视化

前言 移植了各种caffe&#xff0c;是时候进行下一步操作了&#xff0c;先拿可视化下手吧。大部分内容可能跟网上的方法不一样&#xff0c;大家看完我的博客最好去网上看看大牛们的博客&#xff0c;万一被我误导了&#xff0c;就罪过了o(╯□╰)o&#xff0c;开更.............…

【caffe-matlab】使用matlab训练caffe及绘制loss

前言 此博客主要介绍如何利用matlab一步一步训练caffe模型&#xff0c;类似使用caffe.exe 的train命令。 国际惯例&#xff0c;参考博客&#xff1a; http://caffe.berkeleyvision.org/tutorial/interfaces.html http://www.cnblogs.com/denny402/p/5110204.html 抱怨一…

【caffe-matlab】目标检测R-FCN算法于Windows下配置

前言 首先谢谢好友推荐的这篇论文及代码&#xff0c;前面学习的caffe可能比较浅显&#xff0c;想要深入caffe就可以从这个代码下手了&#xff0c;配置方法还是挺简单的&#xff0c;但是可能会出现部分问题。在作者的论文中有github的地址。注意&#xff0c;本文只介绍如何配置…

【写作】Texlive和Texmaker学习

前言 最近要看一些论文做一下笔记&#xff0c;所以准备使用一下比较流行的Texlive和Texmaker写一下。其实CSDN的Markdown也是不错滴。 首先国际惯例&#xff0c;贴几个地址&#xff1a; Texlive镜像下载地址&#xff1a;http://mirror.lzu.edu.cn/CTAN/systems/texlive/Imag…

《Neural Networks for Machine Learning》学习一

前言 最近报了一下Hinton大牛的coursera的神经网络课程&#xff0c;奈何比较懒&#xff0c;一直没看&#xff0c;还是写个博客督促自己比较好 贴一下课程地址&#xff1a;https://www.coursera.org/learn/neural-networks/home/week/1 第一讲主题是为何需要机器学习&#xf…

《Neural Networks for Machine Learning》学习二

前言 课程地址&#xff1a;https://www.coursera.org/learn/neural-networks/home/week/1‘’ 【Lecture 2】百度云下载地址&#xff1a;链接&#xff1a;http://pan.baidu.com/s/1nvMynhR 密码&#xff1a;ru3y 神经网络架构概览 前馈神经网络(Feed-Forward neural network)…

入门 | 初学者必读:解读14个深度学习关键词

作者&#xff1a;Matthew Mayo 机器之心编译 参与&#xff1a;Xuwen Wang、Chen Chen 微信公众号&#xff1a;&#xff08;almosthuman2014&#xff09;授权转载&#xff0c;禁止二次转载&#xff0c;点此为原文链接 本文介绍了包括 LSTM、ANNS、生物神经元、反向传播、多元感知…

深度 | 一篇文章带你进入无监督学习:从基本概念到四种实现模型(附论文)

作者&#xff1a;Eugenio Culurciello 机器之心编译 参与&#xff1a;李亚洲、武竞 微信公众号&#xff1a;&#xff08;almosthuman2014&#xff09;授权转载&#xff0c;禁止二次转载&#xff0c;点此为原文链接 这是今年 6 月份普渡大学副教授 Eugenio Culurciello 写的一篇…

【caffe-Windows】微软官方caffe之 Python接口配置及图片生成实例

前言 发现许多代码还是用python写的&#xff0c;所以还是配置一下接口吧&#xff0c;虽然博主不会Python&#xff0c;咳咳。在这里使用的python安装包是anaconda2&#xff0c;注意使用Python2.7版本的那个安装包。 官网地址&#xff1a;https://www.continuum.io/downloads …

判别模型的玻尔兹曼机论文源码解读

前言 三号要去参加CAD/CG会议&#xff0c;投了一篇关于使用生成模型和判别模型的RBM做运动捕捉数据风格识别的论文。这段时间一直搞卷积RBM了&#xff0c;差点把原来的实验内容都忘记了&#xff0c;这里复习一下判别式玻尔兹曼机的训练流程。 国际惯例&#xff0c;贴几个链接…