Skip to content
This repository was archived by the owner on Oct 25, 2024. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions week09/improvement/clustering.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
"""This code implements the k-means clustering algorithm for 2 dimensions."""

from math import *
from random import *
from math import sqrt
from random import randrange

k=3
num_clusters=3

lines = open('samples.csv', 'r').readlines()
ps=[]
for line in lines: ps.append(tuple(map(float, line.strip().split(','))))

m=[ps[randrange(len(ps))], ps[randrange(len(ps))], ps[randrange(len(ps))]]
m=[ps[randrange(len(ps))] for i in range(num_clusters)]

alloc=[None]*len(ps)
n=0
Expand All @@ -21,12 +21,12 @@
d[1]=sqrt((p[0]-m[1][0])**2 + (p[1]-m[1][1])**2)
d[2]=sqrt((p[0]-m[2][0])**2 + (p[1]-m[2][1])**2)
alloc[i]=d.index(min(d))
for i in range(3):
for i in range(num_clusters):
alloc_ps=[p for j, p in enumerate(ps) if alloc[j] == i]
new_mean=(sum([a[0] for a in alloc_ps]) / len(alloc_ps), sum([a[1] for a in alloc_ps]) / len(alloc_ps))
m[i]=new_mean
n=n+1

for i in range(3):
for i in range(num_clusters):
alloc_ps=[p for j, p in enumerate(ps) if alloc[j] == i]
print("Cluster " + str(i) + " is centred at " + str(m[i]) + " and has " + str(len(alloc_ps)) + " points.")
12 changes: 12 additions & 0 deletions week09/improvement/samples.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
342,4454
34,5
34,34
45,56
453,67
34,6
7,45
45,7
45,6
65654,456
54,564
456,56