Flatten, Then Find Density

Machine Learning in CodeHard+10 XP+10

Flatten, Then Find Density

DBSCAN struggles in 13 dimensions, where everything is far from everything. Squash the wine data with PCA first and try again.

Task: write density_groups(n_components, eps, min_samples).

  • Load load_wine(return_X_y=True, as_frame=True) and scale the 13 columns with StandardScaler().fit_transform(X).
  • Reduce them with PCA(n_components=n_components).fit_transform(...).
  • Fit DBSCAN(eps=eps, min_samples=min_samples) on the reduced data.
  • Return a dict:
    • "sizes": the number of wines in each cluster, sorted from largest to smallest, with noise left out
    • "noise": how many wines were labelled -1
    • "match": adjusted_rand_score(y, labels) with the labels exactly as DBSCAN gave them, as a plain float rounded to 3 decimal places

If every wine is noise, "sizes" is an empty list.

Examples

n_components = 2
eps = 0.7
min_samples = 5
returns {'sizes': [126, 46], 'noise': 6, 'match': 0.437}
n_components = 2
eps = 0.5
min_samples = 5
returns {'sizes': [68, 28, 22, 15, 14], 'noise': 31, 'match': 0.379}

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run