Kmeans Algorithm Implementation In Python
Source Code:
inp = list(map(int,raw_input("Enter Elements ").split()))
k = int(raw_input(" Enter Number Of Cluster : "))
itr = 0
clusters = []
for i in range(k):
clusters.append([])
i = 0
for n in inp:
clusters[i].append(n)
i = (i+1)%3
c_copy = clusters
while True:
t = []
for c in clusters:
t.append(sum(c)/len(c))
clusters = []
for i in range(k):
clusters.append([])
for n in inp:
z = []
for m in t:
z.append(abs(m-n))
clusters[z.index(min(z))].append(n)
itr = itr+1
if(c_copy == clusters):
print "Final Clusters after",itr,"iteration"
for cl in clusters:
print cl
break
else:
c_copy = clusters
Output:
Enter Elements 25 10 36 45 78 95 11 23 84 67 65
Enter Number Of Cluster : 3
Final Clusters after 3 iteration
[25, 10, 11, 23]
[36, 45]
[78, 95, 84, 67, 65]
Comments
Post a Comment