@@ -23,7 +23,7 @@ def fit(self, X):
23
23
while (pre_centers != self .centers ).any ():
24
24
pre_centers = self .centers .copy ()
25
25
dis = euc_dis (X [:, None , :], self .centers [None , :, :])
26
- cluster = dis .argmax (axis = - 1 )
26
+ cluster = dis .argmin (axis = - 1 )
27
27
for i in range (self .k ):
28
28
self .centers [i ] = X [cluster == i ].mean (axis = 0 )
29
29
step += 1
@@ -32,7 +32,7 @@ def fit(self, X):
32
32
33
33
def predict (self , X ):
34
34
dis = euc_dis (X [:, None , :], self .centers [None , :, :])
35
- return dis .argmax (axis = - 1 )
35
+ return dis .argmin (axis = - 1 )
36
36
37
37
if __name__ == "__main__" :
38
38
def demonstrate (X , k , desc ):
@@ -46,15 +46,17 @@ def demonstrate(X, k, desc):
46
46
plt .show ()
47
47
48
48
# -------------------------- Example 1 ----------------------------------------
49
- X = np .array ([[0 , 0 ], [0 , 1 ], [1 , 0 ], [2 , 2 ], [2 , 1 ], [1 , 2 ]])
50
- # generate grid-shaped test data
49
+ X = np .array ([[0 , 0 ], [0 , 1 ], [1 , 0 ], [2 , 2 ], [2 , 1 ], [1 , 2 ]]).astype (float )
51
50
demonstrate (X , 2 , "Example 1" )
52
51
53
52
# -------------------------- Example 2 ----------------------------------------
54
53
X = np .concatenate ([
55
54
np .random .normal ([0 , 0 ], [.3 , .3 ], [100 , 2 ]),
56
55
np .random .normal ([0 , 1 ], [.3 , .3 ], [100 , 2 ]),
57
56
np .random .normal ([1 , 0 ], [.3 , .3 ], [100 , 2 ]),
58
- ])
59
- # generate grid-shaped test data
60
- demonstrate (X , 3 , "Example 2: it is very sensitive to noise" )
57
+ ]).astype (float )
58
+ demonstrate (X , 3 , "Example 2" )
59
+
60
+ # -------------------------- Example 3 ----------------------------------------
61
+ X = np .array ([[0 , 0 ], [0 , 1 ], [0 , 3 ]]).astype (float )
62
+ demonstrate (X , 2 , "Example 3: K-Means doesn't always return the best answer. (try to run multiple times!)" )
0 commit comments