Sigmoid is usually the first activation function anyone writes. It looks like a one-liner, and most tutorials treat it as one:
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))It works for the numbers you try first. Then one day you feed it a batch of logits from a model that hasn't been tuned yet, and your training log fills up with this:
RuntimeWarning: overflow encountered in expThis post is about that warning: where it comes from, why it matters more than it looks, and how to write a sigmoid you can trust. By the end you'll have a version that is vectorised, numerically stable, handles scalars and nested lists, and is the exact shape most interview graders expect.
What sigmoid actually does
Sigmoid squashes any real number into the range (0, 1):
σ(x) = 1 / (1 + e^(−x))
A few values worth remembering, because they make debugging much faster:
| x | σ(x) | What it means |
|---|---|---|
| 0 | 0.5 | Completely undecided |
| 2 | ≈ 0.881 | Fairly confident "yes" |
| −2 | ≈ 0.119 | Fairly confident "no" |
| 10 | ≈ 0.99995 | Basically certain |
| −10 | ≈ 0.0000454 | Basically certain "no" |
That's why it shows up at the end of binary classifiers. The output reads like a probability, and the curve is smooth, so gradients flow through it.
Where the naive version breaks
Run the one-liner on some extreme values:
x = np.array([-1000.0, 0.0, 1000.0])
print(sigmoid(x))
# RuntimeWarning: overflow encountered in exp
# [0. 0.5 1. ]The answer is technically right. So why care?
For x = -1000, the code computes np.exp(1000). That number is far beyond what a 64-bit float can hold (the limit is around 1.8e308), so NumPy returns inf, raises a warning, and 1 / (1 + inf) quietly becomes 0.0.
Three things go wrong in real projects:
- The warnings drown your logs. One noisy batch can print thousands of lines, and real problems get buried.
- Strict environments fail. Many test harnesses and production services turn warnings into errors. The same code that "works" locally crashes in CI.
infspreads. In this formula it collapses to 0, but if you reusenp.exp(-x)in a loss or gradient, aninfcan turn into ananthat ruins a whole training run.
The stable version
The trick is to never call exp on a large positive number. Sigmoid has two equivalent forms:
- For x ≥ 0:
1 / (1 + exp(-x)). Here-xis zero or negative, soexp(-x)is between 0 and 1. Safe. - For x < 0:
exp(x) / (1 + exp(x)). Herexis negative, soexp(x)is between 0 and 1. Also safe.
Both are the same function (multiply the top and bottom of the first by exp(x) to get the second). We just pick whichever one is safe for each element:
import numpy as np
def sigmoid(x):
x = np.asarray(x, dtype=np.float64)
out = np.empty_like(x)
pos = x >= 0
out[pos] = 1.0 / (1.0 + np.exp(-x[pos]))
exp_x = np.exp(x[~pos])
out[~pos] = exp_x / (1.0 + exp_x)
return float(out) if out.ndim == 0 else outCheck it with warnings turned into errors, so a single overflow would crash it:
import warnings
with warnings.catch_warnings():
warnings.simplefilter("error")
print(sigmoid([-1000, 0, 1000])) # [0. 0.5 1. ]
print(sigmoid(0)) # 0.5
print(sigmoid([[-1, 0], [1, 2]]))
# [[0.26894142 0.5 ]
# [0.73105858 0.88079708]]No warnings, same answers.
Why each line is there
np.asarray(x, dtype=np.float64)accepts a scalar, a list or a nested list, and makes sure we're not doing integer maths. Without the dtype, an integer input gives an integer output array and every value rounds to 0 or 1.np.empty_like(x)keeps the input's shape, so a 2×2 input returns a 2×2 output.- Boolean masks (
pos,~pos) keep it fully vectorised. There's no Pythonforloop, which matters whenxhas a million elements. float(out) if out.ndim == 0returns a plain Python float for scalar input. Many graders check the return type, not just the value.
In practice: if SciPy is available,
scipy.special.expitis a fast, stable sigmoid you can use directly. Writing it yourself is still worth doing once, because the same trick comes back in softmax, log-sigmoid and cross-entropy.
The gradient, and why sigmoid "saturates"
Sigmoid has a famously tidy derivative:
σ′(x) = σ(x) · (1 − σ(x))
def sigmoid_grad(x):
s = sigmoid(x)
return s * (1 - s)
print(sigmoid_grad(np.array([-10.0, 0.0, 10.0])))
# [4.53958077e-05 2.50000000e-01 4.53958077e-05]Look at those numbers. The largest possible gradient is 0.25, at x = 0. At x = ±10 it's about 0.00005.
That's the saturation problem. When a neuron's input drifts far from zero, its gradient almost disappears and the neuron stops learning. Stack several sigmoid layers and you multiply these small numbers together. That's the vanishing-gradient problem that pushed deep networks towards ReLU and its relatives in hidden layers.
Sigmoid is still the right tool in a few places:
- the output of a binary classifier, paired with binary cross-entropy;
- gates in LSTMs and GRUs, where you really want a value between 0 and 1;
- multi-label classification, where each label gets its own independent probability.
Common mistakes
- Integer input.
np.expon an integer array works, but if you build the output withnp.empty_likeon an int array, everything truncates. Cast to float first. - Python loops.
[1 / (1 + math.exp(-v)) for v in x]is slow and fails on nested lists. Vectorise. - Computing sigmoid and then log separately.
np.log(sigmoid(x))underflows tolog(0) = -inffor very negative x. If you need log-probabilities, use a log-sigmoid form directly:-np.logaddexp(0, -x). - Returning a 0-d array for scalar input.
np.array(0.5)prints like0.5but isn't afloat. Some tests will reject it.
Key takeaways
- The textbook formula overflows for large negative inputs. The answer survives, but your logs, CI and later maths may not.
- Pick the safe algebraic form per element with a boolean mask. It's still fully vectorised.
- The gradient peaks at 0.25 and vanishes as |x| grows. That's why sigmoid belongs at the output, not in deep hidden stacks.
Want to practise the same idea? The Stable Masked Softmax problem in our problem set uses exactly this "shift before you exponentiate" pattern, and it's graded against extreme inputs. Next, read our post on softmax and the log-sum-exp trick, which extends the idea to many classes.
Frequently asked questions
Why does np.exp overflow in the sigmoid function?
For large negative inputs, the textbook formula computes exp(-x) with a large positive argument. Above roughly 709, the result exceeds the largest 64-bit float, so NumPy returns infinity and raises an overflow warning.
How do you implement a numerically stable sigmoid in NumPy?
Use 1 / (1 + exp(-x)) for non-negative inputs and exp(x) / (1 + exp(x)) for negative inputs, selecting per element with a boolean mask. Both forms are mathematically equal, but each only exponentiates non-positive numbers, so it never overflows.
What is the derivative of the sigmoid function?
The derivative is sigmoid(x) multiplied by (1 - sigmoid(x)). Its maximum value is 0.25 at x = 0, and it approaches zero for large positive or negative inputs, which causes vanishing gradients in deep networks.