1 | %KDNNC 1-Nearest Neighbor Classifier using KDTree |
---|
2 | % |
---|
3 | % W = KNNC(A,TYPE) |
---|
4 | % |
---|
5 | % INPUT |
---|
6 | % A Dataset |
---|
7 | % TYPE 'fast' (default) or 'good' |
---|
8 | % |
---|
9 | % OUTPUT |
---|
10 | % W NN classifier using KDTree for finding nearest neighbors |
---|
11 | % |
---|
12 | % DESCRIPTION |
---|
13 | % This is a KD-Tree nearest neighbor implementation for PRTools using the |
---|
14 | % KD-Tree package by Pramod Vemulapalli, see |
---|
15 | % http://www.mathworks.com/matlabcentral/fileexchange/26649-kdtree-implementation-in-matlab |
---|
16 | % It should be in the Matlab search path. |
---|
17 | % |
---|
18 | % SEE ALSO |
---|
19 | % MAPPINGS, DATASETS, KNNC |
---|
20 | |
---|
21 | % Copyright: R.P.W. Duin, r.p.w.duin@prtools.org |
---|
22 | % Faculty EWI, Delft University of Technology |
---|
23 | % P.O. Box 5031, 2600 GA Delft, The Netherlands |
---|
24 | |
---|
25 | |
---|
26 | function out = kdnnc(a,par) |
---|
27 | |
---|
28 | prtrace(mfilename); |
---|
29 | |
---|
30 | kdtreecheck; |
---|
31 | name = 'KDTree NN Classifier'; |
---|
32 | % No input data, return an untrained classifier. |
---|
33 | if nargin < 2, par = 'good'; end |
---|
34 | if (nargin == 0) | (isempty(a)) |
---|
35 | out = mapping(mfilename,'untrained',par); |
---|
36 | out = setname(out,name); |
---|
37 | elseif isdataset(a) & isstr(par) % training |
---|
38 | if isempty(strmatch(par,char('fast','good'))) |
---|
39 | error('KDTree type should be either ''fast'' or ''good''') |
---|
40 | end |
---|
41 | islabtype(a,'crisp'); |
---|
42 | isvaldfile(a,1,2); % at least 1 object per class, 2 classes |
---|
43 | a = testdatasize(a); |
---|
44 | a = testdatasize(a,'objects'); |
---|
45 | a = seldat(a); % get labeled objects only |
---|
46 | [m,k,c] = getsize(a); |
---|
47 | data.kdtree = kd_buildtree(+a,0); |
---|
48 | data.nlab = getnlab(a); |
---|
49 | data.type = par; |
---|
50 | out = mapping(mfilename,'trained',data,getlablist(a),k,c); |
---|
51 | out = setname(out,name); |
---|
52 | elseif nargin == 2 & ismapping(par) % execution |
---|
53 | kdtree = getdata(par,'kdtree'); |
---|
54 | nlab = getdata(par,'nlab'); |
---|
55 | if strcmp(getdata(par,'type'),'fast') |
---|
56 | kdtype = @kd_closestpointfast; |
---|
57 | else |
---|
58 | kdtype = @kd_closestpointgood; |
---|
59 | end |
---|
60 | a_data = +a; |
---|
61 | % PRTools want posteriors. In this case these are just 0/1 's |
---|
62 | out = zeros(size(a,1),size(getlab(par),1)); |
---|
63 | m = size(a,1); |
---|
64 | s = sprintf('Testing %i objects: ',m); |
---|
65 | prwaitbar(m,s); |
---|
66 | for i=1:m; |
---|
67 | prwaitbar(m,i,[s int2str(i)]); |
---|
68 | j = kdtype(kdtree,a_data(i,:)); |
---|
69 | out(i,nlab(j)) = 1; |
---|
70 | end |
---|
71 | prwaitbar(0); |
---|
72 | out = setdat(a,out); |
---|
73 | end |
---|
74 | |
---|
75 | |
---|