Daniel@0: function [y, l] = knnfwd(net, x) Daniel@0: %KNNFWD Forward propagation through a K-nearest-neighbour classifier. Daniel@0: % Daniel@0: % Description Daniel@0: % [Y, L] = KNNFWD(NET, X) takes a matrix X of input vectors (one vector Daniel@0: % per row) and uses the K-nearest-neighbour rule on the training data Daniel@0: % contained in NET to produce a matrix Y of outputs and a matrix L of Daniel@0: % classification labels. The nearest neighbours are determined using Daniel@0: % Euclidean distance. The IJth entry of Y counts the number of Daniel@0: % occurrences that an example from class J is among the K closest Daniel@0: % training examples to example I from X. The matrix L contains the Daniel@0: % predicted class labels as an index 1..N, not as 1-of-N coding. Daniel@0: % Daniel@0: % See also Daniel@0: % KMEANS, KNN Daniel@0: % Daniel@0: Daniel@0: % Copyright (c) Ian T Nabney (1996-2001) Daniel@0: Daniel@0: Daniel@0: errstring = consist(net, 'knn', x); Daniel@0: if ~isempty(errstring) Daniel@0: error(errstring); Daniel@0: end Daniel@0: Daniel@0: ntest = size(x, 1); % Number of input vectors. Daniel@0: nclass = size(net.tr_targets, 2); % Number of classes. Daniel@0: Daniel@0: % Compute matrix of squared distances between input vectors from the training Daniel@0: % and test sets. The matrix distsq has dimensions (ntrain, ntest). Daniel@0: Daniel@0: distsq = dist2(net.tr_in, x); Daniel@0: Daniel@0: % Now sort the distances. This generates a matrix kind of the same Daniel@0: % dimensions as distsq, in which each column gives the indices of the Daniel@0: % elements in the corresponding column of distsq in ascending order. Daniel@0: Daniel@0: [vals, kind] = sort(distsq); Daniel@0: y = zeros(ntest, nclass); Daniel@0: Daniel@0: for k=1:net.k Daniel@0: % We now look at the predictions made by the Kth nearest neighbours alone, Daniel@0: % and represent this as a 1-of-N coded matrix, and then accumulate the Daniel@0: % predictions so far. Daniel@0: Daniel@0: y = y + net.tr_targets(kind(k,:),:); Daniel@0: Daniel@0: end Daniel@0: Daniel@0: if nargout == 2 Daniel@0: % Convert this set of outputs to labels, randomly breaking ties Daniel@0: [temp, l] = max((y + 0.1*rand(size(y))), [], 2); Daniel@0: end