-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathplot_kmedoids.py
61 lines (50 loc) · 1.51 KB
/
plot_kmedoids.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# -*- coding: utf-8 -*-
"""
=============
KMedoids Demo
=============
KMedoids clustering of data points. The goal is to find medoids than minimize
the sum of absolute distance to the closest medoid. A medoid is a point of the
dataset. Read more in the :ref:`User Guide <_k_medoids>`.
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn_extra.cluster import KMedoids
from sklearn.datasets import make_blobs
print(__doc__)
# #############################################################################
# Generate sample data
centers = [[1, 1], [-1, -1], [1, -1]]
X, labels_true = make_blobs(
n_samples=750, centers=centers, cluster_std=0.4, random_state=0
)
# #############################################################################
# Compute Kmedoids clustering
cobj = KMedoids(n_clusters=3).fit(X)
labels = cobj.labels_
##############################################################
# Plot results
unique_labels = set(labels)
colors = [
plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))
]
for k, col in zip(unique_labels, colors):
class_member_mask = labels == k
xy = X[class_member_mask]
plt.plot(
xy[:, 0],
xy[:, 1],
"o",
markerfacecolor=tuple(col),
markeredgecolor="k",
markersize=6,
)
plt.plot(
cobj.cluster_centers_[:, 0],
cobj.cluster_centers_[:, 1],
"o",
markerfacecolor="cyan",
markeredgecolor="k",
markersize=6,
)
plt.title("KMedoids clustering. Medoids are represented in cyan.")