Stable Masked Sigmoid From Scratch

Quick Overview

Implement an elementwise sigmoid in NumPy that never overflows, even when floating-point overflow is set to raise an error. It tests why np.where still evaluates both branches, how boolean masks keep exp on safe inputs, and how to preserve the array's shape and dtype.

Stable Masked Sigmoid From Scratch

Role: Data Scientist

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `stable_sigmoid_masked(z)`. Given a `float64` NumPy array `z` (1-D or 2-D), return a new `float64` array with `out.shape == z.shape` holding the elementwise sigmoid. The grader runs it inside `np.errstate(over='raise', invalid='raise')`, so `np.where` over two fully evaluated branches fails. The function must: - Split by boolean masks: `z >= 0` uses `1/(1+exp(-z))`, and `z < 0` uses `exp(z)/(1+exp(z))`. - Evaluate each branch only on its masked elements, writing into a preallocated output buffer. - Raise no `FloatingPointError`. - Match `expit` to floating-point tolerance. Only NumPy is available. Do not call `expit`. Example: ```python z = np.array([-1000.0, -50.0, 0.0, 50.0, 1000.0]) stable_sigmoid_masked(z) # -> [0.0, ~1.93e-22, 0.5, ~1.0, 1.0] z2 = np.array([[-800.0, 0.0], [0.0, 800.0]]) stable_sigmoid_masked(z2).shape # (2, 2) ``` ```hint Check the sign of each exponent For each of the two formulas, work out the sign of the argument passed to `exp` on the elements that formula receives. In float64, `exp` only overflows when its argument is large and positive. ``` ```hint Keeping the shape `z[mask]` returns a flat 1-D copy. Think about how assigning through the same mask puts the values back where they came from, which matters for the 2-D case. ``` ### Constraints & Assumptions - `z` is a `float64` NumPy array with one or two dimensions. - The call runs under `np.errstate(over='raise', invalid='raise')`. Underflow is not trapped, so a value that underflows to `0.0` (as for `-1000.0` in the example) is acceptable. - Only NumPy is available. `scipy.special.expit` is the reference for correctness but may not be called. - The function returns a new array and leaves `z` unchanged. ### What a Strong Answer Covers - Why the textbook formula and `np.where` overflow under the strict error policy even though `np.where` throws the bad values away. - A check that each branch only passes non-positive arguments to `exp`, and that the two formulas are algebraically equal. - Boolean masks with a preallocated buffer, so the output keeps the input's shape and dtype for both 1-D and 2-D arrays. - Behavior at the extremes: exactly 0, very large positive and negative values, and underflow to 0.0. - Time and space cost. ### Follow-up Questions - Why is masking safe here while `np.where` is not? - How would you extend this to preserve NaNs or handle non-contiguous inputs? - Can you get the same stability with a single `exp` call and no boolean masks?

Overview: Implement an elementwise sigmoid in NumPy that never overflows, even when floating-point overflow is set to raise an error. It tests why np.where still evaluates both branches, how boolean masks keep exp on safe inputs, and how to preserve the array's shape and dtype.

General logo
General
Nov 25, 2026
mediumData ScientistOtherMachine Learning
0
0

Implement stable_sigmoid_masked(z). Given a float64 NumPy array z (1-D or 2-D), return a new float64 array with out.shape == z.shape holding the elementwise sigmoid. The grader runs it inside np.errstate(over='raise', invalid='raise'), so np.where over two fully evaluated branches fails.

The function must:

  • Split by boolean masks: z >= 0 uses 1/(1+exp(-z)) , and z < 0 uses exp(z)/(1+exp(z)) .
  • Evaluate each branch only on its masked elements, writing into a preallocated output buffer.
  • Raise no FloatingPointError .
  • Match expit to floating-point tolerance.

Only NumPy is available. Do not call expit.

Example:

z = np.array([-1000.0, -50.0, 0.0, 50.0, 1000.0])
stable_sigmoid_masked(z)
# -> [0.0, ~1.93e-22, 0.5, ~1.0, 1.0]

z2 = np.array([[-800.0, 0.0], [0.0, 800.0]])
stable_sigmoid_masked(z2).shape  # (2, 2)

Constraints & Assumptions

  • z is a float64 NumPy array with one or two dimensions.
  • The call runs under np.errstate(over='raise', invalid='raise') . Underflow is not trapped, so a value that underflows to 0.0 (as for -1000.0 in the example) is acceptable.
  • Only NumPy is available. scipy.special.expit is the reference for correctness but may not be called.
  • The function returns a new array and leaves z unchanged.

What a Strong Answer Covers Guidance

  • Why the textbook formula and np.where overflow under the strict error policy even though np.where throws the bad values away.
  • A check that each branch only passes non-positive arguments to exp , and that the two formulas are algebraically equal.
  • Boolean masks with a preallocated buffer, so the output keeps the input's shape and dtype for both 1-D and 2-D arrays.
  • Behavior at the extremes: exactly 0, very large positive and negative values, and underflow to 0.0.
  • Time and space cost.

Follow-up Questions Guidance

  • Why is masking safe here while np.where is not?
  • How would you extend this to preserve NaNs or handle non-contiguous inputs?
  • Can you get the same stability with a single exp call and no boolean masks?