Early Stopping With Precision at K
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement three functions. `sigmoid(margins)` maps raw margins to probabilities elementwise for any input shape. `precision_at_k(y_true, proba, k)` returns the fraction of positives (label `1`) among the `k` highest-probability samples. `early_stop(staged_margins, y_val, k, patience, min_delta=0.0)` scores each stage (row) of `staged_margins` and returns `(best_iteration, best_score, scores)`.
The functions must follow these rules:
- `sigmoid` must not overflow or warn for margins like `±1000`.
- Ties in `proba` go to the lower sample index. A non-integer `k`, a `k` outside `[1, n]`, or a length mismatch raises `ValueError`.
- Stage 0 sets the initial best. Stage `i` improves only if `score > best + min_delta`, which resets the wait counter. Otherwise the wait counter increments.
- Stop once the wait counter reaches `patience`. `scores` includes every evaluated stage, including the stopping one.
- Return `(int, float, np.ndarray)` with a 0-based `best_iteration`. A `staged_margins` that is not 2-D, zero stages, or `patience < 1` raises `ValueError`.
Example:
```python
y_val = [1, 0, 1, 0]
HALF = [2.0, 1.0, -1.0, -2.0] # p@2 = 0.5
ONE = [2.0, -1.0, 1.0, -2.0] # p@2 = 1.0
early_stop([HALF, ONE, HALF, ONE, HALF, HALF], y_val, k=2, patience=2)
# -> (1, 1.0, array([0.5, 1.0, 0.5, 1.0]))
# stage 3 equals best, so it is not an improvement: wait hits 2 and the run stops
```
```hint Overflow
The logistic function can be written in two algebraically equal forms. Check which one keeps the argument of `exp` non-positive for a given sign of the margin.
```
```hint Tie order
A default descending sort makes no promise about the order of equal probabilities. Look for a sort whose output keeps equal keys in their original index order.
```
### Constraints & Assumptions
- `staged_margins` has shape `(n_stages, n_samples)`, and each row must have the same length as `y_val`.
- Label `1` marks a positive. Any other label counts as a miss in the top `k`.
- `min_delta` defaults to `0.0`, so by default any strict increase counts as an improvement.
### What a Strong Answer Covers
- A sigmoid that keeps the input shape and produces no overflow or warning at extreme margins.
- Top-k selection with a deterministic lower-index tie rule, plus the validation of `k` and of the input lengths.
- The patience bookkeeping: how stage 0 is handled, what counts as an improvement, when the run stops, and which stages appear in `scores`.
- Exact return types and the `ValueError` cases for `early_stop`.
- The cost per evaluated stage, and why the earliest of several equal best stages is reported.
### Follow-up Questions
- How would you support metrics where lower is better, such as log loss?
- How would you plug this metric into XGBoost or LightGBM training directly?
- Can you make top-k selection cheaper for large validation sets?
Overview: Implement a numerically stable sigmoid, a precision at k metric with a fixed tie rule, and a patience-based early-stopping loop over staged boosting margins. It tests overflow-safe math, deterministic top-k ranking and the bookkeeping that picks the best iteration.