Skip to main content

🎯 K-Means

The most popular clustering algorithm.

📍 The Magnet Analogy

It randomly drops K "Magnets" onto your data map. Every point gets pulled to its closest magnet.

🐍 Python Implementation

from sklearn.cluster import KMeans

# 4 random dots on a map
X = [[1, 2], [1, 4], [10, 2], [10, 4]]

# Group them into 2 clusters
kmeans = KMeans(n_clusters=2, random_state=0)
kmeans.fit(X)

print("Cluster labels for the points:", kmeans.labels_)
print("Magnet centers:", kmeans.cluster_centers_)