IRootLab
An Open-Source MATLAB toolbox for vibrational biospectroscopy
clssr_knn.m
Go to the documentation of this file.
1 %> @brief k-Nearest Neighbours Classifier
2 %>
3 %> Posterior probabilities are calculated using the Laplace estimator [1].
4 %>
5 %> <h3>References</h3>
6 %> [1] Kuncheva, Combining Pattern Classifiers, page 154, 2004.
7 %>
8 %> @sa uip_clssr_knn.m
9 classdef clssr_knn < clssr
10  properties
11  %> =1. k-NN's k.
12  k = 1;
13  end;
14 
15  properties(SetAccess=private)
16  %> Training data is part of the model in the k-NN algorithm
17  X = [];
18  classes = [];
19  end;
20 
21  methods
22  function o = clssr_knn(o)
23  o.classtitle = 'k-Nearest Neighbours';
24  o.short = 'k-NN';
25  end;
26  end;
27 
28  methods(Access=protected)
29 
30  function o = do_boot(o)
31  end;
32 
33  function o = do_train(o, data)
34  o.classlabels = data.classlabels;
35 
36  tic;
37  o.X = data.X;
38  o.classes = o.get_classes(data);
39  o.time_train = toc;
40  end;
41 
42 
43 
44  %> Uses Laplace estimator for the posterior probabilities
45  %>
46  %> Reference: Kuncheva, Combining Pattern Classifiers, page 154, 2004.
47  function est = do_use(o, data)
48  flag_verbose = 1;
49  no_obs_test = data.no;
50  no_obs_train = size(o.X, 1);
51  no_classes = length(o.classlabels);
52 
53  votes = zeros(no_obs_test, no_classes);
54  est = estimato();
55  est.classlabels = o.classlabels;
56  est = est.copy_from_data(data);
57 
58  ii = 0;
59  tic();
60  for i = 1:no_obs_test
61  % vector to be tested
62  v_test = data.X(i, :);
63 
64  % Distance vector
65  dists = sum(bsxfun(@minus, o.X, v_test).^2, 2);
66 
67  [vv, idxs] = sort(dists);
68 
69  for j = 1:min(no_obs_train, o.k)
70  votes(i, o.classes(idxs(j))+1) = votes(i, o.classes(idxs(j))+1)+1; % Here a weight on the vote could be put
71  end;
72 
73  if flag_verbose
74  ii = ii+1;
75  if ii == 1000
76  ii = 0;
77  irverbose(sprintf('%d/%d', i, no_obs_test));
78  end;
79  end;
80  end;
81 
82  est.X = (votes+1)/(no_classes+o.k); % The Laplace formula
83 
84  o.time_use = toc();
85  end;
86  end;
87 
88 end
k-Nearest Neighbours Classifier
Definition: clssr_knn.m:9
Classifiers base class.
Definition: clssr.m:6