Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e3a263c

Browse files
lorenzo30salgadoMaximSmolskiy
andauthored
Adding a 3D plot to the k-means clustering algorithm (#12372)
* Adding a 3D plot to the k-means clustering algorithm * Update k_means_clust.py * Update k_means_clust.py --------- Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
1 parent 501576f commit e3a263c

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

‎machine_learning/k_means_clust.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,13 @@
3737
heterogeneity,
3838
k
3939
)
40-
5. Transfers Dataframe into excel format it must have feature called
40+
5. Plot the labeled 3D data points with centroids.
41+
plot_kmeans(
42+
X,
43+
centroids,
44+
cluster_assignment
45+
)
46+
6. Transfers Dataframe into excel format it must have feature called
4147
'Clust' with k means clustering numbers in it.
4248
"""
4349

@@ -126,6 +132,19 @@ def plot_heterogeneity(heterogeneity, k):
126132
plt.show()
127133

128134

135+
def plot_kmeans(data, centroids, cluster_assignment):
136+
ax = plt.axes(projection="3d")
137+
ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=cluster_assignment, cmap="viridis")
138+
ax.scatter(
139+
centroids[:, 0], centroids[:, 1], centroids[:, 2], c="red", s=100, marker="x"
140+
)
141+
ax.set_xlabel("X")
142+
ax.set_ylabel("Y")
143+
ax.set_zlabel("Z")
144+
ax.set_title("3D K-Means Clustering Visualization")
145+
plt.show()
146+
147+
129148
def kmeans(
130149
data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False
131150
):
@@ -193,6 +212,7 @@ def kmeans(
193212
verbose=True,
194213
)
195214
plot_heterogeneity(heterogeneity, k)
215+
plot_kmeans(dataset["data"], centroids, cluster_assignment)
196216

197217

198218
def report_generator(

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /