function net = knn(nin, k, tr_x, tr_y)
%KNN	Creates a K-nearest-neighbour classifier.
%
%	Description
%	NET = KNN(NIN, NOUT, K, TR_X, TR_Y) creates a KNN model NET
%	with input dimension NIN and K neighbours.
%       TR_X,TR_Y are the inouts and outputs in the training (labeled) set.
% 	
%       See also KMEANS, KNNFWD


%
%	The fields in NET are
%	  type = 'knn'
%	  nin = number of inputs
%	  nout = number of outputs
%	  tr_in = training input data
%	  tr_targets = training target data
%
%

%	Copyright (c) Ian T Nabney (1996-2001)
%       Modified by Greg Shakhnarovich  2002 - binary specific

nout = 2;

tr_y=sparse2dense(tr_y);
tr_targets=zeros(size(tr_x,1),nout);
tr_y=reshape(tr_y,size(1:size(tr_x,1)));
tr_targets(sub2ind(size(tr_targets),1:size(tr_x,1),tr_y))=1;


net.type = 'knn';
net.nin = nin;
net.nout = nout;
net.k = k;

net.tr_in = tr_x; 
net.tr_targets = tr_targets;





function ydense = sparse2dense(ysparse)
% takes a avector of labels, translates the labels so that they form a
% dense sequence 1..K

ydense = zeros(length(ysparse),1);

vals = unique(ysparse);
for n=1:length(vals)
  ydense(find(vals(n)==ysparse))=n;
end
