# Clustering kmeans = KMeans(k=n_centers, iterations=max_iterations, random_state=random_state, track_history=True) kmeans.fit(X) # Extract centroids centroids = kmeans.history_centroids # Create decision boundary data h = .1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) area_data = np.c_[xx.ravel(), yy.ravel()] # Prepare predictions predicted_labels = [] predicted_area = [] for iteration in range(max_iterations): kmeans.centroids = centroids[iteration] area = np.array(kmeans.predict(area_data)) area = area.reshape(xx.shape) predicted_labels.append(kmeans.predict(X)) predicted_area.append(area) # Plotting and showing the animation. fig, ax = plt.subplots(figsize=(15, 6), dpi=80) animation = FuncAnimation(fig, update, frames=max_iterations, interval=800, repeat=False) plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.show()