Skip to content

39. Unsupervised learning — Exercises

These exercises practice every idea of the unsupervised learning lesson. They use the course customers, products, stores and sensor readings, scikit-learn’s bundled iris, wine and digits data, and the make_blobs and make_moons generators.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and the starter code into a script and replace each to-do comment with your code.
  3. Run the script and compare your output with the expected output. Clustering results depend on random_state; use the values given in the task to get the same numbers.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Every exercise runs after this block. It imports the tools and fixes the pandas display.

import numpy as np
import pandas as pd
from sklearn.cluster import DBSCAN, KMeans
from sklearn.decomposition import PCA
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
FEATURES = [
"tenure_months",
"monthly_charges",
"logins_last_30d",
"avg_session_minutes",
"support_tickets",
]
Warm-up

Make 200 points around 3 centers with make_blobs(n_samples=200, centers=3, cluster_std=1.0, random_state=7). Fit KMeans with 3 clusters, n_init=10 and random_state=42. Print the cluster sizes in ascending order and the inertia rounded to 1 decimal.

Expected output
sizes: [66, 67, 67]
inertia: 384.3
Starter
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=200, centers=3, cluster_std=1.0, random_state=7)
# TODO: fit KMeans with 3 clusters, n_init=10, random_state=42
# TODO: print the sorted cluster sizes and the inertia
Hint 1

After fit, the labels are in model.labels_ and the inertia in model.inertia_.

Hint 2

np.bincount(labels) counts the rows per cluster id. Wrap it in sorted() for ascending order.

Solution
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=200, centers=3, cluster_std=1.0, random_state=7)
model = KMeans(n_clusters=3, n_init=10, random_state=42).fit(X)
sizes = sorted(np.bincount(model.labels_).tolist())
print("sizes:", sizes)
print("inertia:", round(model.inertia_, 1))
assert sum(sizes) == 200
assert model.cluster_centers_.shape == (3, 2)
Output
sizes: [66, 67, 67]
inertia: 384.3

How it works:

  1. make_blobs returns the points and their true centers. The underscore drops the true labels; clustering does not use them.
  2. fit runs k-means 10 times from different k-means++ starts and keeps the run with the lowest inertia.
  3. np.bincount counts how many rows have label 0, 1 and 2. Sorting removes the dependence on the arbitrary label numbers.

Alternative: fit_predict fits and returns the labels in one call: labels = KMeans(3, n_init=10, random_state=42).fit_predict(X).

M39-W02 · Predict the output: renamed clusters

Section titled “M39-W02 · Predict the output: renamed clusters”
Warm-up

Predict the output: two k-means runs with different seeds cluster the same blobs. Predict whether their first labels are equal, whether all labels are equal and what the adjusted Rand index (ARI) is. Then run the code.

Starter
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=150, centers=3, cluster_std=0.6, random_state=0)
labels_a = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(X)
labels_b = KMeans(n_clusters=3, n_init=10, random_state=7).fit_predict(X)
print(labels_a[:6], labels_b[:6])
print("identical arrays:", bool((labels_a == labels_b).all()))
print("ARI:", adjusted_rand_score(labels_a, labels_b))
# TODO: write your prediction for each line, then run the code

Acceptance criteria: Write your prediction line by line, then run the code. Your prediction matches the Output in the solution, and you can explain why the ARI and the array comparison disagree.

Hint 1

The blobs are well separated, so both runs find the same three groups.

Hint 2

Which group gets the name 0, 1 or 2 depends on where the centroids started. ARI compares groups, not names.

Solution
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=150, centers=3, cluster_std=0.6, random_state=0)
labels_a = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(X)
labels_b = KMeans(n_clusters=3, n_init=10, random_state=7).fit_predict(X)
print(labels_a[:6], labels_b[:6])
print("identical arrays:", bool((labels_a == labels_b).all()))
print("ARI:", adjusted_rand_score(labels_a, labels_b))
assert adjusted_rand_score(labels_a, labels_b) == 1.0
Output
[1 0 0 0 1 0] [2 1 1 1 2 1]
identical arrays: False
ARI: 1.0

How it works:

  1. Both runs put exactly the same points together, so the partition is identical.
  2. The names differ: the group that the first run calls 0 is group 1 in the second run, and group 1 became group 2. So an element-wise comparison says the arrays are not identical.
  3. ARI ignores names and compares only which rows share a cluster, so it is exactly 1.0.

M39-W03 · Compute one silhouette value by hand

Section titled “M39-W03 · Compute one silhouette value by hand”
Warm-up

Six daily sales totals (in thousands of USD) fall into two clusters: [1, 2, 3] and [10, 11, 13]. Compute the silhouette value of the first point (1) by hand with NumPy: a is its mean distance to the other points of its cluster, b its mean distance to the points of the other cluster. Print a, b and s, rounded to 3 decimals, and check s against sklearn.metrics.silhouette_samples.

Expected output
a = 1.500, b = 10.333, s = 0.855
sklearn: 0.855
Starter
from sklearn.metrics import silhouette_samples
X = np.array([[1.0], [2.0], [3.0], [10.0], [11.0], [13.0]])
labels = np.array([0, 0, 0, 1, 1, 1])
# TODO: a = mean distance from X[0] to X[1] and X[2]
# TODO: b = mean distance from X[0] to the three points of cluster 1
# TODO: s = (b - a) / max(a, b); compare with silhouette_samples(X, labels)[0]
Hint 1

In one dimension the distance is np.abs(x - y). Select the rows of a cluster with a mask such as labels == 1.

Hint 2

Leave the point itself out of a: use X[1:3], not X[0:3].

Solution
from sklearn.metrics import silhouette_samples
X = np.array([[1.0], [2.0], [3.0], [10.0], [11.0], [13.0]])
labels = np.array([0, 0, 0, 1, 1, 1])
point = X[0, 0]
a = np.abs(X[1:3, 0] - point).mean()
b = np.abs(X[labels == 1, 0] - point).mean()
s = (b - a) / max(a, b)
print(f"a = {a:.3f}, b = {b:.3f}, s = {s:.3f}")
print(f"sklearn: {silhouette_samples(X, labels)[0]:.3f}")
assert np.isclose(s, silhouette_samples(X, labels)[0])
Output
a = 1.500, b = 10.333, s = 0.855
sklearn: 0.855

How it works:

  1. a averages the distances 1 and 2 to the other members of cluster 0.
  2. b averages the distances 9, 10 and 12 to the members of cluster 1.
  3. b is much larger than a, so s is close to 1: the point sits well inside its own cluster.

M39-W04 · Fix the bug: clusters that only see tenure

Section titled “M39-W04 · Fix the bug: clusters that only see tenure”
Warm-up

Fix the bug: this code clusters the customers on the five FEATURES without scaling, so tenure and charges decide everything. Put a StandardScaler before the KMeans in one pipeline. Print the sorted cluster sizes and the mean support tickets per cluster, sorted, rounded to 2 decimals.

Expected output
sizes: [840, 982, 1399, 1779]
mean tickets per cluster: [0.62, 0.96, 0.98, 2.37]
Starter
customers = pd.read_csv("data/customers.csv")
model = KMeans(n_clusters=4, n_init=10, random_state=42)
labels = model.fit_predict(customers[FEATURES]) # bug: raw units
# TODO: scale inside a pipeline, then print sizes and mean tickets per cluster
Hint 1

make_pipeline(StandardScaler(), KMeans(...)) returns one estimator. fit_predict works on it.

Hint 2

Group the tickets by the labels: customers.groupby(labels)["support_tickets"].mean().

Solution
customers = pd.read_csv("data/customers.csv")
pipe = make_pipeline(StandardScaler(), KMeans(n_clusters=4, n_init=10, random_state=42))
labels = pipe.fit_predict(customers[FEATURES])
sizes = sorted(np.bincount(labels).tolist())
tickets = customers.groupby(labels)["support_tickets"].mean().sort_values()
print("sizes:", sizes)
print("mean tickets per cluster:", tickets.round(2).tolist())
assert sum(sizes) == len(customers)
assert tickets.max() > 2
Output
sizes: [840, 982, 1399, 1779]
mean tickets per cluster: [0.62, 0.96, 0.98, 2.37]

How it works:

  1. The pipeline standardizes each feature, then clusters. The scaler is fitted on the same data, inside the same fit call.
  2. With every column on the same scale, one cluster now gathers the customers with many support tickets (more than 2 on average).
  3. In the buggy version, tickets (standard deviation 1.2) are invisible next to tenure (about 20) and charges (about 23).

Alternative: scale by hand with StandardScaler().fit_transform(customers[FEATURES]). A pipeline is safer, because it keeps the scaler and the model together for predict on new customers.

Warm-up

Group the 12 stores of data/stores.csv by floor area (size_sqm). Build a Ward linkage with SciPy, cut it into 3 clusters with fcluster and print the cities of each cluster, smallest cluster id first.

Expected output
1 ['Minneapolis', 'Detroit', 'Miami', 'Boston', 'Philadelphia', 'San Francisco', 'Denver'] 1728
2 ['Atlanta', 'Seattle'] 2390
3 ['Chicago', 'Houston', 'New York'] 3116
Starter
from scipy.cluster.hierarchy import fcluster, linkage
stores = pd.read_csv("data/stores.csv")
# TODO: Z = linkage(...) on the size_sqm column, method="ward"
# TODO: cut into 3 clusters and print the cities per cluster
Hint 1

linkage needs a 2-D input: pass stores[["size_sqm"]] (double brackets), not a Series.

Hint 2

fcluster(Z, t=3, criterion="maxclust") returns cluster ids starting at 1. Group the city names by them.

Solution
from scipy.cluster.hierarchy import fcluster, linkage
stores = pd.read_csv("data/stores.csv")
Z = linkage(stores[["size_sqm"]], method="ward")
stores["group"] = fcluster(Z, t=3, criterion="maxclust")
for group, part in stores.groupby("group"):
print(group, part["city"].tolist(), int(part["size_sqm"].mean()))
assert stores["group"].nunique() == 3
Output
1 ['Minneapolis', 'Detroit', 'Miami', 'Boston', 'Philadelphia', 'San Francisco', 'Denver'] 1728
2 ['Atlanta', 'Seattle'] 2390
3 ['Chicago', 'Houston', 'New York'] 3116

How it works:

  1. linkage merges the stores bottom-up. Ward linkage merges the pair whose merge raises the inertia least.
  2. fcluster with criterion="maxclust" cuts the tree into at most 3 flat clusters.
  3. The loop prints the cities and the mean floor area of each group: small, medium and large stores.

Alternative: scikit-learn gives the same flat cut, numbered from 0: AgglomerativeClustering(n_clusters=3, linkage="ward").fit_predict(stores[["size_sqm"]]).

Warm-up

A DBSCAN run on 10 delivery addresses returned these labels: [0, 0, 1, -1, 1, 1, 2, -1, 0, 2]. Compute the number of clusters (noise does not count), the number of noise points and the noise share. Print them in one line.

Expected output
clusters: 3, noise: 2, noise share: 20%
Starter
labels = np.array([0, 0, 1, -1, 1, 1, 2, -1, 0, 2])
# TODO: n_clusters, n_noise and noise_share
Hint 1

set(labels) gives the distinct labels. Remove -1 before you count.

Hint 2

(labels == -1).sum() counts the noise points; .mean() gives their share.

Solution
labels = np.array([0, 0, 1, -1, 1, 1, 2, -1, 0, 2])
n_clusters = len(set(labels.tolist()) - {-1})
n_noise = int((labels == -1).sum())
noise_share = (labels == -1).mean()
print(f"clusters: {n_clusters}, noise: {n_noise}, noise share: {noise_share:.0%}")
assert (n_clusters, n_noise) == (3, 2)
Output
clusters: 3, noise: 2, noise share: 20%

How it works:

  1. The distinct labels are -1, 0, 1 and 2. Removing -1 leaves 3 clusters.
  2. A comparison gives a Boolean array; sum counts the True values and mean gives their share.

Alternative: np.unique(labels, return_counts=True) lists every label with its count in one call.

M39-W07 · Components for 95% of the variance

Section titled “M39-W07 · Components for 95% of the variance”
Warm-up

The wine data (load_wine) has 178 wines with 13 chemical measurements in different units. Scale the features, fit a PCA and print the cumulative explained variance of the first 3 components and the number of components needed for at least 95%.

Expected output
first 3 cumulative: [0.362 0.554 0.665]
components for 95%: 10
Starter
from sklearn.datasets import load_wine
X, _ = load_wine(return_X_y=True)
# TODO: scale, fit PCA, compute the cumulative explained variance ratio
# TODO: print the first 3 cumulative values and the count for 95%
Hint 1

pca.explained_variance_ratio_.cumsum() gives the running total.

Hint 2

np.argmax(cumulative >= 0.95) returns the first index that reaches 95%. Add 1 to turn the index into a count.

Solution
from sklearn.datasets import load_wine
X, _ = load_wine(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)
cumulative = PCA().fit(X_scaled).explained_variance_ratio_.cumsum()
needed = int(np.argmax(cumulative >= 0.95)) + 1
print("first 3 cumulative:", cumulative[:3].round(3))
print("components for 95%:", needed)
assert needed == PCA(n_components=0.95).fit(X_scaled).n_components_
Output
first 3 cumulative: [0.362 0.554 0.665]
components for 95%: 10

How it works:

  1. Scaling gives each of the 13 measurements the same weight; without it, the proline column (values in the hundreds and thousands) would take almost all the variance.
  2. The cumulative sum shows how much variance the first k components keep together.
  3. The assert checks the result against PCA(n_components=0.95), which picks the same number by itself.

Alternative: fit PCA(n_components=0.95) directly and read n_components_.

Warm-up

A temperature sensor sent these 12 readings (°C): 21.0, 21.4, 20.9, 21.7, 22.0, 21.8, 31.6, 21.5, 21.1, 20.8, 21.3, 21.6. Fit an IsolationForest(n_estimators=100, contamination=0.1, random_state=42) on them and print the readings that it flags.

Expected output
flagged: [22. 31.6]
Starter
from sklearn.ensemble import IsolationForest
readings = np.array([21.0, 21.4, 20.9, 21.7, 22.0, 21.8, 31.6, 21.5, 21.1, 20.8,
21.3, 21.6])
# TODO: fit on a 2-D array of shape (12, 1), then print the flagged readings
Hint 1

scikit-learn wants a 2-D input: readings.reshape(-1, 1).

Hint 2

fit_predict returns -1 for anomalies. Use == -1 as a mask on readings.

Solution
from sklearn.ensemble import IsolationForest
readings = np.array([21.0, 21.4, 20.9, 21.7, 22.0, 21.8, 31.6, 21.5, 21.1, 20.8,
21.3, 21.6])
iso = IsolationForest(n_estimators=100, contamination=0.1, random_state=42)
flags = iso.fit_predict(readings.reshape(-1, 1)) == -1
print("flagged:", readings[flags])
assert 31.6 in readings[flags]
Output
flagged: [22. 31.6]

How it works:

  1. The model wants rows and columns, so the 12 values become 12 rows with 1 column.
  2. contamination=0.1 sets the threshold so that about 10% of 12 readings (here 2) count as anomalies.
  3. 31.6 °C is isolated with very few random cuts, so it gets the lowest score. The second flag, 22.0 °C, is the highest normal reading: contamination forces a quota of 2, so one normal reading must be flagged.

Alternative: compare with a robust z-score (module 26): (x - median) / MAD. For one feature it is simpler and needs no quota.

Core

Scale the 13 features of load_wine. For k from 2 to 6, fit KMeans(n_clusters=k, n_init=10, random_state=42) and collect the inertia and the silhouette score in a DataFrame. Print it, then print the k with the highest silhouette.

Expected output
k inertia silhouette
2 1658.759 0.259
3 1277.928 0.285
4 1175.428 0.260
5 1109.513 0.202
6 1046.002 0.237
best k by silhouette: 3
Starter
from sklearn.datasets import load_wine
X, _ = load_wine(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)
rows = []
# TODO: loop over k = 2..6, append (k, inertia, silhouette)
# TODO: build the DataFrame, print it and the best k
Hint 1

silhouette_score(X_scaled, model.labels_) scores one fitted model.

Hint 2

table.loc[table["silhouette"].idxmax(), "k"] returns the k of the best row.

Solution
from sklearn.datasets import load_wine
X, _ = load_wine(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)
rows = []
for k in range(2, 7):
model = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X_scaled)
rows.append((k, model.inertia_, silhouette_score(X_scaled, model.labels_)))
table = pd.DataFrame(rows, columns=["k", "inertia", "silhouette"])
best_k = int(table.loc[table["silhouette"].idxmax(), "k"])
print(table.round(3).to_string(index=False))
print("best k by silhouette:", best_k)
assert table["inertia"].is_monotonic_decreasing
assert best_k == 3
Output
k inertia silhouette
2 1658.759 0.259
3 1277.928 0.285
4 1175.428 0.260
5 1109.513 0.202
6 1046.002 0.237
best k by silhouette: 3

