Implementing K-Means with Scikit-learn
You'll learn how to fit a K-Means model, extract cluster assignments and centroids, and visualize the clustering results in practice.
The Core Idea
Now that you understand how K-Means works conceptually, it's time to use it in real code. Scikit-learn makes this incredibly straightforward: you initialize a KMeans object with your chosen number of clusters, fit it to your data, and extract the results. Think of it like using a cookie cutter—you specify the shape (number of clusters), press it onto dough (fit to data), and collect the cut pieces (cluster labels).
Hands-On Implementation
Here's the basic workflow:
from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
# Your feature-scaled data
X = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
# Initialize and fit K-Means
kmeans = KMeans(n_clusters=2, random_state=42)
kmeans.fit(X)
# Extract results
labels = kmeans.labels_ # Cluster assignments for each point
centroids = kmeans.cluster_centers_ # Coordinates of cluster centers
# Visualize
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis')
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='X', s=200, c='red', edgecolor='black')
plt.show()
The labels_ array tells you which cluster (0, 1, etc.) each data point belongs to. The cluster_centers_ array gives you the final centroid positions after convergence. Plotting these together reveals how K-Means carved up your data space.
Why This Matters
This workflow—fit, extract, visualize—is your standard practice for applying K-Means to any dataset. You'll repeat these steps whether analyzing customer segments, compressing images, or grouping similar documents.
Key Takeaway: Scikit-learn's KMeans class lets you fit clusters with .fit(), retrieve assignments via .labels_, access centroids through .cluster_centers_, and visualize the groupings—all in just a few lines of code.