test knn fonctionnel
This commit is contained in:
parent
3ddc45508a
commit
4f8da781bf
2 changed files with 29 additions and 7 deletions
31
Code/Knn.py
31
Code/Knn.py
|
@ -111,6 +111,7 @@ class Knn: #nom de la class à changer
|
|||
"""
|
||||
n,m = self.train.shape
|
||||
nn=np.empty((self.k,2))
|
||||
nn[:,0]=[i for i in range(self.k)]
|
||||
nn[:,1]=np.apply_along_axis(minkowski_distance,1,self.train[0:self.k],exemple,self.minkowski_p)
|
||||
for i in range(self.k,n):
|
||||
dist = minkowski_distance(self.train[i],exemple,self.minkowski_p)
|
||||
|
@ -150,6 +151,32 @@ class Knn: #nom de la class à changer
|
|||
|
||||
"""
|
||||
|
||||
n,m = test.shape
|
||||
n_ex,m_ex = self.train.shape
|
||||
nn=np.empty((n,self.k,2))
|
||||
# Boucle sur chaque ligne du jeu de test
|
||||
for x in range(n):
|
||||
nn[x,:,0]=[i for i in range(self.k)]
|
||||
nn[x,:,1]=np.apply_along_axis(minkowski_distance,1,self.train[0:self.k],test[x],self.minkowski_p)
|
||||
for i in range(self.k,n_ex):
|
||||
dist = minkowski_distance(self.train[i],test[x],self.minkowski_p)
|
||||
nn_dist=nn[x,:,1]
|
||||
distdiff = nn_dist-dist
|
||||
max_distdiff=max(distdiff)
|
||||
if(max_distdiff>0):
|
||||
pos_changement = np.argwhere(nn_dist==max(nn_dist))[0]
|
||||
nn[x,pos_changement,0]=i
|
||||
nn[x,pos_changement,1]=max_distdiff
|
||||
nn_labels = self.train_labels[nn[:,:,0].astype(np.int)]
|
||||
nn_mode_label = np.apply_along_axis(mode,1,nn_labels)
|
||||
# on construit la matrice de confusion
|
||||
cm = self.confusion_matrix(test_labels,nn_mode_label)
|
||||
accuracy, precision, recall = self.prediction_metrics(cm,test_labels,nn_mode_label)
|
||||
self.print_prediction_metrics(cm,accuracy,precision,recall)
|
||||
|
||||
return cm,accuracy,precision,recall
|
||||
|
||||
|
||||
def confusion_matrix(self,obs_labels,pred_labels):
|
||||
"""
|
||||
Retourne la matrice de confusion
|
||||
|
@ -157,11 +184,9 @@ class Knn: #nom de la class à changer
|
|||
Retourne une matrice NumPy
|
||||
"""
|
||||
unique_obs_labels=np.unique(obs_labels)
|
||||
unique_pred_labels=np.unique(pred_labels)
|
||||
nb_unique_obs_labels=(unique_obs_labels.shape)[0]
|
||||
nb_unique_pred_labels=(unique_pred_labels.shape)[0]
|
||||
|
||||
confusion_matrix = np.zeros((nb_unique_obs_labels,nb_unique_pred_labels))
|
||||
confusion_matrix = np.zeros((nb_unique_obs_labels,nb_unique_obs_labels))
|
||||
|
||||
for observed,predicted in zip(obs_labels,pred_labels):
|
||||
confusion_matrix[observed][predicted] += 1
|
||||
|
|
|
@ -37,12 +37,9 @@ train, train_labels, test, test_labels = ld.load_iris_dataset(0.7)
|
|||
|
||||
myKnn.train(train, train_labels)
|
||||
|
||||
for i in range(train.shape[0]):
|
||||
myKnn.predict(train[i],train_labels[i])
|
||||
|
||||
# Tester votre classifieur
|
||||
|
||||
|
||||
myKnn.test(test, test_labels)
|
||||
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue