K-Medoids PAM on a Precomputed Distance Matrix
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `k_medoids(D, k, init_medoids=None, max_iter=100)` for an `n × n` distance matrix `D`. Medoids must be actual data indices. Return `(medoids, labels, cost)`: `medoids` as an int array sorted ascending, `labels[i]` as the position (in the sorted `medoids`) of point `i`'s nearest medoid, and `cost` as a float sum of point-to-assigned-medoid distances.
The function must follow these rules:
- When `init_medoids is None`, run BUILD. The first medoid is the row with the smallest sum of `D`, then greedily add the non-medoid that most reduces total cost. Ties go to the lowest index.
- In SWAP, each iteration evaluates every (medoid, non-medoid) swap and applies the single best one only if it strictly lowers cost. Stop when none improves or after `max_iter` iterations (`max_iter=0` skips SWAP).
- Label ties go to the lowest medoid position (`argmin` over the sorted medoids).
- Raise `ValueError` if `D` is not square, `k` is outside `[1, n]`, or `init_medoids` is not `k` distinct indices.
Example:
```python
# D = |x_i - x_j| for x = [0, 1, 2, 10, 11, 12]
k_medoids(D, 2)
# -> medoids [1, 4], labels [0, 0, 0, 1, 1, 1], cost 4.0
# D for x = [0, 1, 2]
k_medoids(D, 2, init_medoids=[2, 0], max_iter=0)
# -> medoids [0, 2], labels [0, 0, 1], cost 1.0
```
In the second call, point 1 is at distance 1 from both medoids, so the label tie rule gives it position 0.
```hint One cost function
Every phase compares the same quantity: the sum over all points of the distance to the closest medoid in a candidate set. Write that once and build BUILD and SWAP on top of it.
```
```hint Where the tie rules live
Each tie rule in the spec maps to the order in which you scan candidates and whether your comparison is strict. Decide that before writing the loops, and remember that labels refer to the sorted medoids.
```
### Constraints & Assumptions
- `D` is symmetric, non-negative, with a zero diagonal (any metric).
- `n` is at most about 100.
- Use only NumPy.
### Clarifying Questions to Ask
- If two swaps lower the cost by exactly the same amount, which one should be applied?
- Should an index outside `[0, n)` in `init_medoids` also raise `ValueError`?
- Should a cost drop on the order of floating-point rounding count as a strict improvement?
### What a Strong Answer Covers
- A BUILD phase that starts from the smallest row sum and adds medoids greedily with lowest-index tie-breaking.
- A SWAP phase that scores every (medoid, non-medoid) pair, applies only the single best strict improvement per iteration, and honors `max_iter`, including 0.
- The output contract: sorted medoids, labels as positions in the sorted array with ties to the lower position, and a float cost.
- Validation for every listed `ValueError` case.
- The time complexity of each phase and an argument for why SWAP terminates.
### Follow-up Questions
- How would you scale PAM's SWAP phase to large `n`?
- Why choose k-medoids over k-means?
- How would you pick `k` using only `D`?
Overview: Implement the PAM k-medoids algorithm in NumPy on a precomputed distance matrix, with a greedy BUILD phase, a best-improvement SWAP phase and exact tie rules. It tests clustering fundamentals, careful input validation and reasoning about the cost of each phase.