Homepage › Solution manuals › Kevin P. Murphy › Machine Learning: a Probabilistic Perspective › Exercise 11.9 - K-means clustering by hand
Exercise 11.9 - K-means clustering by hand
Answers
import math def distance(a,b): return math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2) data=[[1,0],[3,0],[5,0],[7,0],[9,0],[11,0],[13,0],[15,0],[17,0], [1,3],[3,3],[5,3],[7,3],[9,3],[11,3],[13,3],[15,3],[17,3]] c1=[9,3] c2=[11,3] membership=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] for i in range(10): c1i=0 c1x=0 c1y=0 c2i=0 c2x=0 c2y=0 for j in range(len(data)): if (distance(data[j],c1)<=distance(data[j],c2)): membership[i]=1 c1i=c1i+1 c1x=c1x+data[j][0] c1y=c1y+data[j][1] else: membership[i]=2 c2i=c2i+1 c2x=c2x+data[j][0] c2x=c2x+data[j][1] c1[0]=c1x/c1i c1[1]=c1y/c1i c2[0]=c2x/c2i c2[1]=c2y/c2i print(c1) print(c2)
The result is:
[5.0, 1.5] [15.5, 0.0]
2021-03-24 13:42