Shoppers Who Shop Alike

Machine Learning in CodeMedium+10 XP+10

Shoppers Who Shop Alike

A small bookshop wants to group its loyalty-card customers. For each customer it has two numbers:

  • [0] money spent this year, in pounds (hundreds or thousands)
  • [1] visits per month (between 1 and about 20)

Those columns live on very different scales, so the shop scales them first.

Task: write customer_groups(customers, k).

  • Scale the columns with StandardScaler().fit_transform(...).
  • Fit KMeans(n_clusters=k, random_state=0, n_init=10) on the scaled data.
  • Collect the row indices of the customers in each cluster.
  • Sort the indices inside each group from smallest to largest.
  • Return the groups as a list of lists, ordered by each group's smallest index.

Cluster numbers are arbitrary, so only who is grouped with whom counts.

Examples

customers = [[1200, 2], [1350, 9], [1280, 3], [1400, 10], [1250, 2], [1320, 9], [3100, 3], [3300, 10], [3200, 2], [3050, 9]]
k = 4
returns [[0, 2, 4], [1, 3, 5], [6, 8], [7, 9]]
customers = [[400, 1], [420, 12], [2600, 1], [410, 11], [2650, 13], [430, 2], [2580, 12], [2620, 2]]
k = 4
returns [[0, 5], [1, 3], [2, 7], [4, 6]]

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