InferenceAIAll articles

Sigmoid in NumPy: Why the One-Liner Overflows and How to Fix It

By InferenceAI Editorial · 8 min read · beginner · Updated

The textbook sigmoid prints overflow warnings on extreme inputs. Learn the stable, vectorised version, its gradient, and where sigmoid still belongs.

Sigmoid is usually the first activation function anyone writes. It looks like a one-liner, and most tutorials treat it as one:

python
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:

text
RuntimeWarning: overflow encountered in exp

This 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
00.5Completely undecided
2≈ 0.881Fairly confident "yes"
−2≈ 0.119Fairly confident "no"
10≈ 0.99995Basically certain
−10≈ 0.0000454Basically 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:

python
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:

  1. The warnings drown your logs. One noisy batch can print thousands of lines, and real problems get buried.
  2. Strict environments fail. Many test harnesses and production services turn warnings into errors. The same code that "works" locally crashes in CI.
  3. inf spreads. In this formula it collapses to 0, but if you reuse np.exp(-x) in a loss or gradient, an inf can turn into a nan that 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 -x is zero or negative, so exp(-x) is between 0 and 1. Safe.
  • For x < 0: exp(x) / (1 + exp(x)). Here x is negative, so exp(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:

python
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 out

Check it with warnings turned into errors, so a single overflow would crash it:

python
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 Python for loop, which matters when x has a million elements.
  • float(out) if out.ndim == 0 returns 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.expit is 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))

python
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

  1. Integer input. np.exp on an integer array works, but if you build the output with np.empty_like on an int array, everything truncates. Cast to float first.
  2. Python loops. [1 / (1 + math.exp(-v)) for v in x] is slow and fails on nested lists. Vectorise.
  3. Computing sigmoid and then log separately. np.log(sigmoid(x)) underflows to log(0) = -inf for very negative x. If you need log-probabilities, use a log-sigmoid form directly: -np.logaddexp(0, -x).
  4. Returning a 0-d array for scalar input. np.array(0.5) prints like 0.5 but isn't a float. 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.

#numpy#activation-functions#numerical-stability#python

Sources and further reading

Practise what you just read

Solve hands-on AI and ML coding problems in your browser, with instant feedback on every test case.

Browse problems