Question: def get_labels(self, X, centroids): labels = np.argmin(np.sqrt(((X - centroids[:, np.newaxis])**2).sum(axis=2)),axis=0) return np.array(labels) KmeansModel.get_labels = get_labels # Here we are just adding the function to the
def get_labels(self, X, centroids): labels = np.argmin(np.sqrt(((X - centroids[:, np.newaxis])**2).sum(axis=2)),axis=0)
return np.array(labels)
KmeansModel.get_labels = get_labels # Here we are just adding the function to the KmeansModel class.
help fill out in python
Now we have our main function which runs the K-means algorithm. This repeatedly performs the two steps of the Kmeans algorithm (Data Assignment and Centroid Update). You should stop when there is no change in the cluster centroids, ie they are the same as the previous step We also stop after a certain number of max iterations if the algorithm is not converging. After convergence, we plot the data again with the new cluster centers and labels. In [ ]: def run(self): iters = 0 while True: # REPLACE THIS WITH THE ACTUAL NEW CENTROIDS CALCULATION. USE get_Labels() new_centroids = centroids # ADD THE CONVERGENCE CONDITION HERE, IE IF THE CENTROIDS DON'T CHANGE SINCE THE LAST ITERATION THEN BREAK # ALSO UPDATE THE CENTROIDS TO THE NEW VALUES if iters == self.max_iters: break iters += 1 final_labels = self.get_labels(self.x, self.centroids) self.plot_data(final_labels, 'Final clusters') KmeansModel.run = run Now we have our main function which runs the K-means algorithm. This repeatedly performs the two steps of the Kmeans algorithm (Data Assignment and Centroid Update). You should stop when there is no change in the cluster centroids, ie they are the same as the previous step We also stop after a certain number of max iterations if the algorithm is not converging. After convergence, we plot the data again with the new cluster centers and labels. In [ ]: def run(self): iters = 0 while True: # REPLACE THIS WITH THE ACTUAL NEW CENTROIDS CALCULATION. USE get_Labels() new_centroids = centroids # ADD THE CONVERGENCE CONDITION HERE, IE IF THE CENTROIDS DON'T CHANGE SINCE THE LAST ITERATION THEN BREAK # ALSO UPDATE THE CENTROIDS TO THE NEW VALUES if iters == self.max_iters: break iters += 1 final_labels = self.get_labels(self.x, self.centroids) self.plot_data(final_labels, 'Final clusters') KmeansModel.run = run
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
