Platt Scaling for SVM Probabilities
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Given SVM decision values `f` and labels `y` in {-1, +1}, implement Platt scaling: `P(y=+1 | f) = 1 / (1 + exp(A·f + B))`. Fit `A` and `B` by minimizing the summed cross-entropy against Platt's adjusted targets: `(N+ + 1)/(N+ + 2)` for positives and `1/(N- + 2)` for negatives.
- `platt_targets(y)`: float array of adjusted targets, one per sample.
- `platt_probability(decision_values, A, B)`: float array of probabilities, finite for extreme scores (for example ±800).
- `platt_nll(decision_values, y, A, B)`: scalar `-Σ[t·log p + (1-t)·log(1-p)]` using the adjusted targets.
- `fit_platt(decision_values, y, max_iter=100, tol=1e-10)`: returns `(A, B)` as floats at the optimum (gradient magnitude < 1e-6). Must not mutate inputs.
For example:
```python
platt_targets([1, -1, -1, 1, -1, -1, -1])
# -> [0.75, 1/7, 1/7, 0.75, 1/7, 1/7, 1/7]
platt_probability([-800.0, 800.0], A=-1.0, B=0.0)
# -> [0.0, 1.0] (no overflow / NaN)
```
```hint Stable sigmoid
`exp(z)` overflows when `z` is large and positive. Find a form of the same probability that only ever exponentiates a non-positive number.
```
```hint Derivatives
Differentiate the per-sample loss with respect to `z = A·f + B` first. The chain rule then gives the gradient and the 2×2 Hessian in `A` and `B` with little extra work.
```
```hint Step control
A full Newton step can raise the loss when you start far from the optimum. Plan for a safeguard and a stopping rule.
```
### Constraints & Assumptions
- `len(decision_values) == len(y)`, both classes present, decision values finite.
- Labels outside {-1, +1} raise `ValueError`.
- Fitted parameters must stay finite even when the scores perfectly separate the classes.
### What a Strong Answer Covers
- Adjusted targets computed from the class counts, with label validation.
- A probability function and a loss that stay finite and NaN-free at extreme scores.
- The correct gradient and Hessian in `A` and `B`, and a Newton update with a safeguard such as a backtracking line search.
- A sensible starting point, a stopping rule, and why the optimum stays finite on perfectly separated scores.
- The cost per iteration and the memory used.
### Follow-up Questions
- Why fit Platt scaling on held-out decision values instead of the training scores?
- Why use the adjusted targets instead of hard 0/1 labels?
- How would you extend this to multiclass SVMs?
Overview: Implement Platt scaling to turn SVM decision values into probabilities, fitting the two sigmoid parameters by Newton's method on smoothed cross-entropy targets. It tests numerically stable sigmoid and log-loss code, gradient and Hessian derivation, and behavior on perfectly separated scores.