Created
December 14, 2014 22:24
-
-
Save daemonfire300/184cfde269a10fe17cf2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def mean(C): | |
m = np.array([0,0]) | |
for c in C: | |
m += c | |
m = m * (1/len(C)) | |
return m | |
def recalc(C, F, k, centroids): | |
sqe = 0 | |
# assign features to clusters based on distance to centroids | |
C = {} | |
C[0] = list() | |
C[1] = list() | |
for f in F: | |
#if np.linalg.norm((f-centroids[1])) < np.linalg.norm((f-centroids[0])): | |
if distance.euclidean(f,centroids[1])**2 <= distance.euclidean(f,centroids[0])**2: | |
C[1].append(f) | |
else: | |
C[0].append(f) | |
print("----------------------------------------------------------------------") | |
print("C",C) | |
print("----------------------------------------------------------------------") | |
# recalculate centroids | |
centroids = [np.array([0,0]),np.array([0,0])] | |
for i in range(k): | |
#centroids[i] = np.mean(C[i], axis=0) | |
centroids[i] = mean(C[i]) | |
for i in range(k): | |
for c in C[i]: | |
sqe += np.linalg.norm((c-centroids[i]))**2 | |
print("iter",i,"error", sqe) | |
return (sqe, C, centroids) | |
def kmeans(F, k, centroids): | |
sqe = 0 | |
psqe = None | |
# create empty clusters | |
C = {} | |
print(C) | |
#sqe, C = recalc(C, F, k, centroids) | |
i = 0 | |
while sqe != psqe: | |
#while i < 3: | |
i += 1 | |
psqe = sqe | |
sqe, C, centroids = recalc(C, F, k, centroids) | |
#print(sqe, centroids, C) | |
#print("mean", mean([np.array([1, 1]),np.array([5, 2])])) | |
#print("mean", mean([np.array([1, 2]),np.array([2, 5]),np.array([4, 4]), np.array([2, 2]), np.array([5, 5])])) | |
return (i, sqe, "CLUSTER", C, "c", centroids) | |
D = np.array([(1,1), (1,2), (2,2), (5,2), (4,4), (2,5), (5,5)]) | |
#print(find_centers(D, 2, np.array([D[3], D[4]]), np.array([D[1], D[2]]))) | |
c = np.array([D[3], D[4]]) | |
print("centroids", c) | |
kms = kmeans(D, 2, c) | |
print(kms) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment