Skip to article frontmatterSkip to article content

Learning purpose: Compare fixed-k partitioning and density-based grouping on generated coordinates. Study parameter effects and the meaning of noise points.

Format: guided learner notebook. Part 1 supplies the conceptual background; try the exercises before consulting the linked solution.

Data: entirely synthetic, generated with a fixed seed. Software: NumPy, Matplotlib and relevant SciPy/scikit-learn functions. No private course datasets or Google Drive required.

After you attempt the exercises: Open the complete solution notebook on GitHub.

1. Generate and inspect the observations

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans, DBSCAN
rng = np.random.default_rng(123)
points = np.vstack([rng.normal((0, 0), .35, (90, 2)),
                    rng.normal((3, 0), .4, (110, 2)),
                    rng.normal((1.4, 2.9), .4, (90, 2)),
                    rng.uniform((-1.5, -1.5), (4.5, 4), size=(25, 2))])
fig, ax = plt.subplots()
ax.scatter(points[:, 0], points[:, 1], s=10)
ax.set(title="Synthetic spatial observations", xlabel="x", ylabel="y")
plt.show()

2. Analyse and evaluate

The generating locations are known to us, but are not provided to the models. Cluster labels are arbitrary identifiers; they do not name geographical categories.

TODO 1 — K-means. Partition points with n_clusters=3. Plot labelled groups and note how outliers are handled.

# TODO: fit KMeans(n_clusters=3, random_state=0, n_init=10).

TODO 2 — DBSCAN. Fit DBSCAN(eps=0.3, min_samples=6). Count the distinct non-noise clusters and noise observations. Try a larger eps and explain changes.

# TODO: fit DBSCAN and report number of clusters and noise points.

3. Interpretation

K-means assigns every observation to one of k groups, while DBSCAN may label sparse observations as noise. Spatial clusters depend on the coordinates, distance metric, scaling and parameters; neither algorithm explains why the pattern exists.

Write your own interpretation: How might parameter selection or observation design change the result?

Check your understanding

Try the exercises and write down your interpretation before comparing your work with the complete answers.

Open the worked solution