-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMeansClustering.py
94 lines (64 loc) · 2.58 KB
/
KMeansClustering.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
def euclidean_dist(x1, x2):
return np.sqrt(np.sum((x1-x2)**2))
class KMeans:
def __init__(self, K):
# number of clusters
self.K = K
# mean vectors for each cluster
self.centroids = []
def classify(self, X):
self.X = X
self.n_samples, self.n_features = X.shape
# initialization of centroids
self.centroids = X[np.random.choice(self.X.shape[0], self.K, replace=False), :]
while (True):
self.clusters = self._create_clusters(self.centroids)
centroids_old = self.centroids
self.centroids = self._get_centroids(self.clusters)
if self._is_converged(centroids_old, self.centroids):
break
return self._get_labels(self.clusters)
def _get_labels(self, clusters):
labels = np.empty(self.n_samples)
for cluster_idx, cluster in enumerate(clusters):
for sample_idx in cluster:
labels[sample_idx] = cluster_idx
return labels
def _create_clusters(self, centroids):
clusters = [[] for i in range(self.K)]
for idx, sample in enumerate(self.X):
centroid_idx = self._closest_centroid(sample, centroids)
clusters[centroid_idx].append(idx)
return clusters
def _closest_centroid(self, sample, centroids):
distances = [euclidean_dist(sample, centroid) for centroid in centroids]
closest_idx = np.argmin(distances)
return closest_idx
def _get_centroids(self, clusters):
centroids = np.zeros((self.K, self.n_features))
for cluster_idx, cluster in enumerate(clusters):
cluster_mean = np.mean(self.X[cluster], axis = 0)
centroids[cluster_idx] = cluster_mean
return centroids
def _is_converged(self, centroids_old, centroids):
distances = [euclidean_dist(centroids_old[i], centroids[i]) for i in range(self.K)]
return sum(distances) == 0
def plot(self):
fig, ax = plt.subplots(figsize = (12,8))
for i, index in enumerate(self.clusters):
point = self.X[index].T
ax.scatter(*point, marker=".")
for point in self.centroids:
ax.scatter(*point, marker="x", color="black", linewidth=2)
plt.show()
def main():
X, y = make_blobs(centers=4, n_samples=500, n_features=2, shuffle=True)
clusters = len(np.unique(y))
k = KMeans(K=clusters)
y_pred = k.classify(X)
k.plot()
if __name__ == "__main__":
main()