How it works:

  1. Each pass fits one k-means model and scores it with inertia and silhouette.
  2. Inertia falls at every step, so it cannot pick k alone; the first assert checks this.
  3. The silhouette peaks at k = 3, which matches the three grape cultivars in the data. The elbow in the inertia column is also near 3: the drop from 2 to 3 is much bigger than from 3 to 4.

Alternative: score several k values in one line with a list comprehension and max(..., key=...). The DataFrame is easier to read and to plot.

M39-C02 · Build a profile table with ratios

Section titled “M39-C02 · Build a profile table with ratios”
Core

Cluster the customers into 4 groups on the scaled FEATURES (n_init=10, random_state=42). Build a profile table with the median of each feature per cluster, the cluster size and the churn rate. Then print a second table: each cluster mean divided by the overall mean of that feature, rounded to 2 decimals.

Expected output
tenure_months monthly_charges logins_last_30d avg_session_minutes support_tickets \
cluster
0 15.0 58.02 20.0 24.30 1.0
1 14.0 69.61 8.0 11.00 1.0
2 53.0 56.45 9.0 12.05 1.0
3 10.0 40.44 9.0 11.80 2.0
size churn_rate
cluster
0 840 0.129
1 1779 0.230
2 982 0.048
3 1399 0.285
tenure_months monthly_charges logins_last_30d avg_session_minutes support_tickets
cluster
0 0.84 0.97 1.87 1.74 0.79
1 0.66 1.23 0.77 0.81 0.50
2 2.35 0.95 0.88 0.90 0.78
3 0.58 0.76 0.86 0.86 1.92
Starter
customers = pd.read_csv("data/customers.csv")
pipe = make_pipeline(StandardScaler(), KMeans(n_clusters=4, n_init=10, random_state=42))
customers["cluster"] = pipe.fit_predict(customers[FEATURES])
# TODO: medians per cluster, plus size and churn_rate
# TODO: ratio table: cluster means / overall means
Hint 1

customers.groupby("cluster")[FEATURES].median() builds the first part. Add columns with value_counts() and a churn mean.

Hint 2

Dividing a DataFrame by a Series aligns the Series index with the DataFrame columns: means / customers[FEATURES].mean().

Solution
customers = pd.read_csv("data/customers.csv")
pipe = make_pipeline(StandardScaler(), KMeans(n_clusters=4, n_init=10, random_state=42))
customers["cluster"] = pipe.fit_predict(customers[FEATURES])
groups = customers.groupby("cluster")
profile = groups[FEATURES].median()
profile["size"] = groups.size()
profile["churn_rate"] = groups["churned"].mean().round(3)
ratios = groups[FEATURES].mean() / customers[FEATURES].mean()
print(profile)
print(ratios.round(2))
assert profile["size"].sum() == len(customers)
assert (ratios.max() > 1.5).any()
Output
tenure_months monthly_charges logins_last_30d avg_session_minutes support_tickets \
cluster
0 15.0 58.02 20.0 24.30 1.0
1 14.0 69.61 8.0 11.00 1.0
2 53.0 56.45 9.0 12.05 1.0
3 10.0 40.44 9.0 11.80 2.0
size churn_rate
cluster
0 840 0.129
1 1779 0.230
2 982 0.048
3 1399 0.285
tenure_months monthly_charges logins_last_30d avg_session_minutes support_tickets
cluster
0 0.84 0.97 1.87 1.74 0.79
1 0.66 1.23 0.77 0.81 0.50
2 2.35 0.95 0.88 0.90 0.78
3 0.58 0.76 0.86 0.86 1.92

How it works:

  1. groupby("cluster") splits the rows once; the same groups object gives the medians, the sizes and the churn rates.
  2. Medians resist the long tails of tenure and logins; means show the totals better. Use the one that your audience reads more easily, and say which one you used.
  3. The ratio table divides each cluster mean by the overall mean, column by column. A ratio of 2.4 on tenure says “this group has stayed 2.4 times longer than the average customer”.

Alternative: customers.groupby("cluster")[FEATURES].agg(["median", "mean"]) shows both statistics side by side, with a two-level column index.

M39-C03 · Name clusters from their profile

Section titled “M39-C03 · Name clusters from their profile”
Core

Write a function name_cluster(ratios_row) that takes one row of a ratio table (cluster mean / overall mean) and returns a name such as "high support_tickets, low monthly_charges": the feature with the largest ratio and the feature with the smallest ratio. Apply it to the ratio table of 4 customer clusters and print the names.

Expected output
0 high logins_last_30d, low support_tickets
1 high monthly_charges, low support_tickets
2 high tenure_months, low support_tickets
3 high support_tickets, low tenure_months
Starter
customers = pd.read_csv("data/customers.csv")
pipe = make_pipeline(StandardScaler(), KMeans(n_clusters=4, n_init=10, random_state=42))
labels = pipe.fit_predict(customers[FEATURES])
ratios = customers.groupby(labels)[FEATURES].mean() / customers[FEATURES].mean()
def name_cluster(ratios_row: pd.Series) -> str:
# TODO: use idxmax() and idxmin() on the row
...
# TODO: apply name_cluster to every row and print the result
Hint 1

row.idxmax() returns the column label of the largest value in a Series.

Hint 2

ratios.apply(name_cluster, axis=1) calls the function once per row.

Solution
customers = pd.read_csv("data/customers.csv")
pipe = make_pipeline(StandardScaler(), KMeans(n_clusters=4, n_init=10, random_state=42))
labels = pipe.fit_predict(customers[FEATURES])
ratios = customers.groupby(labels)[FEATURES].mean() / customers[FEATURES].mean()
def name_cluster(ratios_row: pd.Series) -> str:
return f"high {ratios_row.idxmax()}, low {ratios_row.idxmin()}"
names = ratios.apply(name_cluster, axis=1)
for cluster_id, name in names.items():
print(cluster_id, name)
assert names.str.startswith("high ").all()
Output
0 high logins_last_30d, low support_tickets
1 high monthly_charges, low support_tickets
2 high tenure_months, low support_tickets
3 high support_tickets, low tenure_months

How it works:

  1. idxmax and idxmin find the most and the least distinctive feature of each cluster.
  2. apply(..., axis=1) passes each row as a Series whose index is the feature names.
  3. The automatic names are a first draft. A person turns “high logins_last_30d, low support_tickets” into “Power users” after reading the full profile.

Alternative: rank features by distance from 1 ((ratios_row - 1).abs()) to name the cluster after its most unusual feature, high or low.

M39-C04 · Refactor: vectorize the assignment step

Section titled “M39-C04 · Refactor: vectorize the assignment step”
Core

Refactor: the starter assigns each point to its nearest centroid with two nested loops. Replace the loops with NumPy broadcasting. Check that your labels equal KMeans.predict and print how many points each centroid gets.

Expected output
distance table shape: (500, 4)
points per centroid: [125 125 125 125]
Starter
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=500, centers=4, random_state=42)
model = KMeans(n_clusters=4, n_init=10, random_state=42).fit(X)
centroids = model.cluster_centers_
labels = []
for point in X: # loop version: slow for big data
best, best_dist = 0, float("inf")
for j, centroid in enumerate(centroids):
dist = ((point - centroid) ** 2).sum()
if dist < best_dist:
best, best_dist = j, dist
labels.append(best)
# TODO: compute the same labels with broadcasting, no Python loops
Hint 1

X[:, None, :] - centroids[None, :, :] has shape (500, 4, 2): every point minus every centroid.

Hint 2

Square, sum over the last axis to get a (500, 4) distance table, then argmin(axis=1).

Solution
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=500, centers=4, random_state=42)
model = KMeans(n_clusters=4, n_init=10, random_state=42).fit(X)
centroids = model.cluster_centers_
squared = ((X[:, None, :] - centroids[None, :, :]) ** 2).sum(axis=2)
labels = squared.argmin(axis=1)
print("distance table shape:", squared.shape)
print("points per centroid:", np.bincount(labels))
assert (labels == model.predict(X)).all()
Output
distance table shape: (500, 4)
points per centroid: [125 125 125 125]

How it works:

  1. Adding axes with None makes the shapes (500, 1, 2) and (1, 4, 2). Broadcasting (module 23) stretches them to (500, 4, 2).
  2. Summing the squared differences over the last axis gives the squared distance from every point to every centroid.
  3. argmin(axis=1) picks the nearest centroid per row. The square root is not needed: it does not change which distance is smallest.

Alternative: sklearn.metrics.pairwise_distances_argmin(X, centroids) does the same in one call, in chunks that save memory.

Core

Write kmeans(X, init_centroids, n_iter) with NumPy: repeat the assign step and the update step n_iter times, then return the labels, the centroids and the inertia. Start from the first 3 rows of the shuffled blobs. Compare your inertia with scikit-learn’s KMeans started from the same centroids (init=start, n_init=1).

Expected output
my inertia: 813.26
sklearn inertia: 813.26
same partition: True
Starter
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=300, centers=3, cluster_std=1.2, random_state=1)
start = X[:3].copy()
def kmeans(X, init_centroids, n_iter=20):
centroids = init_centroids.copy()
for _ in range(n_iter):
# TODO: assign step (nearest centroid)
# TODO: update step (mean of the rows of each cluster)
...
# TODO: compute the inertia and return labels, centroids, inertia
# TODO: run it, then compare with KMeans(n_clusters=3, init=start, n_init=1)
Hint 1

Reuse the broadcasting trick from M39-C04 for the assign step.

Hint 2

The update step is np.array([X[labels == j].mean(axis=0) for j in range(k)]). The inertia is the sum of the squared distances from each row to its own centroid.

Solution
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=300, centers=3, cluster_std=1.2, random_state=1)
start = X[:3].copy()
def kmeans(X, init_centroids, n_iter=20):
centroids = init_centroids.copy()
k = len(centroids)
for _ in range(n_iter):
squared = ((X[:, None, :] - centroids[None, :, :]) ** 2).sum(axis=2)
labels = squared.argmin(axis=1)
centroids = np.array([X[labels == j].mean(axis=0) for j in range(k)])
squared = ((X[:, None, :] - centroids[None, :, :]) ** 2).sum(axis=2)
labels = squared.argmin(axis=1)
inertia = squared[np.arange(len(X)), labels].sum()
return labels, centroids, inertia
labels, centroids, inertia = kmeans(X, start)
reference = KMeans(n_clusters=3, init=start, n_init=1).fit(X)
print("my inertia: ", round(float(inertia), 2))
print("sklearn inertia:", round(float(reference.inertia_), 2))
print("same partition:", adjusted_rand_score(labels, reference.labels_) == 1.0)
assert np.isclose(inertia, reference.inertia_)
Output
my inertia: 813.26
sklearn inertia: 813.26
same partition: True

How it works:

  1. The assign step builds the distance table and takes the nearest centroid per row.
  2. The update step moves each centroid to the mean of its rows. 20 passes are plenty for three blobs; the real KMeans stops when the centroids stop moving.
  3. squared[np.arange(len(X)), labels] picks, for each row, the distance to its own centroid. Their sum is the inertia.
  4. With the same start, scikit-learn finds the same partition and the same inertia.

Alternative: stop early when np.allclose(new_centroids, centroids). Production code also handles an empty cluster, which this version does not.

M39-C06 · Choose the linkage for curved shapes

Section titled “M39-C06 · Choose the linkage for curved shapes”
Core

Choose a method and justify it: cluster make_moons(n_samples=300, noise=0.06, random_state=42) into 2 groups with AgglomerativeClustering and each of the four linkages. Print the ARI against the true moons for each linkage, then explain which linkage you would use and why.

Expected output
ward: ARI = 0.597
complete: ARI = 0.311
average: ARI = 0.597
single: ARI = 1.000
Starter
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=300, noise=0.06, random_state=42)
# TODO: for each linkage in ward, complete, average, single: fit 2 clusters, print ARI
Hint 1

AgglomerativeClustering(n_clusters=2, linkage="single").fit_predict(X) returns the labels.

Hint 2

Think about what “the smallest distance between two clusters” does along a dense curve.

Solution
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=300, noise=0.06, random_state=42)
scores = {}
for link in ("ward", "complete", "average", "single"):
labels = AgglomerativeClustering(n_clusters=2, linkage=link).fit_predict(X)
scores[link] = adjusted_rand_score(y, labels)
print(f"{link:>8}: ARI = {scores[link]:.3f}")
assert max(scores, key=scores.get) == "single"
Output
ward: ARI = 0.597
complete: ARI = 0.311
average: ARI = 0.597
single: ARI = 1.000

How it works:

  1. Ward, complete and average linkage prefer compact groups, so they cut each moon somewhere in the middle.
  2. Single linkage joins the two clusters with the closest pair of points. Along a dense curve, every point has a close neighbor, so the merges follow the moon and never jump the gap.
  3. Choice: single linkage for well-separated, curved groups. It chains when a few noise points form a bridge, so check the data for bridges first, or use DBSCAN, which has a noise label.

M39-C07 · Pick eps from the k-distance curve

Section titled “M39-C07 · Pick eps from the k-distance curve”
Core

Make 3 blobs with make_blobs(n_samples=300, centers=3, cluster_std=0.7, random_state=7), add 15 random points from rng.uniform(-12, 12, size=(15, 2)) with rng = np.random.default_rng(42) and scale the result. With min_samples=5, set eps to the 95th percentile of the 5th-nearest-neighbor distances, rounded to 2 decimals. Run DBSCAN and print eps, the number of clusters and the number of noise points.

Expected output
eps: 0.25
clusters: 3 noise points: 14
Starter
from sklearn.datasets import make_blobs
from sklearn.neighbors import NearestNeighbors
X_blobs, _ = make_blobs(n_samples=300, centers=3, cluster_std=0.7, random_state=7)
rng = np.random.default_rng(42)
stray = rng.uniform(-12, 12, size=(15, 2))
X = StandardScaler().fit_transform(np.vstack([X_blobs, stray]))
# TODO: 5th-nearest-neighbor distances, eps = 95th percentile
# TODO: DBSCAN(eps=eps, min_samples=5); print eps, clusters, noise
Hint 1

NearestNeighbors(n_neighbors=5).fit(X).kneighbors(X) returns distances of shape (315, 5). The last column is the 5th neighbor; the first is the point itself.

Hint 2

np.percentile(k_dist, 95) gives the cut. Count clusters as the distinct labels other than -1.

Solution
from sklearn.datasets import make_blobs
from sklearn.neighbors import NearestNeighbors
X_blobs, _ = make_blobs(n_samples=300, centers=3, cluster_std=0.7, random_state=7)
rng = np.random.default_rng(42)
stray = rng.uniform(-12, 12, size=(15, 2))
X = StandardScaler().fit_transform(np.vstack([X_blobs, stray]))
distances, _ = NearestNeighbors(n_neighbors=5).fit(X).kneighbors(X)
eps = round(float(np.percentile(distances[:, -1], 95)), 2)
labels = DBSCAN(eps=eps, min_samples=5).fit_predict(X)
n_clusters = len(set(labels.tolist()) - {-1})
print("eps:", eps)
print("clusters:", n_clusters, "noise points:", int((labels == -1).sum()))
assert n_clusters == 3
Output
eps: 0.25
clusters: 3 noise points: 14

How it works:

  1. The 5th-nearest-neighbor distance is small inside a blob and large for a stray point.
  2. The 95th percentile assumes that roughly 5% of the points are noise. Here 15 of 315 points (4.8%) are random, so the cut lands at the bend of the curve.
  3. DBSCAN finds the 3 blobs and marks the far-away strays as noise. Strays that fall inside or next to a blob join it.

Alternative: plot the sorted distances and read the bend by eye, as in the lesson. The percentile rule is a quick default when you can estimate the noise share.

M39-C08 · Fix the bug: DBSCAN sees only noise

Section titled “M39-C08 · Fix the bug: DBSCAN sees only noise”
Core

Fix the bug: the starter clusters two features of delivery stops, distance from the depot (km) and parcel value (USD), with DBSCAN(eps=0.5, min_samples=5). It finds no real clusters. Fix it so that DBSCAN finds the 3 groups, and print the label counts.

Expected output
buggy noise share: 1.0
{0: 80, 1: 80, 2: 80}
Starter
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=240, centers=3, cluster_std=0.5, random_state=3)
X[:, 1] = X[:, 1] * 100 + 1_000 # parcel value in USD
labels = DBSCAN(eps=0.5, min_samples=5).fit_predict(X) # bug
print(np.unique(labels, return_counts=True))
# TODO: fix the bug and print the label counts
Hint 1

Print the buggy label counts first. What does -1 everywhere tell you about eps compared with the spread of the second column?

Hint 2

eps is one radius in every direction. Put both columns on the same scale.

Solution
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=240, centers=3, cluster_std=0.5, random_state=3)
X[:, 1] = X[:, 1] * 100 + 1_000 # parcel value in USD
buggy = DBSCAN(eps=0.5, min_samples=5).fit_predict(X)
print("buggy noise share:", round(float((buggy == -1).mean()), 2))
fixed = DBSCAN(eps=0.5, min_samples=5).fit_predict(StandardScaler().fit_transform(X))
values, counts = np.unique(fixed, return_counts=True)
print(dict(zip(values.tolist(), counts.tolist())))
assert len(set(fixed.tolist()) - {-1}) == 3
Output
buggy noise share: 1.0
{0: 80, 1: 80, 2: 80}

How it works:

  1. In raw units, parcel values differ by tens of dollars between neighbors, so no point has 5 neighbors within 0.5. Every point becomes noise (share 1.0).
  2. After StandardScaler, both columns have standard deviation 1, and a radius of 0.5 means the same thing in both directions.
  3. DBSCAN then finds the 3 groups.

Alternative: put the steps in a pipeline: make_pipeline(StandardScaler(), DBSCAN(eps=0.5, min_samples=5)).fit_predict(X).

M39-C09 · Let BIC choose the number of components

Section titled “M39-C09 · Let BIC choose the number of components”
Core

Make stretched clusters: make_blobs(n_samples=400, centers=4, random_state=170), then multiply by the matrix [[0.6, -0.6], [-0.4, 0.8]]. Fit GaussianMixture(n_components=k, covariance_type="full", random_state=42) for k from 1 to 7 and print the BIC of each. Print the k with the lowest BIC.

Expected output
{1: 3688.5, 2: 2915.8, 3: 2594.0, 4: 2366.6, 5: 2398.0, 6: 2429.6, 7: 2460.4}
lowest BIC at k = 4
Starter
from sklearn.datasets import make_blobs
from sklearn.mixture import GaussianMixture
X, y = make_blobs(n_samples=400, centers=4, random_state=170)
X = X @ np.array([[0.6, -0.6], [-0.4, 0.8]])
# TODO: BIC for k = 1..7, then the best k
Hint 1

GaussianMixture(...).fit(X).bic(X) returns one number. Lower is better.

Hint 2

Store the values in a dict {k: bic} and use min(bics, key=bics.get).

Solution
from sklearn.datasets import make_blobs
from sklearn.mixture import GaussianMixture
X, y = make_blobs(n_samples=400, centers=4, random_state=170)
X = X @ np.array([[0.6, -0.6], [-0.4, 0.8]])
bics = {}
for k in range(1, 8):
gmm = GaussianMixture(n_components=k, covariance_type="full", random_state=42)
bics[k] = gmm.fit(X).bic(X)
print({k: round(v, 1) for k, v in bics.items()})
best_k = min(bics, key=bics.get)
print("lowest BIC at k =", best_k)
assert best_k == 4
Output
{1: 3688.5, 2: 2915.8, 3: 2594.0, 4: 2366.6, 5: 2398.0, 6: 2429.6, 7: 2460.4}
lowest BIC at k = 4

How it works:

  1. The matrix product stretches and tilts the round blobs into ellipses.
  2. Each fit gives a BIC: fit quality minus a penalty for the number of parameters.
  3. BIC drops steeply up to 4 components and rises after that: extra components buy too little likelihood for their cost.

Alternative: GaussianMixture.aic(X) uses a smaller penalty and tends to choose more components. BIC is the usual choice for clustering.

M39-C10 · Find the customers on the fence

Section titled “M39-C10 · Find the customers on the fence”
Core

Fit GaussianMixture(n_components=4, covariance_type="full", random_state=42) on the scaled FEATURES of the customers. A customer is “on the fence” when their highest component probability is below 0.8. Print the share of such customers and the churn rate of the fence group and of the rest.

Expected output
on the fence: 41.4%
False 0.203
True 0.178
Name: churn_rate, dtype: float64
Starter
from sklearn.mixture import GaussianMixture
customers = pd.read_csv("data/customers.csv")
X = StandardScaler().fit_transform(customers[FEATURES])
# TODO: fit the GMM, take predict_proba(X).max(axis=1)
# TODO: share on the fence, churn rate of each group
Hint 1

gmm.predict_proba(X) has one column per component. .max(axis=1) keeps the top probability per customer.

Hint 2

customers.groupby(on_fence)["churned"].mean() splits the churn rate by a Boolean array.

Solution
from sklearn.mixture import GaussianMixture
customers = pd.read_csv("data/customers.csv")
X = StandardScaler().fit_transform(customers[FEATURES])
gmm = GaussianMixture(n_components=4, covariance_type="full", random_state=42).fit(X)
top = gmm.predict_proba(X).max(axis=1)
on_fence = top < 0.8
print(f"on the fence: {on_fence.mean():.1%}")
print(customers.groupby(on_fence)["churned"].mean().round(3).rename("churn_rate"))
assert 0 < on_fence.mean() < 1
Output
on the fence: 41.4%
False 0.203
True 0.178
Name: churn_rate, dtype: float64

How it works:

  1. predict_proba gives each customer a probability for each of the 4 components.
  2. A top probability below 0.8 means the customer sits between components: a hard label would hide this.
  3. More than 40% of the customers are on the fence: the behavior data has no sharp borders, as the low silhouette scores in the lesson showed. Their churn rate (17.8%) is close to the rest (20.3%), so here the uncertainty is not a churn signal. It is a warning that a hard segment label oversimplifies many customers.

M39-C11 · Interpret the PCA loadings of wine

Section titled “M39-C11 · Interpret the PCA loadings of wine”
Core

Interpret a result: fit a 2-component PCA on the scaled wine features (load_wine(as_frame=True)). For each of PC1 and PC2, print the 3 features with the largest absolute loading and their loading. Then say in one sentence what each component measures.

Expected output
PC1 {'flavanoids': 0.42, 'total_phenols': 0.39, 'od280/od315_of_diluted_wines': 0.38}
PC2 {'color_intensity': 0.53, 'alcohol': 0.48, 'proline': 0.36}
Starter
from sklearn.datasets import load_wine
wine = load_wine(as_frame=True)
X_scaled = StandardScaler().fit_transform(wine.data)
pca = PCA(n_components=2).fit(X_scaled)
# TODO: loadings DataFrame (features x components)
# TODO: top 3 features by absolute loading per component
Hint 1

pd.DataFrame(pca.components_.T, index=wine.data.columns, columns=["PC1", "PC2"]) puts features in rows.

Hint 2

loadings["PC1"].abs().nlargest(3).index gives the top features; then look up their signed values.

Solution
from sklearn.datasets import load_wine
wine = load_wine(as_frame=True)
X_scaled = StandardScaler().fit_transform(wine.data)
pca = PCA(n_components=2).fit(X_scaled)
loadings = pd.DataFrame(
pca.components_.T, index=wine.data.columns, columns=["PC1", "PC2"]
)
for pc in ("PC1", "PC2"):
top = loadings.loc[loadings[pc].abs().nlargest(3).index, pc]
print(pc, top.round(2).to_dict())
assert np.allclose(np.linalg.norm(pca.components_, axis=1), 1)
Output
PC1 {'flavanoids': 0.42, 'total_phenols': 0.39, 'od280/od315_of_diluted_wines': 0.38}
PC2 {'color_intensity': 0.53, 'alcohol': 0.48, 'proline': 0.36}

How it works:

  1. Each row of components_ is one component; its 13 numbers are the loadings, and each row has length 1 (the assert checks it).
  2. Sorting by absolute value finds the features that drive the component, whatever their sign.
  3. Interpretation: PC1 is driven by the phenolic compounds (flavanoids, total phenols, and the related OD280/OD315 measure) all with the same sign: it measures the phenol content. PC2 is driven by color intensity, alcohol and proline: it measures the strength and color of the wine. The sign of a whole component is arbitrary.

M39-C12 · PCA inside a clustering pipeline

Section titled “M39-C12 · PCA inside a clustering pipeline”
Core

Cluster the wines into 3 groups in three ways and print the ARI against the true cultivar for each: k-means on raw features, k-means on scaled features, and scaled features → PCA(n_components=2) → k-means. Use n_init=10, random_state=42 and make_pipeline for each.

Expected output
raw: ARI = 0.371
scaled: ARI = 0.897
scaled + PCA(2): ARI = 0.895
Starter
from sklearn.datasets import load_wine
X, y = load_wine(return_X_y=True)
pipelines = {
"raw": ..., # TODO
"scaled": ..., # TODO
"scaled + PCA(2)": ..., # TODO
}
# TODO: fit_predict each pipeline and print its ARI
Hint 1

make_pipeline(KMeans(...)) with a single step works too, so all three entries have the same interface.

Hint 2

make_pipeline(StandardScaler(), PCA(n_components=2), KMeans(...)) chains all three steps.

Solution
from sklearn.datasets import load_wine
X, y = load_wine(return_X_y=True)
def km():
return KMeans(n_clusters=3, n_init=10, random_state=42)
pipelines = {
"raw": make_pipeline(km()),
"scaled": make_pipeline(StandardScaler(), km()),
"scaled + PCA(2)": make_pipeline(StandardScaler(), PCA(n_components=2), km()),
}
scores = {}
for name, pipe in pipelines.items():
scores[name] = adjusted_rand_score(y, pipe.fit_predict(X))
print(f"{name:>16}: ARI = {scores[name]:.3f}")
assert scores["scaled"] > 2 * scores["raw"]
Output
raw: ARI = 0.371
scaled: ARI = 0.897
scaled + PCA(2): ARI = 0.895

How it works:

  1. On raw features, proline (values up to about 1,700) dominates every distance, so the clusters follow one column.
  2. Scaling lets all 13 measurements count, and the ARI jumps.
  3. PCA to 2 components keeps the main structure of the scaled data, so its ARI stays close to the full scaled version, with 2 columns instead of 13.

Alternative: pass n_components=0.9 to keep 90% of the variance instead of a fixed number of components.

M39-C13 · Compare map settings with trustworthiness

Section titled “M39-C13 · Compare map settings with trustworthiness”
Core

Take the first 500 images of load_digits. Build 2-D maps with t-SNE at perplexity 5 and 50 and with UMAP at n_neighbors 5 and 50 (always random_state=42; UMAP also n_jobs=1). Print the trustworthiness of each map with n_neighbors=5 and n_neighbors=50.

Expected output
t-SNE perplexity 5: local 0.994, wide 0.928
t-SNE perplexity 50: local 0.994, wide 0.949
UMAP n_neighbors 5: local 0.992, wide 0.887
UMAP n_neighbors 50: local 0.985, wide 0.949
Starter
import umap
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness
from threadpoolctl import threadpool_limits
X, _ = load_digits(return_X_y=True)
X = X[:500]
maps = {}
# TODO: fill maps with four embeddings, then print both trustworthiness scores
Hint 1

TSNE(perplexity=5, random_state=42).fit_transform(X) (inside with threadpool_limits(limits=1):, so that the numbers do not depend on your CPU’s thread count) and umap.UMAP(n_neighbors=5, random_state=42, n_jobs=1).fit_transform(X).

Hint 2

trustworthiness(X, emb, n_neighbors=5) checks the 5 nearest neighbors on the map; 50 checks a wider neighborhood.

Solution
import umap
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness
from threadpoolctl import threadpool_limits
X, _ = load_digits(return_X_y=True)
X = X[:500]
maps = {}
for p in (5, 50):
tsne = TSNE(perplexity=p, random_state=42)
with threadpool_limits(limits=1): # one thread: machine-independent numbers
maps[f"t-SNE perplexity {p}"] = tsne.fit_transform(X)
for n in (5, 50):
reducer = umap.UMAP(n_neighbors=n, random_state=42, n_jobs=1)
maps[f"UMAP n_neighbors {n}"] = reducer.fit_transform(X)
for name, emb in maps.items():
t5 = trustworthiness(X, emb, n_neighbors=5)
t50 = trustworthiness(X, emb, n_neighbors=50)
print(f"{name:>21}: local {t5:.3f}, wide {t50:.3f}")
assert all(emb.shape == (500, 2) for emb in maps.values())
Output
t-SNE perplexity 5: local 0.994, wide 0.928
t-SNE perplexity 50: local 0.994, wide 0.949
UMAP n_neighbors 5: local 0.992, wide 0.887
UMAP n_neighbors 50: local 0.985, wide 0.949

How it works:

  1. Small perplexity or n_neighbors makes the method care about the very nearest neighbors; large values make it care about wider neighborhoods.
  2. Trustworthiness with 5 neighbors measures fine local detail; with 50 it measures how well whole groups stay together.
  3. All four maps keep the 5 nearest neighbors well (0.985 to 0.994). The wide score shows the trade-off: the large settings (perplexity 50, 50 neighbors) keep whole groups together best (0.949 each); UMAP with 50 neighbors gives up a little local detail for it (0.985). The small settings keep local detail but break wider groups (0.928 and 0.887). Run two settings before you trust a pattern on a map.

M39-C14 · Score next week’s readings with LOF

Section titled “M39-C14 · Score next week’s readings with LOF”
Core

Novelty detection: train LocalOutlierFactor(n_neighbors=20, novelty=True) on the scaled readings of sensor S2 from May 1 to May 7 (temperature, humidity, vibration; drop blanks). Then score the readings from May 8 to May 14 with the same scaler. Print the number of new readings, the number flagged and the 3 lowest-scoring new readings.

Expected output
new readings: 1002 flagged: 42
timestamp temperature_c humidity_pct vibration_mm_s
2024-05-10 19:00:00 25.74 52.7 12.78
2024-05-09 20:00:00 39.09 54.1 2.53
2024-05-12 03:30:00 21.43 59.4 10.59
Starter
from sklearn.neighbors import LocalOutlierFactor
cols = ["temperature_c", "humidity_pct", "vibration_mm_s"]
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
s2 = sensors[sensors["sensor_id"] == "S2"].dropna(subset=cols)
train = s2[s2["timestamp"] < "2024-05-08"]
new = s2[s2["timestamp"] >= "2024-05-08"].copy()
# TODO: fit a scaler and LOF(novelty=True) on train; predict and score new
Hint 1

Fit the scaler on train[cols] only, then transform both parts.

Hint 2

lof.predict(X_new) gives -1 for novelties and lof.score_samples(X_new) gives scores, lower for more unusual rows.

Solution
from sklearn.neighbors import LocalOutlierFactor
cols = ["temperature_c", "humidity_pct", "vibration_mm_s"]
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
s2 = sensors[sensors["sensor_id"] == "S2"].dropna(subset=cols)
train = s2[s2["timestamp"] < "2024-05-08"]
new = s2[s2["timestamp"] >= "2024-05-08"].copy()
scaler = StandardScaler().fit(train[cols])
lof = LocalOutlierFactor(n_neighbors=20, novelty=True)
lof.fit(scaler.transform(train[cols]))
X_new = scaler.transform(new[cols])
new["flag"] = lof.predict(X_new) == -1
new["score"] = lof.score_samples(X_new)
print("new readings:", len(new), "flagged:", int(new["flag"].sum()))
print(new.nsmallest(3, "score")[["timestamp"] + cols].to_string(index=False))
assert new["flag"].sum() < len(new) * 0.1
Output
new readings: 1002 flagged: 42
timestamp temperature_c humidity_pct vibration_mm_s
2024-05-10 19:00:00 25.74 52.7 12.78
2024-05-09 20:00:00 39.09 54.1 2.53
2024-05-12 03:30:00 21.43 59.4 10.59

How it works:

  1. The scaler and the LOF learn “normal” from the first week only. The second week plays tomorrow’s data.
  2. novelty=True enables predict and score_samples on new rows. Without it, LOF only has fit_predict on its training data.
  3. The lowest scores are the temperature and vibration spikes of the second week. The default threshold (contamination="auto") flags rows whose local density is clearly below their neighbors’.
  4. 42 flags are 4.2% of the new readings, about four times the expected spike rate of 1%. The ranking is good, but the default threshold is too loose. Set contamination=0.01 and count how many flags are real spikes, with the spike rule from the lesson:
local = new[cols].rolling(13, center=True, min_periods=1).median()
new["rule_spike"] = (new["temperature_c"] - local["temperature_c"] > 6) | (
new["vibration_mm_s"] / local["vibration_mm_s"] > 2.2
)
for rate in ("auto", 0.01):
model = LocalOutlierFactor(n_neighbors=20, novelty=True, contamination=rate)
flags = model.fit(scaler.transform(train[cols])).predict(X_new) == -1
hits = int((flags & new["rule_spike"]).sum())
print(f"contamination={rate}: {int(flags.sum())} flags, {hits} rule spikes")
print("rule spikes in week 2:", int(new["rule_spike"].sum()))
Output
contamination=auto: 42 flags, 10 rule spikes
contamination=0.01: 8 flags, 8 rule spikes
rule spikes in week 2: 10

With "auto", all 10 rule spikes are among the 42 flags, so about 32 flags are false alarms. With contamination=0.01, the model flags 8 rows, and all 8 are rule spikes; it misses 2. A tight threshold saves the technicians’ time, a loose one misses fewer faults: choose it with the people who check the flags.

Alternative: IsolationForest(random_state=42).fit(train[cols]) followed by predict(new[cols]) does the same job without scaling.

M39-C15 · Choose the clusterer for stretched clusters

Section titled “M39-C15 · Choose the clusterer for stretched clusters”
Core

Choose a method and justify it: on the stretched blobs from M39-C09 (scaled), compare k-means (4 clusters), a full-covariance Gaussian mixture (4 components) and DBSCAN (eps=0.3, min_samples=10). Print each method’s ARI against the true blobs and pick one.

Expected output
k-means: ARI = 0.668
GMM full: ARI = 0.762
DBSCAN: ARI = 0.332
Starter
from sklearn.datasets import make_blobs
from sklearn.mixture import GaussianMixture
X, y = make_blobs(n_samples=400, centers=4, random_state=170)
X = StandardScaler().fit_transform(X @ np.array([[0.6, -0.6], [-0.4, 0.8]]))
# TODO: three labelings, then print the ARI of each
Hint 1

All three have fit_predict(X).

Hint 2

Look at the shape of the clusters: tilted ellipses. Which model can describe a tilted ellipse?

Solution
from sklearn.datasets import make_blobs
from sklearn.mixture import GaussianMixture
X, y = make_blobs(n_samples=400, centers=4, random_state=170)
X = StandardScaler().fit_transform(X @ np.array([[0.6, -0.6], [-0.4, 0.8]]))
models = {
"k-means": KMeans(n_clusters=4, n_init=10, random_state=42),
"GMM full": GaussianMixture(
n_components=4, covariance_type="full", random_state=42
),
"DBSCAN": DBSCAN(eps=0.3, min_samples=10),
}
scores = {name: adjusted_rand_score(y, m.fit_predict(X)) for name, m in models.items()}
for name, score in scores.items():
print(f"{name:>8}: ARI = {score:.3f}")
assert max(scores, key=scores.get) == "GMM full"
Output
k-means: ARI = 0.668
GMM full: ARI = 0.762
DBSCAN: ARI = 0.332

How it works:

  1. k-means assumes round clusters of similar spread, so it cuts the tilted ellipses at the wrong places.
  2. A full covariance matrix lets each Gaussian component take the tilt and stretch of its cluster.
  3. DBSCAN depends on density; where two stretched clusters come close, one eps either merges them or leaves many points as noise.
  4. Choice: the Gaussian mixture. The clusters are elliptical and there is little noise, which is exactly what a GMM models.

M39-X01 · A segmentation pipeline with PCA

Section titled “M39-X01 · A segmentation pipeline with PCA”
Challenge

Build one pipeline: StandardScaler → PCA(n_components=0.8, random_state=42) → KMeans(n_clusters=5, n_init=10, random_state=42) on the customer FEATURES. Report how many components PCA kept, the ARI between its labels and the labels of the lesson’s Example 1 model (the same steps without PCA), and the churn rate per cluster, sorted.

Expected output
components kept: 4
ARI with the no-PCA model: 0.983
churn per cluster: [0.045, 0.126, 0.147, 0.311, 0.318]
Starter
customers = pd.read_csv("data/customers.csv")
# TODO: the Example 1 model: scaler + KMeans(5)
# TODO: the PCA pipeline; read pipe.named_steps["pca"].n_components_
# TODO: ARI between the two labelings, churn rate per PCA cluster
Hint 1

make_pipeline names its steps after the lowercase class names: "standardscaler", "pca", "kmeans".

Hint 2

customers.groupby(labels)["churned"].mean().sort_values() gives the sorted churn rates.

Solution
customers = pd.read_csv("data/customers.csv")
X = customers[FEATURES]
def km5():
return KMeans(n_clusters=5, n_init=10, random_state=42)
base_labels = make_pipeline(StandardScaler(), km5()).fit_predict(X)
pca = PCA(n_components=0.8, random_state=42)
pca_pipe = make_pipeline(StandardScaler(), pca, km5())
pca_labels = pca_pipe.fit_predict(X)
kept = pca_pipe.named_steps["pca"].n_components_
churn = customers.groupby(pca_labels)["churned"].mean().sort_values()
print("components kept:", kept)
agreement = adjusted_rand_score(base_labels, pca_labels)
print("ARI with the no-PCA model:", round(agreement, 3))
print("churn per cluster:", churn.round(3).tolist())
assert kept < len(FEATURES)
Output
components kept: 4
ARI with the no-PCA model: 0.983
churn per cluster: [0.045, 0.126, 0.147, 0.311, 0.318]

How it works:

  1. A float n_components=0.8 keeps the smallest number of components that explains at least 80% of the variance. The five customer features are weakly correlated, so PCA keeps 4 of the 5 (86% of the variance; 3 components give only 71%). With 0.9 it would keep all 5, and PCA would only rotate the data.
  2. The ARI compares the two segmentations without caring about label names. A high value means that dropping the last component barely changes the segments.
  3. The churn rates per cluster have the same spread as in the lesson (from about 4% to about 32%), so the business story survives the compression.

Alternative: compare the profile tables of both models side by side instead of one number. ARI says how much they agree; the profiles say where they differ.

Challenge

A good k gives segments that survive small changes in the data. For k from 3 to 6: fit k-means on all scaled customers, then 5 times on a bootstrap sample (5,000 rows drawn with replacement, rng = np.random.default_rng(42) created once before the loop). Use each bootstrap model to predict all customers and compute the ARI with the full-data labels. Print the mean ARI per k and the most stable k. Use n_init=5, random_state=42 everywhere.

Expected output
k = 3: mean ARI 0.724, worst 0.539
k = 4: mean ARI 0.764, worst 0.675
k = 5: mean ARI 0.968, worst 0.960
k = 6: mean ARI 0.946, worst 0.917
most stable k: 5
Starter
customers = pd.read_csv("data/customers.csv")
X = StandardScaler().fit_transform(customers[FEATURES])
rng = np.random.default_rng(42)
stability = {}
for k in range(3, 7):
# TODO: full-data labels, 5 bootstrap fits, ARI of each with the full labels
...
# TODO: print the mean ARI per k and the most stable k
Hint 1

idx = rng.choice(len(X), size=len(X), replace=True) draws one bootstrap sample; fit on X[idx].

Hint 2

Predict on the full X, not on X[idx], so both labelings cover the same 5,000 customers.

Solution
customers = pd.read_csv("data/customers.csv")
X = StandardScaler().fit_transform(customers[FEATURES])
rng = np.random.default_rng(42)
stability = {}
for k in range(3, 7):
full = KMeans(n_clusters=k, n_init=5, random_state=42).fit_predict(X)
aris = []
for _ in range(5):
idx = rng.choice(len(X), size=len(X), replace=True)
boot = KMeans(n_clusters=k, n_init=5, random_state=42).fit(X[idx])
aris.append(adjusted_rand_score(full, boot.predict(X)))
stability[k] = float(np.mean(aris))
print(f"k = {k}: mean ARI {stability[k]:.3f}, worst {min(aris):.3f}")
best = max(stability, key=stability.get)
print("most stable k:", best)
assert best == 5
Output
k = 3: mean ARI 0.724, worst 0.539
k = 4: mean ARI 0.764, worst 0.675
k = 5: mean ARI 0.968, worst 0.960
k = 6: mean ARI 0.946, worst 0.917
most stable k: 5

How it works:

  1. A bootstrap sample (module 9) draws rows with replacement, so each sample is a slightly different version of the customer base.
  2. If k matches real structure, every sample finds nearly the same segments, and the ARI with the full-data labels stays high. If k is arbitrary, the borders move from sample to sample.
  3. k = 5 is the most stable, and its worst run is still high. k = 3 and k = 4 swing between runs: the data has no natural 3- or 4-way split. This supports the choice of k = 5 in the lesson, which the silhouette alone could not settle.

Alternative: use subsamples without replacement (for example 80% of the rows) instead of the bootstrap. The idea is the same: stable clusters reappear.

M39-X03 · Give the anomaly detector context

Section titled “M39-X03 · Give the anomaly detector context”
Challenge

In the lesson, Isolation Forest on sensor S1 missed a 34.7 °C reading at 16:30, because 34.7 °C looks less strange in the warm afternoon. Replace temperature_c with temp_dev: the temperature minus the median temperature of the same hour of day for S1. Fit IsolationForest(n_estimators=200, contamination=0.01, random_state=42) on temp_dev, humidity_pct and vibration_mm_s. Print the number of flags, how many match the lesson’s spike rule, and whether the 16:30 reading on May 6 is flagged.

