Skip to content
Snippets Groups Projects
Commit 705ef408 authored by thibault.capt's avatar thibault.capt
Browse files

final commit

parent 8ed475a5
No related branches found
No related tags found
No related merge requests found
# Author : Capt Thibault , Souza Luz Juliano
# Date : 10.10.2023
# Project : Kmeans
# Description : Ce fi
# Description : Ce fichier représente notre utilisation de kmeans pour le fichier iris
import pandas as pd
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
def manhattan_distance(x1: np.ndarray, x2: np.ndarray) -> float:
"""
Distance manhattan L2
:param x1: un premier point
:param x2: un deuxieme point
:return: Distance entre ces 2 points selon la formule
"""
distance = 0
if x1.shape == x2.shape:
for i in range(x1.size):
......@@ -36,15 +40,16 @@ if __name__ == '__main__':
# Algorithme K-Means
for i in range(max_iter):
# Créer des clusters vides
# Créer k clusters vides
clusters = [[] for _ in range(k)]
# Sauvegarder les anciens centroïdes
# Pour chaque points
for point in X:
distances = [manhattan_distance(point, centroid) for centroid in centroids]
cluster_index = np.argmin(distances)
distances = [manhattan_distance(point, centroid) for centroid in centroids] # calcul des distances
cluster_index = np.argmin(distances) # distance minimale
clusters[cluster_index].append(point)
# Sauvegarder les anciens centroïdes
# Sauvegarder les anciens centroïdes (pour vérifier la convergence plus tard)
old_centroids = centroids.copy()
# Mettre à jour les centroïdes en calculant la moyenne des points dans chaque cluster
......@@ -60,17 +65,22 @@ if __name__ == '__main__':
total_variances.append(total_variance)
# Convergence ?
# Vérifier s'il y a une convergence pour stop le programme
if np.all(old_centroids == centroids):
break
# Calculer le taux de classification par cluster et la classe majoritaire par cluster
cluster_classifications = {}
cluster_majority_class = {}
# récupérer l'index et le point du cluster
for cluster_index, cluster_points in enumerate(clusters):
# récupérer les labels du cluster
cluster_labels = labels[np.isin(X, cluster_points).all(axis=1)]
# Récupérer le nombre de labels dans le cluster
cluster_counts = Counter(cluster_labels)
# Taux de classification
cluster_classifications[cluster_index] = cluster_counts
# Classe majoritaire
cluster_majority_class[cluster_index] = cluster_counts.most_common(1)[0][0]
# Afficher le taux de classification par cluster et la classe majoritaire par cluster
......
# Importation des bibliothèques
# Author : Capt Thibault , Souza Luz Juliano
# Date : 10.10.2023
# Project : Kmeans
# Description : Ce fichier représente notre utilisation de kmeans pour les fichiers student
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def manhattan_distance(x1: np.ndarray, x2: np.ndarray) -> float:
"""
Distance manhattan L2
:param x1: un premier point
:param x2: un deuxieme point
:return: Distance entre ces 2 points selon la formule
"""
distance = 0
if x1.shape == x2.shape:
for i in range(x1.size):
......@@ -15,7 +23,7 @@ def manhattan_distance(x1: np.ndarray, x2: np.ndarray) -> float:
if __name__ == '__main__':
dataset = pd.read_csv("Data/student-data-test.csv", header=0)
X = dataset.iloc[:, 1:].values
k = 3
k = 2 # nombre de clusters
# Initialisation des k-centroides de manière aléatoire
centroids = X[np.random.choice(X.shape[0], k, replace=False)]
......@@ -24,15 +32,16 @@ if __name__ == '__main__':
total_variances = []
# Algorithme K-Means
for i in range(max_iter):
# Créer des clusters vides
# Créer k clusters vides
clusters = [[] for _ in range(k)]
# Sauvegarder les anciens centroïdes
# Pour chaque points
for point in X:
distances = [manhattan_distance(point, centroid) for centroid in centroids]
cluster_index = np.argmin(distances)
distances = [manhattan_distance(point, centroid) for centroid in centroids] # calcul des distances
cluster_index = np.argmin(distances) # distance minimale
clusters[cluster_index].append(point)
# Sauvegarder les anciens centroïdes
# Sauvegarder les anciens centroïdes (pour vérifier la convergence plus tard)
old_centroids = centroids.copy()
# Mettre à jour les centroïdes en calculant la moyenne des points dans chaque cluster
......@@ -60,7 +69,7 @@ if __name__ == '__main__':
plt.legend()
plt.show()
# Convergence ?
# Vérifier s'il y a une convergence pour stop le programme
if np.all(old_centroids == centroids):
break
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment