function [Outputs,Pre_Labels]=COMMU_test_knn(train_data,train_target,test_data,M)
%%knn for test stage
%M (dim, dim) the learned metric matrix 
%%
[n,p]=size(test_data);
q=size(train_target,2);
m=size(train_data,1);
K=10;
labelP=zeros(n,q);
w=zeros(n,K);
for i=1:n
    for j=1:m
    v(i,j)=(test_data(i,:)-train_data(j,:))*M*(test_data(i,:)-train_data(j,:))';
    end
    [v2,index]=sort(v(i,:));
    knnY(i,:)=index(1:K);
    for l=1:K
        if sum(v2(1:K))==0
            w(i,:)=1/K;
            break;
        else      
       w(i,l)=1-v2(l)/sum(v2(1:K));
        end
    end
end
%predict
temp=zeros(K,q);
weight=zeros(size(w));
for i=1:n
      for l=1:K
         weight(i,l)=w(i,l)/sum(w(i,:));   
         temp(l,:)=weight(i,l).*train_target(knnY(i,l),:);
      end
      sumC=sum(temp,1);
      sumlabelP(i,:)=sumC;
      sumC(sumC>=0.5)=1; 
      sumC(sumC<0.5)=-1;
      labelP(i,:)=sumC; 
      
end
Outputs=sumlabelP';
Pre_Labels=labelP';
end