Skip to content
Snippets Groups Projects
Commit e50c7a0f authored by thibault.capt's avatar thibault.capt
Browse files
parents 6fe6d24d 2cb83f2f
Branches
No related tags found
No related merge requests found
...@@ -30,7 +30,9 @@ def manhattan_distance(x1: np.ndarray, x2: np.ndarray) -> float: ...@@ -30,7 +30,9 @@ def manhattan_distance(x1: np.ndarray, x2: np.ndarray) -> float:
Returns: Returns:
float: La distance de Manhattan entre x1 et x2. float: La distance de Manhattan entre x1 et x2.
""" """
return np.sum(np.abs(x1 - x2)) squared_diff = (x1 - x2) ** 2 # Carré des différences
l2_manhattan = np.sqrt(np.sum(squared_diff)) # Racine carrée de la somme des carrés
return l2_manhattan
def assign_clusters(X: np.ndarray, centroids: np.ndarray) -> np.ndarray: def assign_clusters(X: np.ndarray, centroids: np.ndarray) -> np.ndarray:
...@@ -62,21 +64,19 @@ def k_means(X: np.ndarray, k: int, max_iterations: int = 100) -> Tuple[np.ndarra ...@@ -62,21 +64,19 @@ def k_means(X: np.ndarray, k: int, max_iterations: int = 100) -> Tuple[np.ndarra
""" """
# Initialisation des k-centroïdes de manière aléatoire # Initialisation des k-centroïdes de manière aléatoire
np.random.seed(0) np.random.seed(0)
centroids = X[np.random.choice(X.shape[0], k, replace=False)] centroids = X[np.random.choice(X.shape[0], k, replace=False)] # séléctionne k points aléatoirement dans la liste X
old_centroids = np.zeros(centroids.shape) old_centroids = np.zeros(centroids.shape)
new_centroids = centroids.copy() new_centroids = centroids.copy()
distances_history = [] # Pour stocker la somme des distances à chaque itération distances_history = [] # Pour stocker la somme des distances
iteration = 0 iteration = 0
# pour vérifier que les centroides ne changent plus , il faut check que l'ancien et le nouveau soient pareils , on ajoute tout de même un nombre d'itérations max pour ne pas tourner à l'infini
while not np.array_equal(old_centroids, new_centroids) and iteration < max_iterations: while not np.array_equal(old_centroids, new_centroids) and iteration < max_iterations:
iteration += 1 iteration += 1
labels = assign_clusters(X, new_centroids) labels = assign_clusters(X, new_centroids)
old_centroids = new_centroids.copy() old_centroids = new_centroids.copy()
for i in range(k): for i in range(k):
new_centroids[i] = np.mean(X[labels == i], axis=0) new_centroids[i] = np.mean(X[labels == i], axis=0)
...@@ -88,7 +88,6 @@ def k_means(X: np.ndarray, k: int, max_iterations: int = 100) -> Tuple[np.ndarra ...@@ -88,7 +88,6 @@ def k_means(X: np.ndarray, k: int, max_iterations: int = 100) -> Tuple[np.ndarra
total_distance += cluster_distance total_distance += cluster_distance
distances_history.append(total_distance) distances_history.append(total_distance)
# Affichage des clusters à cette itération # Affichage des clusters à cette itération
plt.figure(figsize=(8, 6)) plt.figure(figsize=(8, 6))
for i in range(k): for i in range(k):
...@@ -125,7 +124,7 @@ if __name__ == "__main__": ...@@ -125,7 +124,7 @@ if __name__ == "__main__":
# afficher les nouveaux cluster à chaque itérations # afficher les nouveaux cluster à chaque itérations
# Charger les données depuis le fichier CSV # Charger les données depuis le fichier CSV
df = import_csv("Data/iris.csv", None) df = import_csv("Data/iris.csv", h=None)
X = df.iloc[:, :-1].values X = df.iloc[:, :-1].values
k = 3 k = 3
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment