TEC-DATA85-08 · Lesson 6 · 12 clock hours · lab
Unsupervised Learning: K-Means Clustering
Objective. Students will apply k-means clustering to an unlabeled dataset, use the elbow method and silhouette score to select k, and communicate cluster profiles to a business audience.
⚠ Pending professional review
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
What Is Unsupervised Learning?
In supervised learning, every training record comes with a label — for example, "churned" or "stayed." Unsupervised learning works differently: you hand the algorithm a dataset with no labels and ask it to find structure on its own. K-means clustering is the most widely used unsupervised technique. It groups records into k clusters so that observations inside a cluster are as similar to each other as possible and as different as possible from observations in other clusters.
Common business uses include customer segmentation, grouping city service requests by geographic pattern, detecting unusual usage behavior, and summarizing large surveys. Because the algorithm produces groups rather than predictions, your job as a data analyst is to interpret what each group means and communicate that meaning clearly to decision-makers.
How K-Means Works
K-means follows a straightforward iterative process:
1. Initialize — The algorithm places k centroids (center points) randomly in the feature space.
2. Assign — Every data point is assigned to the nearest centroid, measured by Euclidean distance.
3. Update — Each centroid moves to the mean position of all points assigned to it.
4. Repeat — Steps 2 and 3 repeat until centroid positions stop changing (convergence).
The scikit-learn `KMeans` class handles this automatically. You specify `n_clusters=k`, call `.fit()` on scaled data, and retrieve cluster labels with `.labels_`.
Feature scaling is essential. K-means uses Euclidean distance, so a feature measured in dollars (0–10,000) will dominate a feature measured in years (0–80) if you do not scale first. Use `StandardScaler` or `MinMaxScaler` before fitting. This is a data-quality and model-validity issue, not just a best practice.
Choosing k: The Elbow Method
K-means requires you to specify k before fitting. Two diagnostics help you choose a defensible value.
Inertia (within-cluster sum of squares) measures the total squared distance of each point from its centroid. Lower inertia means tighter clusters, but inertia always decreases as k increases — adding more clusters eventually assigns every point to its own cluster, reducing inertia to zero. The elbow curve plots inertia on the y-axis against k on the x-axis. Look for the point where the curve bends sharply — the "elbow" — after which adding more clusters yields diminishing returns. That bend is a candidate value for k.
In Python with yellowbrick:
```python
from yellowbrick.cluster import KElbowVisualizer
from sklearn.cluster import KMeans
model = KMeans()
visualizer = KElbowVisualizer(model, k=(2, 11))
visualizer.fit(X_scaled)
visualizer.show()
```
Choosing k: Silhouette Score
The silhouette score gives a second, more rigorous check. For each point it computes:
- a — average distance to all other points in the same cluster
- b — average distance to all points in the nearest neighboring cluster
The silhouette score for that point is (b − a) / max(a, b). Scores range from −1 to +1. A score near +1 means the point fits its cluster well. A score near 0 means the point sits on a cluster boundary. A negative score suggests the point may have been assigned to the wrong cluster.
You compute the mean silhouette score across all points for each candidate k and prefer higher values. Compare the elbow curve and silhouette scores together: the best k typically shows both a clear elbow and a peak (or near-peak) silhouette score.
```python
from sklearn.metrics import silhouette_score
for k in range(2, 11):
km = KMeans(n_clusters=k, random_state=42)
labels = km.fit_predict(X_scaled)
score = silhouette_score(X_scaled, labels)
print(f'k={k}, silhouette={score:.3f}')
```
Visualizing and Profiling Clusters
Once you select k, refit the model and attach the cluster labels back to your original (unscaled) dataframe. A color-coded scatter plot — using two features or the first two principal components — makes the separation visible. Label each color in the legend with the cluster number.
Next, compute summary statistics per cluster (mean, median, count) using `groupby`. These statistics are what let you describe each cluster in plain English. For example: "Cluster 2 contains ZIP codes with high library visits per capita but low digital-access scores — these locations may benefit from expanded in-branch computer stations."
Writing for a Business Audience
Technical plots alone rarely move decision-makers. Your business memo should:
- State what the analysis was and why it was done (one short paragraph).
- Describe each cluster in plain language, using the summary statistics as evidence.
- Offer one concrete, data-backed recommendation per cluster.
- Avoid jargon such as "centroid," "inertia," or "Euclidean distance" unless you define the terms.
Clarity and brevity matter as much as accuracy. A city department director needs to act on your findings, not grade your code.
Data Ethics and Safety Notes
Public city datasets often contain information that can be disaggregated by neighborhood in ways that reflect historical inequities. Before labeling a cluster "low-performing" or similar, consider whether the pattern reflects a genuine difference in service demand or a disparity in resource allocation. Report what the data shows; avoid language that stigmatizes communities. Always verify that the dataset is truly public and contains no personally identifiable information (PII) before loading it into your environment. If PII is discovered, stop work and notify your instructor — handle data with the same care you would handle any sensitive workplace material.
Key terms8
K-means clusteringAn unsupervised algorithm that partitions data into k groups by iteratively assigning each point to the nearest centroid and moving centroids to the mean of their assigned points.
CentroidThe center point of a cluster, calculated as the mean position of all data points assigned to that cluster.
InertiaThe sum of squared distances between each data point and its assigned cluster centroid; also called within-cluster sum of squares. Lower values indicate tighter clusters.
Elbow methodA technique for selecting k by plotting inertia against different values of k and identifying the point where additional clusters produce diminishing reductions in inertia.
Silhouette scoreA metric ranging from -1 to +1 that measures how similar a point is to its own cluster compared to the nearest neighboring cluster; higher values indicate better-defined clusters.
Feature scalingThe process of transforming features to a common range or distribution (e.g., using StandardScaler) so that no single feature dominates distance-based calculations.
Unsupervised learningA class of machine learning in which the algorithm finds patterns in data that has no predefined labels or target variable.
Cluster profileA plain-language description of a cluster's characteristics, derived from summary statistics, used to communicate findings to non-technical stakeholders.
Worked examples4
1. You run k-means on a dataset of 200 retail customers with two features: annual spending ($) and visit frequency (visits/year). You compute the mean silhouette score for k = 2, 3, and 4. The scores are 0.58, 0.71, and 0.63. Which value of k does the silhouette score recommend, and why?
- Step 1: List the silhouette scores by k — k=2: 0.58, k=3: 0.71, k=4: 0.63.
- Step 2: Recall that a higher silhouette score indicates better-separated, more cohesive clusters.
- Step 3: Identify the maximum score — 0.71 occurs at k=3.
- Step 4: Conclude that k=3 is preferred by the silhouette criterion because it produces the highest average score, indicating the tightest within-cluster similarity and greatest between-cluster separation among the candidates tested.
Answer: k = 3 is recommended; it has the highest silhouette score (0.71), indicating the best cluster structure among the values tested.
2. After fitting k-means with k=3 on scaled data, you attach labels to the original dataframe and call groupby to get cluster means. Cluster 0 has a mean annual spending of $15,200 and mean visit frequency of 2.1. Cluster 1 has $42,800 and 9.7. Cluster 2 has $9,400 and 12.3. Write a one-sentence plain-language label for each cluster.
- Step 1: Read each cluster's values — Cluster 0 spends moderately and visits rarely; Cluster 1 spends heavily and visits often; Cluster 2 spends little but visits very frequently.
- Step 2: Translate numbers into behavior patterns a business audience recognizes.
- Step 3: Draft a label for Cluster 0 — 'Occasional moderate spenders: customers who visit infrequently and spend a moderate amount per year.'
- Step 4: Draft a label for Cluster 1 — 'High-value loyalists: customers who visit often and account for the highest average annual spending.'
- Step 5: Draft a label for Cluster 2 — 'Frequent low-spenders: customers who visit very often but spend the least per year, possibly browsing more than buying.'
Answer: Cluster 0 — Occasional moderate spenders. Cluster 1 — High-value loyalists. Cluster 2 — Frequent low-spenders.
3. A student runs k-means on city library usage data WITHOUT scaling the features first. Feature A is annual checkouts (range 0–12,000) and Feature B is library card age in years (range 0–30). Explain the mathematical reason this will likely produce misleading clusters.
- Step 1: Recall that k-means uses Euclidean distance to assign points to centroids.
- Step 2: Calculate example distances. Two records that differ by 1,000 checkouts contribute 1,000² = 1,000,000 to the squared distance. Two records that differ by 10 years of card age contribute 10² = 100 to the squared distance.
- Step 3: Compare the magnitudes — 1,000,000 vs. 100. The checkout feature contributes roughly 10,000 times more to the distance calculation than the card-age feature.
- Step 4: Conclude that the algorithm will effectively ignore card age and cluster records almost entirely on checkout volume, even if card age is a meaningful differentiator. Scaling (e.g., StandardScaler) removes this imbalance by converting each feature to mean 0 and standard deviation 1 before fitting.
Answer: Without scaling, annual checkouts (range 0–12,000) dominates the Euclidean distance calculation by a factor of thousands over card age (range 0–30), causing k-means to cluster almost entirely on the checkout variable and ignore card age.
4. You compute the silhouette score for a single data point in a 3-cluster solution. The average distance from that point to the other points in its cluster (a) is 4.2, and the average distance from that point to all points in the nearest other cluster (b) is 7.8. Calculate the silhouette score for this point.
- Step 1: Recall the formula: silhouette = (b − a) / max(a, b).
- Step 2: Compute the numerator: b − a = 7.8 − 4.2 = 3.6.
- Step 3: Identify max(a, b): max(4.2, 7.8) = 7.8.
- Step 4: Divide: 3.6 / 7.8 ≈ 0.462.
- Step 5: Interpret — a score of approximately 0.46 is positive and moderate, indicating this point fits its cluster reasonably well but is not extremely distant from the neighboring cluster.
Answer: Silhouette score ≈ 0.46, indicating the point fits its cluster reasonably well.
In class: Instructor demo: cluster the Mall Customers dataset (or similar retail dataset) with KMeans for k=2 through k=10, plot inertia (elbow curve) and silhouette scores, and select optimal k; students follow along and annotate. · Lab: students cluster a city public-dataset (e.g., 311 service requests or library usage by ZIP code) provided by the instructor, produce a scatter plot with cluster color coding, and compute summary statistics for each cluster. · Business memo exercise: students write a one-page plain-language memo addressed to a fictional city department director explaining what each cluster represents and one actionable recommendation per cluster.
Materials: Jupyter Lab, scikit-learn KMeans, yellowbrick library for visualizations, publicly available city dataset (instructor-curated), Mall Customers CSV
Check: Lab assessed on: correct elbow/silhouette plot, justified k selection, color-coded cluster scatter plot, and a memo with at least one data-backed recommendation per cluster; ≥ 70% on rubric required.
Practice check8
Answer each question, then check it. Nothing is recorded; this is your own practice.
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.