 knn_fuzzy_fusion <- function (train,trainLabel,test,trueLabel,k,kf){

# fuzzy K-NN
   
   source("./paramperf.r")
   
   
   nbLabel=max(trueLabel)
   nTrain = nrow(train)
   nTest = nrow(test)
   
   # learning membership calculs
   dst = c()
   ist = c()
   for (i in 1:nTrain) {
     distE = rowSums((matrix(1, nTrain, 1) %*% train[i, ] - train)^2)
     dss =sort(distE)
     iss = order(distE)
     dst = cbind(dst, dss[1:kf+1])
     ist = cbind(ist, iss[1:kf+1])
   }
   
   matLabelT <- matrix(trainLabel[ist],nrow=kf)
   
   mu_it=matrix(0,nrow=nbLabel,ncol=nTrain)
   for (t in 1:nTrain){
     for (i in 1:nbLabel){
       ki<-length(which(matLabelT[,t]==i))
       mu_it[i,t]<-ki
     }
   }
   mu_it <-mu_it/kf
   ######################
   
   
   # training membership calculs
   
   dst = c()
   ist = c()
   
   for (i in 1:nTest) {
     distE = rowSums((matrix(1, nTrain, 1) %*% test[i, ] - train)^2)
     dss =sort(distE)
     iss = order(distE)
     dst = cbind(dst, dss[1:k])
     ist = cbind(ist, iss[1:k])
   }
   
   dst[which(dst==0)]<-0.000001 # to avoid to divide by 0
   
   foundLabel =c()
   mu_i=matrix(0,nrow=nbLabel,ncol=nTest)
   for (t in 1:nTest){
     for (i in 1:nbLabel){
       mu_i[i,t] <- sum(mu_it[i,ist[,t]]/dst[,t])/sum(1/dst[,t])
     }
     foundLabel <- c(foundLabel,which.max(mu_i[,t]))  # maximization of membership
   }
   
   
  
   
   restest=rbind(trueLabel ,foundLabel)
   
   res<-paramperf(restest)
   matr_conf<- res[1]
   vect_prob_classif<- res[2]
   vect_prob_erreur<- res[3]
 
   return (list(foundLabel=foundLabel,matr_conf=matr_conf,vect_prob_classif=vect_prob_classif,vect_prob_erreur=vect_prob_erreur,matr_sort_classif=mu_i))  
 }
 