annotate toolboxes/MIRtoolbox1.3.2/somtoolbox/knn.m @ 0:cc4b1211e677 tip

initial commit to HG from Changeset: 646 (e263d8a21543) added further path and more save "camirversion.m"
author Daniel Wolff
date Fri, 19 Aug 2016 13:07:06 +0200
parents
children
rev   line source
Daniel@0 1 function [C,P]=knn(d, Cp, K)
Daniel@0 2
Daniel@0 3 %KNN K-Nearest Neighbor classifier using an arbitrary distance matrix
Daniel@0 4 %
Daniel@0 5 % [C,P]=knn(d, Cp, [K])
Daniel@0 6 %
Daniel@0 7 % Input and output arguments ([]'s are optional):
Daniel@0 8 % d (matrix) of size NxP: This is a precalculated dissimilarity (distance matrix).
Daniel@0 9 % P is the number of prototype vectors and N is the number of data vectors
Daniel@0 10 % That is, d(i,j) is the distance between data item i and prototype j.
Daniel@0 11 % Cp (vector) of size Px1 that contains integer class labels. Cp(j) is the class of
Daniel@0 12 % jth prototype.
Daniel@0 13 % [K] (scalar) the maximum K in K-NN classifier, default is 1
Daniel@0 14 % C (matrix) of size NxK: integers indicating the class
Daniel@0 15 % decision for data items according to the K-NN rule for each K.
Daniel@0 16 % C(i,K) is the classification for data item i using the K-NN rule
Daniel@0 17 % P (matrix) of size NxkxK: the relative amount of prototypes of
Daniel@0 18 % each class among the K closest prototypes for each classifiee.
Daniel@0 19 % That is, P(i,j,K) is the relative amount of prototypes of class j
Daniel@0 20 % among K nearest prototypes for data item i.
Daniel@0 21 %
Daniel@0 22 % If there is a tie between representatives of two or more classes
Daniel@0 23 % among the K closest neighbors to the classifiee, the class i selected randomly
Daniel@0 24 % among these candidates.
Daniel@0 25 %
Daniel@0 26 % IMPORTANT If K>1 this function uses 'sort' which is considerably slower than
Daniel@0 27 % 'max' which is used for K=1. If K>1 the knn always calculates
Daniel@0 28 % results for all K-NN models from 1-NN up to K-NN.
Daniel@0 29 %
Daniel@0 30 % EXAMPLE 1
Daniel@0 31 %
Daniel@0 32 % sP; % a SOM Toolbox data struct containing labeled prototype vectors
Daniel@0 33 % [Cp,label]=som_label2num(sP); % get integer class labels for prototype vectors
Daniel@0 34 % sD; % a SOM Toolbox data struct containing vectors to be classified
Daniel@0 35 % d=som_eucdist2(sD,sP); % calculate euclidean distance matrix
Daniel@0 36 % class=knn(d,Cp,10); % classify using 1,2,...,10-rules
Daniel@0 37 % class(:,5); % includes results for 5NN
Daniel@0 38 % label(class(:,5)) % original class labels for 5NN
Daniel@0 39 %
Daniel@0 40 % EXAMPLE 2 (leave-one-out-crossvalidate KNN for selection of proper K)
Daniel@0 41 %
Daniel@0 42 % P; % a data matrix of prototype vectors (rows)
Daniel@0 43 % Cp; % column vector of integer class labels for vectors in P
Daniel@0 44 % d=som_eucdist2(P,P); % calculate euclidean distance matrix PxP
Daniel@0 45 % d(eye(size(d))==1)=NaN; % set self-dissimilarity to NaN:
Daniel@0 46 % % this drops the prototype itself away from its neighborhood
Daniel@0 47 % % leave-one-out-crossvalidation (LOOCV)
Daniel@0 48 % class=knn(d,Cp,size(P,1)); % classify using all possible K
Daniel@0 49 % % calculate and plot LOOC-validated errors for all K
Daniel@0 50 % failratep = ...
Daniel@0 51 % 100*sum((class~=repmat(Cp,1,size(P,1))))./size(P,1); plot(1:size(P,1),failratep)
Daniel@0 52
Daniel@0 53 % See also SOM_LABEL2NUM, SOM_EUCDIST2, PDIST.
Daniel@0 54 %
Daniel@0 55 % Contributed to SOM Toolbox 2.0, October 29th, 2000 by Johan Himberg
Daniel@0 56 % Copyright (c) by Johan Himberg
Daniel@0 57 % http://www.cis.hut.fi/projects/somtoolbox/
Daniel@0 58
Daniel@0 59 % Version 2.0beta Johan 291000
Daniel@0 60
Daniel@0 61 %% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Daniel@0 62
Daniel@0 63 % Check K
Daniel@0 64 if nargin<3 | isempty(K),
Daniel@0 65 K=1;
Daniel@0 66 end
Daniel@0 67
Daniel@0 68 if ~vis_valuetype(K,{'1x1'})
Daniel@0 69 error('Value for K must be a scalar');
Daniel@0 70 end
Daniel@0 71
Daniel@0 72 % Check that dist is a matrix
Daniel@0 73 if ~vis_valuetype(d,{'nxm'}),
Daniel@0 74 error('Distance matrix not valid.')
Daniel@0 75 end
Daniel@0 76
Daniel@0 77 [N_data N_proto]=size(d);
Daniel@0 78
Daniel@0 79 % Check class label vector: must be numerical and of integers
Daniel@0 80 if ~vis_valuetype(Cp,{[N_proto 1]});
Daniel@0 81 error(['Class vector is invalid: has to be a N-of-data_rows x 1' ...
Daniel@0 82 ' vector of integers']);
Daniel@0 83 elseif sum(fix(Cp)-Cp)~=0
Daniel@0 84 error('Class labels in vector ''Cp'' must be integers.');
Daniel@0 85 end
Daniel@0 86
Daniel@0 87 if size(d,2) ~= length(Cp),
Daniel@0 88 error('Distance matrix and prototype class vector dimensions do not match.');
Daniel@0 89 end
Daniel@0 90
Daniel@0 91 % Check if the classes are given as labels (no class input arg.)
Daniel@0 92 % if they are take them from prototype struct
Daniel@0 93
Daniel@0 94 % Find all class labels
Daniel@0 95 ClassIndex=unique(Cp);
Daniel@0 96 N_class=length(ClassIndex); % number of different classes
Daniel@0 97
Daniel@0 98
Daniel@0 99 %%%% Classification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Daniel@0 100
Daniel@0 101 if K==1, % sort distances only if K>1
Daniel@0 102
Daniel@0 103 % 1NN
Daniel@0 104 % Select the closest prototype
Daniel@0 105 [tmp,proto_index]=min(d,[],2);
Daniel@0 106 C=Cp(proto_index);
Daniel@0 107
Daniel@0 108 else
Daniel@0 109
Daniel@0 110 % Sort the prototypes for each classifiee according to distance
Daniel@0 111 [tmp, proto_index]=sort(d');
Daniel@0 112
Daniel@0 113 %% Select up to K closest prototypes
Daniel@0 114 proto_index=proto_index(1:K,:);
Daniel@0 115 knn_class=Cp(proto_index);
Daniel@0 116 for i=1:N_class,
Daniel@0 117 classcounter(:,:,i)=cumsum(knn_class==ClassIndex(i));
Daniel@0 118 end
Daniel@0 119
Daniel@0 120 %% Vote between classes of K neighbors
Daniel@0 121 [winner,vote_index]=max(classcounter,[],3);
Daniel@0 122
Daniel@0 123 %%% Handle ties
Daniel@0 124
Daniel@0 125 % Set index to classes that got as much votes as winner
Daniel@0 126
Daniel@0 127 equal_to_winner=(repmat(winner,[1 1 N_class])==classcounter);
Daniel@0 128
Daniel@0 129 % set index to ties
Daniel@0 130 [tie_indexi,tie_indexj]=find(sum(equal_to_winner,3)>1); % drop the winner from counter
Daniel@0 131
Daniel@0 132 % Go through tie cases and reset vote_index randomly to one
Daniel@0 133 % of them
Daniel@0 134
Daniel@0 135 for i=1:length(tie_indexi),
Daniel@0 136 tie_class_index=find(squeeze(equal_to_winner(tie_indexi(i),tie_indexj(i),:)));
Daniel@0 137 fortuna=randperm(length(tie_class_index));
Daniel@0 138 vote_index(tie_indexi(i),tie_indexj(i))=tie_class_index(fortuna(1));
Daniel@0 139 end
Daniel@0 140
Daniel@0 141 C=ClassIndex(vote_index)';
Daniel@0 142 end
Daniel@0 143
Daniel@0 144 %% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Daniel@0 145
Daniel@0 146 % Relative amount of classes in K neighbors for each classifiee
Daniel@0 147
Daniel@0 148 if K==1,
Daniel@0 149 P=zeros(N_data,N_class);
Daniel@0 150 if nargout>1,
Daniel@0 151 for i=1:N_data,
Daniel@0 152 P(i,ClassIndex==C(i))=1;
Daniel@0 153 end
Daniel@0 154 end
Daniel@0 155 else
Daniel@0 156 P=shiftdim(classcounter,1)./repmat(shiftdim(1:K,-1), [N_data N_class 1]);
Daniel@0 157 end
Daniel@0 158