K-Means vs DBSCAN on Non-Convex Data
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `make_datasets` to build two-moons and concentric-circles datasets, and `compare_kmeans_dbscan` to cluster each with `KMeans` and `DBSCAN`. Return the adjusted Rand index (ARI) of each method against the true labels.
The functions follow these rules:
- `make_datasets` returns `{'moons': (X, y), 'circles': (X, y)}` from `make_moons` and `make_circles` (`factor=0.5`), passing `n_samples`, `noise` and `random_state` through.
- Run `KMeans(n_clusters=2, n_init=10, random_state=random_state)` on each dataset.
- Run `DBSCAN(eps=eps, min_samples=min_samples)`. The noise label `-1` is scored as-is (all-noise output gives ARI `0.0`).
- Score with `adjusted_rand_score(y_true, labels)` and return Python `float`s.
- Output shape: `{'moons': {'kmeans': ..., 'dbscan': ...}, 'circles': {...}}`.
Example:
```python
res = compare_kmeans_dbscan() # defaults: n=300, noise=0.05, seed=0, eps=0.2, min_samples=5
res["moons"]["dbscan"] > 0.95 # True
res["circles"]["dbscan"] > 0.95 # True
res["circles"]["kmeans"] < 0.1 # True: k-means splits the rings in half
```
```hint Shape of a cluster
Think about the region each k-means cluster can occupy given two centroids, and compare that with what DBSCAN uses to decide that two points belong together.
```
### Constraints & Assumptions
- Defaults: `n_samples=300`, `noise=0.05`, `random_state=0`, `eps=0.2`, `min_samples=5`.
- `scikit-learn` is available. Plotting is out of scope.
### What a Strong Answer Covers
- Seeded dataset generation that passes `n_samples`, `noise` and `random_state` through, with `factor=0.5` for the circles.
- Both clusterers configured as specified, with DBSCAN's noise label scored without remapping.
- ARI as the score, and why it needs no matching of cluster ids.
- Why k-means fails on both shapes and why DBSCAN recovers them at these settings.
- How the DBSCAN result depends on `eps`, `min_samples` and the scale of the features.
### Follow-up Questions
- How would you choose `eps` and `min_samples` on a new dataset without labels?
- What happens to the DBSCAN scores as `noise` grows, or when two clusters have very different densities?
- Which other method could recover the two rings, and what would it need?
Overview: Build seeded two-moons and concentric-circles datasets, cluster each with k-means and DBSCAN in scikit-learn, and score both against the true labels with the adjusted Rand index. It tests why centroid-based clusters fail on non-convex shapes, how the DBSCAN density parameters work, and how noise labels affect the score.