How to graph centroids with KMeans

Written by- Aionlinecourse717 times views

To graph centroids with KMeans, you can use the following steps:

1. Import the necessary libraries. You will need matplotlib for plotting and sklearn for the KMeans algorithm.

import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

1. Load your data into a NumPy array or Pandas dataframe. The data should have at least two features, as KMeans works with numeric data.
2. Use the KMeans class to fit the data and predict the cluster labels.

kmeans = KMeans(n_clusters=3)  # specify the number of clusters
kmeans.fit(data)
labels = kmeans.predict(data)

 1. Extract the centroids from the fitted KMeans model.

centroids = kmeans.cluster_centers_

 1. Plot the data and the centroids using matplotlib.

# plot the data pointsplt.scatter(data[:, 0], data[:, 1], c=labels)
# plot the centroidsplt.scatter(centroids[:, 0], centroids[:, 1], marker='*', c='r', s=200)
plt.show()

Note that this is just one way to visualize the centroids with KMeans. There are many other options and variations depending on the specific requirements and characteristics of your data.