Implement an Open-Set Classifier That Rejects Unknown Inputs with MSP or Energy Score Thresholds

Quick Overview

Implement maximum softmax probability and energy scores, then an open-set predictor that fits a rejection threshold on in-distribution validation logits and labels low-confidence rows as unknown. It tests numerically stable logsumexp, quantile thresholds with ties and float error, and careful input validation.

Implement an Open-Set Classifier That Rejects Unknown Inputs with MSP or Energy Score Thresholds

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement the functions `softmax_confidence` and `energy_score` and the class `OpenSetPredictor(score="msp", target_acceptance=0.95, temperature=1.0, unknown_label=-1)`. The predictor scores each row of logits, fits a rejection threshold from in-distribution validation logits at `target_acceptance`, and labels low-scoring rows as `unknown_label`. The code must meet these requirements: - `softmax_confidence(logits, temperature=1.0)` returns the maximum of `softmax(logits / T)` for each row. `energy_score(logits, temperature=1.0)` returns `T * logsumexp(logits / T)` for each row and must stay finite for extreme logits such as ±1000. Both treat a 1-D input as one row. - `__init__` raises `ValueError` if `score` is not `"msp"` or `"energy"`, if `target_acceptance` is not in (0, 1], or if `temperature <= 0`. - `fit(val_logits, classes=None)` scores the validation rows, sets `k = ceil(target_acceptance * n)` clamped to [1, n], and stores the k-th largest score as the float `threshold_`. `classes_` defaults to `arange(C)` for C logit columns, and a `classes` argument whose length does not match C raises `ValueError`. It returns `self`. - `predict(logits)` returns `classes_[argmax]` for each row, with ties going to the lowest index, and replaces the label with `unknown_label` when the row's score is strictly below `threshold_`. - `predict` before `fit` raises `RuntimeError`. A logit width that differs from the number of classes raises `ValueError`. Example: ```python vals = np.array([3, 7, 0, 9, 1, 5, 8, 2, 6, 4.]).reshape(-1, 1) m = OpenSetPredictor(score="energy", target_acceptance=0.8).fit(vals) m.threshold_ # 2.0 (k = 8, 8th largest) (m.predict(vals) != -1).mean() # 0.8 m = OpenSetPredictor("msp", 0.5).fit([[np.log(3), 0, 0], [0, 0, 0]], classes=[10, 20, 30]) m.threshold_ # 0.6 m.predict([[np.log(3), 0, 0], [0, 5, 0], [0, 0, 0], [0, 0, np.log(4)]]) # -> [10, 20, -1, 30] ``` ```hint Stabilize before exponentiating Both scores exponentiate logits. Think about what you can subtract from each row first without changing the result. ``` ```hint Count the accepted rows Work out how many validation rows pass when the threshold is the k-th largest score and rejection uses a strict comparison. Then check what floating-point error can do to `target_acceptance * n` before you take the ceiling. ``` ### What a Strong Answer Covers - Numerically stable MSP and energy computations with temperature, including 1-D input handling. - How the threshold follows from the validation scores and how many validation rows it accepts, including ties and floating-point error in computing k. - Prediction logic: the argmax tie rule, mapping to `classes_`, strict-inequality rejection, and the type of the returned labels. - Validation of parameters and inputs with the required error types. - Time complexity of fitting and predicting. ### Follow-up Questions - Why does temperature scaling help MSP and energy scores separate in-distribution from out-of-distribution inputs? - How would you evaluate the rejector without fixing a single threshold? - What happens if the validation scores contain many ties at the threshold, and what would you do about it?

Overview: Implement maximum softmax probability and energy scores, then an open-set predictor that fits a rejection threshold on in-distribution validation logits and labels low-confidence rows as unknown. It tests numerically stable logsumexp, quantile thresholds with ties and float error, and careful input validation.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement the functions softmax_confidence and energy_score and the class OpenSetPredictor(score="msp", target_acceptance=0.95, temperature=1.0, unknown_label=-1). The predictor scores each row of logits, fits a rejection threshold from in-distribution validation logits at target_acceptance, and labels low-scoring rows as unknown_label.

The code must meet these requirements:

  • softmax_confidence(logits, temperature=1.0) returns the maximum of softmax(logits / T) for each row. energy_score(logits, temperature=1.0) returns T * logsumexp(logits / T) for each row and must stay finite for extreme logits such as ±1000. Both treat a 1-D input as one row.
  • __init__ raises ValueError if score is not "msp" or "energy" , if target_acceptance is not in (0, 1], or if temperature <= 0 .
  • fit(val_logits, classes=None) scores the validation rows, sets k = ceil(target_acceptance * n) clamped to [1, n], and stores the k-th largest score as the float threshold_ . classes_ defaults to arange(C) for C logit columns, and a classes argument whose length does not match C raises ValueError . It returns self .
  • predict(logits) returns classes_[argmax] for each row, with ties going to the lowest index, and replaces the label with unknown_label when the row's score is strictly below threshold_ .
  • predict before fit raises RuntimeError . A logit width that differs from the number of classes raises ValueError .

Example:

vals = np.array([3, 7, 0, 9, 1, 5, 8, 2, 6, 4.]).reshape(-1, 1)
m = OpenSetPredictor(score="energy", target_acceptance=0.8).fit(vals)
m.threshold_            # 2.0  (k = 8, 8th largest)
(m.predict(vals) != -1).mean()  # 0.8

m = OpenSetPredictor("msp", 0.5).fit([[np.log(3), 0, 0], [0, 0, 0]], classes=[10, 20, 30])
m.threshold_            # 0.6
m.predict([[np.log(3), 0, 0], [0, 5, 0], [0, 0, 0], [0, 0, np.log(4)]])
# -> [10, 20, -1, 30]

What a Strong Answer Covers Guidance

  • Numerically stable MSP and energy computations with temperature, including 1-D input handling.
  • How the threshold follows from the validation scores and how many validation rows it accepts, including ties and floating-point error in computing k.
  • Prediction logic: the argmax tie rule, mapping to classes_ , strict-inequality rejection, and the type of the returned labels.
  • Validation of parameters and inputs with the required error types.
  • Time complexity of fitting and predicting.

Follow-up Questions Guidance

  • Why does temperature scaling help MSP and energy scores separate in-distribution from out-of-distribution inputs?
  • How would you evaluate the rejector without fixing a single threshold?
  • What happens if the validation scores contain many ties at the threshold, and what would you do about it?