Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. def kMedoids(D, k, tmax=100):
  2. # determine dimensions of distance matrix D
  3. m, n = D.shape
  4. # randomly initialize an array of k medoid indices
  5. M = np.sort(np.random.choice(n, k)
  6. # create a copy of the array of medoid indices
  7. Mnew = np.copy(M)
  8. # initialize a dictionary to represent clusters
  9. C = {}
  10. for t in range(tmax):
  11. # determine clusters, i.e. arrays of data indices
  12. J = np.argmin(D[:,M], axis=1)
  13. for kappa in range(k):
  14. C[kappa] = np.where(J==kappa)[0]
  15. # update cluster medoids
  16. for kappa in range(k):
  17. J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)
  18. j = np.argmin(J)
  19. Mnew[kappa] = C[kappa][j]
  20. np.sort(Mnew)
  21. # check for convergence
  22. if np.array_equal(M, Mnew):
  23. break
  24. M = np.copy(Mnew)
  25. else:
  26. # final update of cluster memberships
  27. J = np.argmin(D[:,M], axis=1)
  28. for kappa in range(k):
  29. C[kappa] = np.where(J==kappa)[0]
  30. # return results
  31. return M, C
  32.  
  33. D = pairwise_distances(arraydata,metric='euclidean')
  34.  
  35. # split into 2 clusters
  36. M, C = kMedoids(D, 2)
  37.  
  38. print('medoids:')
  39. for point_idx in M:
  40. print(arraydata[point_idx] )
  41.  
  42. print('')
  43. # array for get label
  44. temp = []
  45. indeks = []
  46. print('clustering result:')
  47. for label in C:
  48. for point_idx in C[label]:
  49. print('label {0}: {1}'.format(label, arraydata[point_idx]))
  50. temp.append(label)
  51. indeks.append(point_idx)
  52.  
  53. clustering result:
  54. label 0: [0.00000000e+00 0.00000000e+00 1.00000000e+00 1.00000000e+00
  55. 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
  56. 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
  57. 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
  58. 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
  59. 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
  60. 1.00000000e+00 0.00000000e+00 1.00000000e+00 1.00000000e+00
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement