Classify by the nearest class centroid

Why it matters Prototype classifiers on top of frozen embeddings are a fast baseline for intent routing.

The simplest classifier: average each class, then label a new point by the closest average.

Write nearest_centroid(X_train, y_train, X_test). Compute one centroid per class (classes are the sorted unique labels), then return the label of the nearest centroid (Euclidean) for every test row. Ties go to the smaller label.

Signaturedef nearest_centroid(X_train, y_train, X_test)

Example

train points [[0], [2], [10]] with labels [0, 0, 1] give centroids 1 and 10, so test [[4], [7]] gives [0, 1].

Understand the idea

Nearest centroid is about the simplest classifier you can build. For every class you compute the average point (the centroid). A new point then gets the label of whichever centroid is closest. Think of sending each student to the nearest school building. Worked example: training points 1 and 3 have label 0, and point 8 has label 1. The class 0 centroid is (1 + 3) / 2 = 2 and the class 1 centroid is 8. Test point 6 is 4 away from 2 and 2 away from 8, so it gets label 1. Test point 5 is 3 away from both, a tie, so it takes the smaller label 0. Rule: centroid_c = mean of the training rows with label c, with classes in sorted order. Prediction = argmin over c of the Euclidean distance ||x - centroid_c||, and ties go to the earlier (smaller) label. Use a mean, not a sum, or big classes get centroids far away from their own data. Used in: prototype networks for few-shot learning, and quick baselines on embeddings where each class is summarised by its average vector.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplenearest_centroid([[0], [2], [10]], [0, 0, 1], [[4], [7]])
  • Sample 2: 2dnearest_centroid([[0, 0], [0, 1], [5, 5], [6, 5]], [3, 3, 7, 7], [[1, 1], [5, 6], [3, 3]])
  • Test 3: three classesnearest_centroid(_X, _y, _T)