Clustering

KMeans on blobs and a scatter of labels.

Clustering assigns a group without labels. KMeans picks k centers and each point joins the nearest center. You choose k. random_state and n_init make the run repeatable.

Goal

Cluster three blobs, print centers, and scatter the labels.

KMeans

from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans

X, _ = make_blobs(n_samples=180, centers=3, random_state=0)
km = KMeans(n_clusters=3, n_init=10, random_state=0)
labels = km.fit_predict(X)
print("counts", np.bincount(labels))
print("centers:\\n", km.cluster_centers_.round(2))

make_blobs also returns true blob ids. We ignore them — clustering is unsupervised. Compare visually.

Scatter

from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans

X, _ = make_blobs(n_samples=180, centers=3, random_state=0)
km = KMeans(n_clusters=3, n_init=10, random_state=0)
labels = km.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=labels, alpha=0.75)
plt.scatter(
    km.cluster_centers_[:, 0],
    km.cluster_centers_[:, 1],
    marker="x",
    s=90,
    c="black",
)
plt.title("KMeans k=3")
plt.show()

Inertia vs k

from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans

X, _ = make_blobs(n_samples=180, centers=3, random_state=0)
ks = [1, 2, 3, 4, 5, 6]
inertias = []
for k in ks:
    km = KMeans(n_clusters=k, n_init=10, random_state=0)
    km.fit(X)
    inertias.append(km.inertia_)
    print("k", k, "inertia", round(km.inertia_, 1))
plt.plot(ks, inertias, marker="o")
plt.xlabel("k")
plt.ylabel("inertia")
plt.title("Elbow")
plt.show()

Inertia drops as k grows. Look for an “elbow” — here it should sit near 3, the true number of blobs.

Pitfall

KMeans assumes round-ish blobs of similar size. Scale features first if columns have different units.