Skip to content

← Activations step 2 of 9

Easy Primitives

Implement Sigmoid

Sigmoid turns each input into a value between zero and one. It is often used to turn a binary classifier's score into a probability:

sigmoid(x) = 1 / (1 + exp(-x))

Zero maps to 0.5. Positive inputs give values above 0.5, and negative inputs give values below 0.5. For [-1.0, 0.0, 1.0], the result is approximately [0.268941, 0.5, 0.731059]. Apply the rule independently to every element.

Avoid an overflowing exponential

The direct formula computes exp(-x), which can overflow for a large negative input. An equivalent form keeps the exponent nonpositive:

  • For x >= 0, use z = exp(-x), then return 1 / (1 + z).
  • For x < 0, use z = exp(x), then return z / (1 + z).

Use a tensor selection to choose the exponent first, then compute exp. This avoids evaluating an overflowing exponential in a branch you discard. The selected formulas agree at zero.

Your task

Implement sigmoid(x) for a floating-point tensor of any shape. Preserve the shape and use basic arithmetic, exp and elementwise selection. Do not call torch.sigmoid or jax.nn.sigmoid.

In real arithmetic, finite inputs produce values strictly between zero and one. Floating-point results can round to exactly zero or one for large input magnitudes. The supplied tests include large positive and negative values; your output should not contain NaN for those finite inputs.

Loading visualization…