Advertisement
EXTREMEXPLOIT

Souti K-Means

May 9th, 2020
1,081
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. #Solution
  2. def K_means_clustering(X, n_clusters=2, seed=1, num_iterations=10):
  3.     # Initialitize centroids based on a random selection of #n_clusters samples of X
  4.     rng = np.random.RandomState(seed)
  5.     i = rng.permutation(X.shape[0])[:n_clusters]
  6.     centroids = X[i]
  7.     labels = []
  8.  
  9.     #Repeat the process during num_iterations or convergence achieved
  10.     for num in range(0, num_iterations):
  11.         distancesMatrix = np.matrix([calculate_distance(X, centroid) for centroid in centroids]).T
  12.        
  13.     #For each iteration, calculate the shortest distance of each point of X to centroids
  14.     #Labels are based on the index in the centroids array
  15.         labels = [distancesMatrix[j].argmin() for j in range(len(distancesMatrix))]
  16.        
  17.     #Calculate the new centroids based on the means of each point assigned to each cluster
  18.         new_centroids= [np.array([0 for _ in range(X.shape[1])]) for n in range(n_clusters)]
  19.         for j in range(len(X)):
  20.             new_centroids[labels[j]] = new_centroids[labels[j]] + X[j]
  21.         for j in range(len(new_centroids)):
  22.             new_centroids[j] = new_centroids[j]/labels.count(j)
  23.            
  24.     # Evaluate convergence: if new_centroids=centroids, stop iterations
  25.         if np.array_equal(centroids, new_centroids):
  26.             print('Convergence achieved with:',num+1, 'iterations')
  27.             break
  28.         else:
  29.             if (num+1)%10 == 0 and num != 0:
  30.                 print('No convergence yet after', num+1, 'iterations')
  31.         centroids = new_centroids
  32.     # print(labels.count(0), labels.count(1), labels.count(2))  
  33.     return centroids, labels
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement