-
Notifications
You must be signed in to change notification settings - Fork 21
/
k_means.py
45 lines (38 loc) · 1.21 KB
/
k_means.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
import numpy as np
import distance
class KMeans:
@property
def centers(self):
return self.__centers
def fit(self, X, n_clusters, epochs):
'''
Parameters
----------
X : shape (n_samples, n_features)
Training data
n_clusters : The number of clusters
epochs : The number of epochs
Returns
-------
y : shape (n_samples,)
Predicted cluster label per sample.
'''
n_samples = X.shape[0]
self.__centers = X[np.random.choice(n_samples, n_clusters)]
for _ in range(epochs):
labels = self.predict(X)
self.__centers = [np.mean(X[np.flatnonzero(labels == i)], axis=0) for i in range(n_clusters)]
return self.predict(X)
def predict(self, X):
'''
Parameters
----------
X : shape (n_samples, n_features)
Predicting data
Returns
-------
y : shape (n_samples,)
Predicted cluster label per sample.
'''
distances = np.apply_along_axis(distance.euclidean_distance, 1, self.__centers, X).T
return np.argmin(distances, axis=1)