liveBook · Manning

K-means clustering

As explained in The Well-Grounded Data Analyst

K-means is a clustering algorithm that partitions observations into a specified number of groups by minimizing distances from observations to their assigned cluster centers.

K-means groups observations into a chosen number of clusters by placing nearby points together, producing internally homogeneous groups that differ from one another. section 13.1.4

A practical clustering workflow includes:

  • Scale continuous features so differences in measurement ranges do not dominate distances. section 13.1.4
  • Try candidate values of k and inspect inertia, choosing the point where additional clusters provide diminishing benefit. section 13.1.4
  • Assign each observation to a cluster, count cluster sizes, and inspect centers in the original feature units. section 13.1.4

Mobile-user segmentation

User features such as app counts, session counts, session length, usage timing, and social-media behavior produce segments including heavy users, casual users, night owls, and usage outliers. section 13.1.4

from sklearn.cluster import KMeans

k_values = range(3, 15)
inertia_values = []

for k in k_values:
    kmeans = KMeans(n_clusters=k, random_state=42)
    kmeans.fit(X_scaled)
    inertia_values.append(kmeans.inertia_)

fig, axis = plt.subplots()

axis.plot(k_values, inertia_values)

_ = axis.set(
    title="'Inertia' values for different values of k",
    xlabel="Number of clusters (the 'k' in k-means)",
    ylabel="Inertia"
)

axis.set_ybound(0, 900)

plt.show()

Run k-means across candidate cluster counts and plot inertia to support a practical choice of k. section 13.1.4

How The Well-Grounded Data Analyst covers it

How deep it goes
Explains scaling, cluster-count selection, assignments, inertia, and center interpretation without mathematical derivation.
Examples
Uses mobile-user records, inertia plots, cluster counts, transformed features, cluster centers, and behavioral personas.
What it assumes
Assumes user-level feature data and basic preprocessing, while introducing cluster-count selection through the elbow method.
What you can do after
Apply it via scikit-learn to assign observations to clusters and interpret their behavioral profiles.
How it connects
Connects clustering with feature scaling, inertia, cluster centers, customer segmentation, and personas.

Also explained in

Compare how 7 books explain K-means clustering →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Data Analyst. The section links point to the parts of the book it draws on.