Expected output
flags: 20 matching the rule: 14
16:30 reading on May 6 flagged: True
Starter
from sklearn.ensemble import IsolationForest
cols = ["temperature_c", "humidity_pct", "vibration_mm_s"]
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
s1 = sensors[sensors["sensor_id"] == "S1"].dropna(subset=cols).reset_index(drop=True)
med = s1[cols].rolling(13, center=True, min_periods=1).median()
spike = ((s1["temperature_c"] - med["temperature_c"]) > 6) | (
s1["vibration_mm_s"] / med["vibration_mm_s"] > 2.2
)
# TODO: hour of day, temp_dev = temperature - median temperature of that hour
# TODO: fit IsolationForest on temp_dev, humidity_pct, vibration_mm_s
# TODO: flags, matches with spike, and the 2024-05-06 16:30 reading
Hint 1

s1.groupby(s1["timestamp"].dt.hour)["temperature_c"].transform("median") returns, for each row, the median of its hour.

Hint 2

Select the reading with s1["timestamp"] == "2024-05-06 16:30" and read its flag.

Solution
from sklearn.ensemble import IsolationForest
cols = ["temperature_c", "humidity_pct", "vibration_mm_s"]
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
s1 = sensors[sensors["sensor_id"] == "S1"].dropna(subset=cols).reset_index(drop=True)
med = s1[cols].rolling(13, center=True, min_periods=1).median()
spike = ((s1["temperature_c"] - med["temperature_c"]) > 6) | (
s1["vibration_mm_s"] / med["vibration_mm_s"] > 2.2
)
hour = s1["timestamp"].dt.hour
usual = s1.groupby(hour)["temperature_c"].transform("median")
s1["temp_dev"] = s1["temperature_c"] - usual
context_cols = ["temp_dev", "humidity_pct", "vibration_mm_s"]
iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=42)
flags = iso.fit_predict(s1[context_cols]) == -1
target = (s1["timestamp"] == "2024-05-06 16:30").to_numpy()
print("flags:", int(flags.sum()), "matching the rule:", int((flags & spike).sum()))
print("16:30 reading on May 6 flagged:", bool(flags[target][0]))
assert flags[target][0]
Output
flags: 20 matching the rule: 14
16:30 reading on May 6 flagged: True

How it works:

  1. groupby(hour).transform("median") gives each reading the typical temperature of its hour of day, so temp_dev measures “warmer or colder than usual for this time”.
  2. The daily cycle no longer hides anything: 34.7 °C at 16:30 is about 10 °C above the usual afternoon value, and the model flags it.
  3. All 14 rule spikes are now among the 20 flags, against 13 with the raw temperature. The cold night readings do not drop out: 5 of the 6 other flags are still cold, humid S1 nights. Humidity moves against temperature, so the raw humidity_pct column still carries the daily cycle. The next step is a hum_dev feature built the same way as temp_dev.

Alternative: add sin and cos of the hour as two extra features (cyclic encoding, module 33). A tree model then has to learn the cycle itself, which works less well with few anomalies; the deviation feature gives it the context directly.

M39-X04 · Reduce an image to eight colors

Section titled “M39-X04 · Reduce an image to eight colors”
Challenge

Outside data science, k-means compresses images: each pixel gets the color of its cluster centroid (color quantization). Load the sample photo load_sample_image("china.jpg") (427 × 640 pixels, RGB). Fit KMeans(n_clusters=8, n_init=4, random_state=42) on a random sample of 2,000 pixels (rng = np.random.default_rng(42)), assign all pixels, and print the number of distinct colors before and after and the mean absolute error per channel.

Expected output
pixels: 273280
distinct colors before: 96615
distinct colors after: 8
mean absolute error: 11.3 of 255 per channel
Starter
from sklearn.datasets import load_sample_image
image = load_sample_image("china.jpg")
pixels = image.reshape(-1, 3).astype(float) / 255 # one row per pixel, values 0-1
rng = np.random.default_rng(42)
# TODO: sample 2,000 rows, fit KMeans(8), predict all pixels
# TODO: rebuild the pixels from the centroids; count distinct colors; compute MAE
Hint 1

sample = pixels[rng.choice(len(pixels), size=2_000, replace=False)].

Hint 2

model.cluster_centers_[labels] turns a label array into a color array. Count colors with len(np.unique(colors, axis=0)).

Solution
from sklearn.datasets import load_sample_image
image = load_sample_image("china.jpg")
pixels = image.reshape(-1, 3).astype(float) / 255 # one row per pixel, values 0-1
rng = np.random.default_rng(42)
sample = pixels[rng.choice(len(pixels), size=2_000, replace=False)]
model = KMeans(n_clusters=8, n_init=4, random_state=42).fit(sample)
labels = model.predict(pixels)
quantized = model.cluster_centers_[labels]
mae = np.abs(pixels - quantized).mean() * 255
print("pixels:", len(pixels))
print("distinct colors before:", len(np.unique(image.reshape(-1, 3), axis=0)))
print("distinct colors after:", len(np.unique(quantized, axis=0)))
print(f"mean absolute error: {mae:.1f} of 255 per channel")
assert len(np.unique(quantized, axis=0)) == 8
Output
pixels: 273280
distinct colors before: 96615
distinct colors after: 8
mean absolute error: 11.3 of 255 per channel

How it works:

  1. Each pixel is a row with three features (red, green, blue). Dividing by 255 puts them in 0–1.
  2. Fitting on 2,000 sampled pixels is much faster than on 273,280, and the centroids barely change. predict then assigns every pixel.
  3. Indexing the centroid array with the labels gives every pixel its centroid’s color: the image now uses 8 colors, with a small average error per channel. The same trick builds color palettes and compresses images for the web.

Alternative: sklearn.cluster.MiniBatchKMeans fits on all pixels in small batches, which scales to large images without sampling.

M39-X05 · Assign new customers to existing segments

Section titled “M39-X05 · Assign new customers to existing segments”
Challenge

Fit a scaler + KMeans(n_clusters=5, n_init=10, random_state=42) pipeline on the customers who signed up before 2024. Use it to assign the customers who signed up in 2024. Print a table with the share of each cluster among old and new customers and the mean tenure per cluster, then explain the biggest shift.

Expected output
3160 old and 1840 new customers
old_share new_share tenure
0 0.324 0.378 24.804
1 0.176 0.177 27.396
2 0.196 0.326 27.434
3 0.170 0.000 63.246
4 0.134 0.119 32.474
Starter
customers = pd.read_csv("data/customers.csv")
old = customers[customers["signup_date"] < "2024-01-01"]
new = customers[customers["signup_date"] >= "2024-01-01"]
# TODO: fit the pipeline on old[FEATURES]; predict old and new
# TODO: share table (old vs new)
# TODO: add the mean tenure of each cluster among old customers
Hint 1

pd.Series(labels).value_counts(normalize=True) gives the shares.

Hint 2

Build a DataFrame with one column per group; fillna(0) covers a cluster that no new customer joins.

Solution
customers = pd.read_csv("data/customers.csv")
old = customers[customers["signup_date"] < "2024-01-01"]
new = customers[customers["signup_date"] >= "2024-01-01"]
pipe = make_pipeline(StandardScaler(), KMeans(n_clusters=5, n_init=10, random_state=42))
old_labels = pipe.fit_predict(old[FEATURES])
new_labels = pipe.predict(new[FEATURES])
table = pd.DataFrame(
{
"old_share": pd.Series(old_labels).value_counts(normalize=True),
"new_share": pd.Series(new_labels).value_counts(normalize=True),
"tenure": old.groupby(old_labels)["tenure_months"].mean(),
}
).fillna(0).sort_index()
print(len(old), "old and", len(new), "new customers")
print(table.round(3))
assert np.isclose(table["new_share"].sum(), 1)
Output
3160 old and 1840 new customers
old_share new_share tenure
0 0.324 0.378 24.804
1 0.176 0.177 27.396
2 0.196 0.326 27.434
3 0.170 0.000 63.246
4 0.134 0.119 32.474

How it works:

  1. The pipeline learns the scaling and the centroids from the old customers only. predict reuses both for the new customers, so the segments keep their meaning.
  2. The share table compares the segment mix of the two groups.
  3. The biggest shift: the long-tenure cluster (mean tenure far above the rest) gets no new customers at all, because a 2024 signup has at most 12 months of tenure. Clusters built on tenure describe the past of a customer, not only their behavior. For a campaign aimed at new customers, cluster without tenure, or segment each signup cohort separately.

Alternative: monitor the shares month by month. A segment that grows or shrinks fast is a signal of data drift, a change in the input data that module 44 treats in production.