-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmeds.py
74 lines (65 loc) · 2.25 KB
/
kmeds.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
global data
global output_ind # output index
global path
<initialize data>
<initialize the output index>
<initialize path>
def kmedoids(k):
nochange=False
#init medoids
medoids={}
meds={}
for i in range(k):
m=randrange(len(data))
while medoids.get((m,0))!=None:
m=randrange(len(data))
medoids[(m,0)]=[]
meds[m]=0
while nochange==False:
#assigning points
for i,elm in enumerate(data):
if meds.get(i)!=None:
continue
else:
best=100000
for m in medoids.keys():
dist=distance(elm,m)
if dist<best:
best=dist
medoid=m
medoids[medoid].append(i)
medoids[(medoid[0],medoid[1]+best)]=medoids.pop(medoid)
#check for a new config
changes=[]
for m in medoids.keys():
cost=m[1]
change=()
x=()
for o in medoids[m]:
cost2=0
for q in medoids[m]:
if q!=o:
cost2+=distance(data[o],data[q])
cost2+=distance(data[o],data[m[0]])
if cost2<cost:
cost=cost2
x=(o,cost2)
if x!=():
change=(m,x)
changes.append(change)
if changes!=[]:
for c in changes:
medoids[c[1]]=medoids.pop(c[0])
del(meds[c[0][0]])
meds[c[1][0]]=0
cop=copy.deepcopy(medoids)
for m in cop.keys():
medoids[m]=[]
medoids[(m[0],0)]=medoids.pop(m)
else:
nochange=True
clusters={}
for m, objects in medoids:
cluster=[data[o] for o in objects]
clusters[data[m[0]]]=cluster
return clusters