Let the Silhouette Choose

Machine Learning in CodeMedium+10 XP+10

Let the Silhouette Choose

A park ranger logged where visitors set up picnics, as [x, y] points in metres from the gate. She doesn't know how many popular spots there are. Inertia always falls as k grows, so she uses the silhouette score instead.

Task: write best_k(points, ks).

  • For each k in ks, in the given order, fit KMeans(n_clusters=k, random_state=0, n_init=10) on the points as given. Don't scale them.
  • Score each clustering with silhouette_score(points, labels).
  • Return a dict:
    • "scores": the silhouette scores in the same order as ks, each rounded to 3 decimal places
    • "best_k": the k with the highest score

Every k in ks is at least 2. No two scores tie.

Examples

points = [[3.4, 5.8], [3.82, 6.13], [7.3, -0.36], [1.97, 5.77], [2.53, 4.56], [1.62, 0.11], [5.36, 0.28], [6.03, -0.48], [6.17, 0.17], [2.99, 5.79], [-0.44, 0.38], [0.48, -0.81], [2.96, 5.03], [0.07, 0.37], [-0.43, -0.05], [-0.12, -0.32], [4.75, -0.42], [6.37, 0.22]]
ks = [2, 3, 4, 5]
returns {'scores': [0.55, 0.796, 0.645, 0.536], 'best_k': 3}
points = [[-0.95, 0.34], [-0.29, -0.35], [-1.3, -1.27], [8.94, 11.73], [10.92, 10.88], [12.5, 11.09], [-1.26, -0.49], [-0.02, 0.94], [-1.31, 0.32], [12.91, 12.9], [11.5, 11.92], [12.26, 10.51], [-0.68, -0.27], [14.34, 13.77], [10.36, 11.98], [1.3, 0.3]]
ks = [2, 3, 4]
returns {'scores': [0.885, 0.679, 0.647], 'best_k': 2}

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