Implement weighted multi-label binary cross-entropy from logits with a stable gradient

Quick Overview

Implement weighted multi-label binary cross-entropy from logits in NumPy, with per-label positive weights, per-row sample weights and three reduction modes, plus its gradient. Tests numerical stability for very large logits, broadcasting and the sigmoid derivative.

Implement weighted multi-label binary cross-entropy from logits with a stable gradient

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `weighted_multilabel_bce` and its logit gradient `weighted_multilabel_bce_grad`. Given logits `z` and targets `y` of shape `(n, k)`, a per-label `pos_weight` of length `k` and a per-row `sample_weight` of length `n`, the element loss is: ```python L[i, j] = sw[i] * (pw[j] * y[i, j] * softplus(-z[i, j]) + (1 - y[i, j]) * softplus(z[i, j])) ``` Use these signatures: ```python def weighted_multilabel_bce(logits, targets, pos_weight=None, sample_weight=None, reduction="mean"): ... def weighted_multilabel_bce_grad(logits, targets, pos_weight=None, sample_weight=None, reduction="mean"): ... ``` Requirements: - `pos_weight` and `sample_weight` default to all ones when `None`. - `reduction="none"` returns the `(n, k)` array, `"sum"` returns a float sum, and `"mean"` returns the sum divided by `n * k` (not by the total weight). The gradient is scaled the same way. - Any other `reduction`, non-2D input, or mismatched shapes raise `ValueError`. Example: ```python z = [[0.0, 2.0], [-1.0, 3.0]] y = [[1.0, 0.0], [0.0, 1.0]] pos_weight = [2.0, 0.5] weighted_multilabel_bce(z, y, pos_weight=pos_weight) # ≈ 0.962694 ``` ```hint Large logits Evaluating `log(1 + exp(x))` directly overflows at `x = 1000`. Look for a NumPy function that computes the log of a sum of exponentials without forming the exponentials. ``` ```hint The gradient Differentiate the two softplus terms separately; the derivative of softplus is a familiar function. Then find a way to compute that function and its complement without subtracting two numbers that are almost equal. ``` ### Constraints & Assumptions - Loss and gradient must stay finite and exact for `|z|` up to 1000. For example, `z = 1000, y = 0` gives loss 1000 and gradient 1. - Targets are 0/1. - Weights are non-negative. ### What a Strong Answer Covers - A numerically stable softplus that keeps the loss finite and exact at $|z| = 1000$. - Correct broadcasting: `pos_weight` along columns and applied only to positive terms, `sample_weight` along rows and applied to both terms. - The analytic gradient written with $\sigma(z)$ and ${1 - \sigma(z)}$, computed without overflow or cancellation. - The three reductions, with the mean taken over $n \cdot k$ elements, the gradient scaled to match, and `ValueError` for bad reductions and shapes. - A check of the result, such as the worked example or a finite-difference comparison. ### Follow-up Questions - How would you pick `pos_weight` for a label that is positive in 1% of rows, and what does it do to the predicted probabilities? - How would you change the loss and gradient to ignore labels that are missing for some rows? - When would you normalize the mean by the total weight instead of `n * k`, and how would the gradient change? - Does the formula still work with soft targets in $[0, 1]$, for example after label smoothing?

Overview: Implement weighted multi-label binary cross-entropy from logits in NumPy, with per-label positive weights, per-row sample weights and three reduction modes, plus its gradient. Tests numerical stability for very large logits, broadcasting and the sigmoid derivative.

PracHub logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement weighted_multilabel_bce and its logit gradient weighted_multilabel_bce_grad. Given logits z and targets y of shape (n, k), a per-label pos_weight of length k and a per-row sample_weight of length n, the element loss is:

L[i, j] = sw[i] * (pw[j] * y[i, j] * softplus(-z[i, j]) + (1 - y[i, j]) * softplus(z[i, j]))

Use these signatures:

def weighted_multilabel_bce(logits, targets, pos_weight=None, sample_weight=None, reduction="mean"): ...
def weighted_multilabel_bce_grad(logits, targets, pos_weight=None, sample_weight=None, reduction="mean"): ...

Requirements:

  • pos_weight and sample_weight default to all ones when None .
  • reduction="none" returns the (n, k) array, "sum" returns a float sum, and "mean" returns the sum divided by n * k (not by the total weight). The gradient is scaled the same way.
  • Any other reduction , non-2D input, or mismatched shapes raise ValueError .

Example:

z  = [[0.0, 2.0], [-1.0, 3.0]]
y  = [[1.0, 0.0], [0.0, 1.0]]
pos_weight = [2.0, 0.5]
weighted_multilabel_bce(z, y, pos_weight=pos_weight)  # ≈ 0.962694

Constraints & Assumptions

  • Loss and gradient must stay finite and exact for |z| up to 1000. For example, z = 1000, y = 0 gives loss 1000 and gradient 1.
  • Targets are 0/1.
  • Weights are non-negative.

What a Strong Answer Covers Guidance

  • A numerically stable softplus that keeps the loss finite and exact at ∣z∣=1000|z| = 1000 .
  • Correct broadcasting: pos_weight along columns and applied only to positive terms, sample_weight along rows and applied to both terms.
  • The analytic gradient written with σ(z)\sigma(z) and 1−σ(z){1 - \sigma(z)} , computed without overflow or cancellation.
  • The three reductions, with the mean taken over n⋅kn \cdot k elements, the gradient scaled to match, and ValueError for bad reductions and shapes.
  • A check of the result, such as the worked example or a finite-difference comparison.

Follow-up Questions Guidance

  • How would you pick pos_weight for a label that is positive in 1% of rows, and what does it do to the predicted probabilities?
  • How would you change the loss and gradient to ignore labels that are missing for some rows?
  • When would you normalize the mean by the total weight instead of n * k , and how would the gradient change?
  • Does the formula still work with soft targets in [0,1][0, 1] , for example after label smoothing?