Cost-Sensitive Binary Cross-Entropy from Logits

Quick Overview

Implement a cost-sensitive binary cross-entropy loss from logits and its gradient in NumPy, driven by a 2x2 cost matrix with sample weights and three reductions. It tests numerical stability at extreme logits, correct gradient scaling, and why only cost differences affect the optimal decision.

Cost-Sensitive Binary Cross-Entropy from Logits

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `cost_sensitive_bce(y_true, logits, cost_matrix, sample_weight=None, reduction="mean")` and its gradient with respect to the logits, `cost_sensitive_bce_grad`, which takes the same arguments. `cost_matrix[i][j]` is the cost of predicting class `j` when the true class is `i`. With `w_pos = C[1,0] - C[1,1]` and `w_neg = C[0,1] - C[0,0]`, the per-example loss for label $y$ and logit $z$ is $$ \ell(y, z) = w_{pos}\, y \log\left(1 + e^{-z}\right) + w_{neg}\,(1 - y) \log\left(1 + e^{z}\right) $$ - Let `s` be `sample_weight` (all ones if `None`). The loss for `"none"` is the array `s * per`, for `"sum"` it is the float `Σ s·per`, and for `"mean"` it is the float `Σ s·per / Σ s`. - The gradient always returns an array of shape `(n,)`: the derivative of the reduced loss for `"sum"` and `"mean"`, and the derivative of each `s·per` entry for `"none"`. - Both functions must be numerically stable: logits of ±1000 give finite, exact values. - Raise `ValueError` if `w_pos < 0` or `w_neg < 0`, the matrix is not `(2, 2)`, the lengths of the inputs differ, or `reduction` is unknown. - Inputs are flattened. With unit costs (`C = [[0, 1], [1, 0]]`) and `"mean"`, the loss equals scikit-learn's `log_loss` with the same sample weights. For example: ```python C = [[0, 2], [5, 0]]; y = [1, 0]; z = [0.0, 0.0] cost_sensitive_bce(y, z, C, reduction="none") # [3.4657, 1.3863] (5 ln2, 2 ln2) cost_sensitive_bce(y, z, C) # 2.4260 (3.5 ln2) cost_sensitive_bce_grad(y, z, C) # [-1.25, 0.5] cost_sensitive_bce_grad(y, z, C, reduction="sum") # [-2.5, 1.0] ``` ```hint Stable log terms `log(1 + e^z)` overflows if you exponentiate a logit of 1000 directly. Look for a NumPy function that computes the log of a sum of exponentials safely, and check what happens to a term that is multiplied by a zero label. ``` ```hint Gradient and reductions Differentiate one example's loss with respect to its own logit and write the result in terms of the sigmoid. Then work out how each reduction scales that per-example term, so the gradient matches the loss exactly. ``` ### Constraints & Assumptions - `y_true`, `logits` and `sample_weight` may be lists or arrays of any shape. They are flattened to length n. - Labels are binary (0 or 1). - Logits can reach ±1000 in either direction. ### What a Strong Answer Covers - Collapsing the cost matrix into `w_pos` and `w_neg`, with the shape and sign checks. - A log-space loss that stays finite and exact at logits of ±1000. - The per-logit gradient written through the sigmoid, using a sigmoid that cannot overflow. - The same reduction rule applied to the loss and the gradient, including the `Σ s` denominator for `"mean"`. - A check that the unit-cost case reduces to weighted log loss. ### Follow-up Questions - What constant logit minimizes this loss, and what decision threshold should a model trained with it use? - Why does the loss depend only on the cost differences within each row of the matrix? - How would you extend this to K classes with a full K×K cost matrix? - How would you test `cost_sensitive_bce_grad` against `cost_sensitive_bce`?

Overview: Implement a cost-sensitive binary cross-entropy loss from logits and its gradient in NumPy, driven by a 2x2 cost matrix with sample weights and three reductions. It tests numerical stability at extreme logits, correct gradient scaling, and why only cost differences affect the optimal decision.

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

Implement cost_sensitive_bce(y_true, logits, cost_matrix, sample_weight=None, reduction="mean") and its gradient with respect to the logits, cost_sensitive_bce_grad, which takes the same arguments. cost_matrix[i][j] is the cost of predicting class j when the true class is i. With w_pos = C[1,0] - C[1,1] and w_neg = C[0,1] - C[0,0], the per-example loss for label yy and logit zz is

ℓ(y,z)=wpos ylog⁡(1+e−z)+wneg (1−y)log⁡(1+ez)\ell(y, z) = w_{pos}\, y \log\left(1 + e^{-z}\right) + w_{neg}\,(1 - y) \log\left(1 + e^{z}\right)
  • Let s be sample_weight (all ones if None ). The loss for "none" is the array s * per , for "sum" it is the float Σ s·per , and for "mean" it is the float Σ s·per / Σ s .
  • The gradient always returns an array of shape (n,) : the derivative of the reduced loss for "sum" and "mean" , and the derivative of each s·per entry for "none" .
  • Both functions must be numerically stable: logits of ±1000 give finite, exact values.
  • Raise ValueError if w_pos < 0 or w_neg < 0 , the matrix is not (2, 2) , the lengths of the inputs differ, or reduction is unknown.
  • Inputs are flattened. With unit costs ( C = [[0, 1], [1, 0]] ) and "mean" , the loss equals scikit-learn's log_loss with the same sample weights.

For example:

C = [[0, 2], [5, 0]]; y = [1, 0]; z = [0.0, 0.0]
cost_sensitive_bce(y, z, C, reduction="none")      # [3.4657, 1.3863]  (5 ln2, 2 ln2)
cost_sensitive_bce(y, z, C)                        # 2.4260  (3.5 ln2)
cost_sensitive_bce_grad(y, z, C)                   # [-1.25, 0.5]
cost_sensitive_bce_grad(y, z, C, reduction="sum")  # [-2.5, 1.0]

Constraints & Assumptions

  • y_true , logits and sample_weight may be lists or arrays of any shape. They are flattened to length n.
  • Labels are binary (0 or 1).
  • Logits can reach ±1000 in either direction.

What a Strong Answer Covers Guidance

  • Collapsing the cost matrix into w_pos and w_neg , with the shape and sign checks.
  • A log-space loss that stays finite and exact at logits of ±1000.
  • The per-logit gradient written through the sigmoid, using a sigmoid that cannot overflow.
  • The same reduction rule applied to the loss and the gradient, including the Σ s denominator for "mean" .
  • A check that the unit-cost case reduces to weighted log loss.

Follow-up Questions Guidance

  • What constant logit minimizes this loss, and what decision threshold should a model trained with it use?
  • Why does the loss depend only on the cost differences within each row of the matrix?
  • How would you extend this to K classes with a full K×K cost matrix?
  • How would you test cost_sensitive_bce_grad against cost_sensitive_bce ?