Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
T
TP-Clustering
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
IA et Machine Learning
TP-Clustering
Commits
23395b03
Commit
23395b03
authored
1 year ago
by
thibault.capt
Browse files
Options
Downloads
Patches
Plain Diff
update
parent
de33161a
No related branches found
No related tags found
No related merge requests found
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
main.py
+53
-39
53 additions, 39 deletions
main.py
with
53 additions
and
39 deletions
main.py
+
53
−
39
View file @
23395b03
...
@@ -3,60 +3,50 @@ import numpy as np
...
@@ -3,60 +3,50 @@ import numpy as np
import
matplotlib.pyplot
as
plt
import
matplotlib.pyplot
as
plt
def
import_csv
(
filename
:
str
,
h
:
int
=
None
)
->
pd
.
DataFrame
:
def
import_csv
(
filename
:
str
):
"""
return
pd
.
read_csv
(
filename
,
header
=
None
)
Imports a CSV file and returns a pandas DataFrame.
Args:
filename (str): The path to the CSV file.
h (int or list of int, default 0): The row(s) to use as the column names.
Returns:
def
manhattan_distance
(
x1
,
x2
):
pandas.DataFrame: The imported data as a DataFrame.
return
np
.
sum
(
np
.
abs
(
x1
-
x2
))
"""
return
pd
.
read_csv
(
filename
,
header
=
h
)
def
euclidian_distance
(
x1
,
x2
):
def
assign_clusters
(
X
,
centroids
):
return
np
.
sqrt
(
np
.
sum
((
x1
-
x2
)
**
2
))
distances
=
np
.
array
([[
manhattan_distance
(
x
,
centroid
)
for
centroid
in
centroids
]
for
x
in
X
])
return
np
.
argmin
(
distances
,
axis
=
1
)
if
__name__
==
"
__main__
"
:
def
k_means
(
X
,
k
,
max_iterations
=
100
):
df
=
import_csv
(
"
Data/iris.csv
"
)
# Initialisation des k-centroïdes de manière aléatoire
# Sélectionner les caractéristiques (colonnes) que vous voulez utiliser pour le clustering
X
=
df
.
iloc
[:,
:
-
1
].
values
# Sélectionner toutes les colonnes sauf la dernière (caratéristique)
k
=
3
# Nombre de clusters
# Initialisation des k-centroïdes de manière aleatoire
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
)]
# Initialisation des variables pour stocker les anciens et nouveaux centroïdes
old_centroids
=
np
.
zeros
(
centroids
.
shape
)
old_centroids
=
np
.
zeros
(
centroids
.
shape
)
new_centroids
=
centroids
.
copy
()
new_centroids
=
centroids
.
copy
()
# Initialisation d'une liste pour stocker la somme des distances au sein de chaque cluster à chaque itération
distances_history
=
[]
# Pour stocker la somme des distances à chaque itération
distances
=
[]
iteration
=
0
iteration
=
0
while
not
np
.
array_equal
(
old_centroids
,
new_centroids
):
while
not
np
.
array_equal
(
old_centroids
,
new_centroids
)
and
iteration
<
max_iterations
:
iteration
+=
1
iteration
+=
1
distances_to_centroids
=
np
.
array
([[
euclidian_distance
(
x
,
centroid
)
for
centroid
in
new_centroids
]
for
x
in
X
]
)
labels
=
assign_clusters
(
X
,
new_centroids
)
# Attribution des points aux centroïdes les plus proches
labels
=
np
.
argmin
(
distances_to
_centroids
,
axis
=
1
)
old_centroids
=
new
_centroids
.
copy
(
)
# Calcul des nouveaux centroïdes comme la moyenne des points de chaque cluster
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
)
# Calcul des distances au sein de chaque cluster
# Calcul de la somme des distances au sein de chaque cluster (fonction objectif)
cluster_distances
=
[
np
.
sum
([
euclidian_distance
(
X
[
j
],
new_centroids
[
i
])
total_distance
=
0
for
j
in
range
(
len
(
X
))
if
labels
[
j
]
==
i
])
for
i
in
range
(
k
)]
for
i
in
range
(
k
):
total_distance
=
np
.
sum
(
cluster_distances
)
cluster_points
=
X
[
labels
==
i
]
distances
.
append
(
total_distance
)
cluster_distance
=
np
.
sum
([
manhattan_distance
(
point
,
new_centroids
[
i
])
for
point
in
cluster_points
])
total_distance
+=
cluster_distance
# Affichage des clusters à cette iteration
distances_history
.
append
(
total_distance
)
# 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
):
cluster_points
=
X
[
labels
==
i
]
cluster_points
=
X
[
labels
==
i
]
...
@@ -68,12 +58,36 @@ if __name__ == "__main__":
...
@@ -68,12 +58,36 @@ if __name__ == "__main__":
plt
.
title
(
f
"
Iteration
{
iteration
}
"
)
plt
.
title
(
f
"
Iteration
{
iteration
}
"
)
plt
.
show
()
plt
.
show
()
# Mettre à jour les anciens et les nouveaux centroïdes
# Tracer la somme des distances à chaque itération
old_centroids
=
new_centroids
.
copy
()
plt
.
figure
(
figsize
=
(
8
,
6
))
plt
.
figure
(
figsize
=
(
8
,
6
))
plt
.
plot
(
range
(
1
,
iteration
+
1
),
distances
,
marker
=
'
o
'
)
plt
.
plot
(
range
(
1
,
iteration
+
1
),
distances
_history
,
marker
=
'
o
'
)
plt
.
xlabel
(
"
Iteration
"
)
plt
.
xlabel
(
"
Iteration
"
)
plt
.
ylabel
(
"
Somme des distances
au carré
"
)
plt
.
ylabel
(
"
Somme des distances
"
)
plt
.
title
(
"
Evolution de la somme des distances
au carré
"
)
plt
.
title
(
"
Evolution de la somme des distances
"
)
plt
.
show
()
plt
.
show
()
return
labels
,
new_centroids
if
__name__
==
"
__main__
"
:
# Initialiser k-centroides
# attribuer les points aux centroïde le plus proche (Manhattan / L2)
# Tant que les centroïdes bougent :
# Pour chaque cluster, calculer le point central du cluster (moyenne des coordonnées)
# noter si ancien centroïde ~= nouveau centroïde
# attribution des points aux nouveaux centroïdes
# calcul de la somme des distances au sein d'un cluster
# fonction objectif à minimiser
# plot la somme de la somme des distances à chaque itération
# afficher les nouveaux cluster à chaque itérations
# Charger les données depuis le fichier CSV
df
=
import_csv
(
"
Data/iris.csv
"
)
X
=
df
.
iloc
[:,
:
-
1
].
values
k
=
3
labels
,
centroids
=
k_means
(
X
,
k
)
print
(
"
Nouveaux centroïdes finaux:
"
)
print
(
centroids
)
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment