Neural network formulas: a cheat sheet · Activation functions

The sigmoid: the logistic function

The function that turns any number into a probability. We take it apart bone by bone: what the formula is made of, where the derivative σ(1 − σ) comes from, how the sigmoid draws the decision boundary of logistic regression, and why it makes gradients vanish in deep networks.

Javharbek Abdulatipov · 30 min read
$$\sigma(x)=\frac{1}{1+e^{-x}}$$

Why we need it

A neural network, logistic regression, gradient boosting — inside all of them you end up with a plain number: $3.7$, $-12$, $0.2$. But the question is often different: how likely is the email spam, will the client repay the loan, is there a person in the frame. A probability must lie between 0 and 1. The sigmoid is the most natural bridge from “any number” to “a probability”.

Where it appears:

  • the output of a binary classifier — logistic regression, the last neuron of a network, $p=\sigma(z)$;
  • gates in LSTM and GRU — a number between 0 and 1 decides what share of the information to let through and what to forget;
  • gradient boosting for classification — XGBoost, LightGBM and CatBoost add trees into a raw score, and the sigmoid turns it into a probability;
  • modern activations — SiLU (Swish) is $x\cdot\sigma(x)$; the SwiGLU block of LLaMA and Qwen is built on it;
  • statistics — the cumulative distribution function of the logistic law and the link between probability and log-odds (logit).
The essentials in a minute

$\sigma$ squeezes the whole real line into $(0,\,1)$, passes through $(0,\,0.5)$ and is symmetric: $\sigma(-x)=1-\sigma(x)$. Its derivative $\sigma'=\sigma(1-\sigma)$ never exceeds $0.25$ — the source of both convenience (cheap backprop) and trouble (vanishing gradients).

Intuition: squeezing infinity

Picture a road between a floor at $y=0$ and a ceiling at $y=1$. On the left the road almost lies on the floor, on the right it almost touches the ceiling, and in the middle it rises smoothly. However far you walk left or right, the floor and the ceiling stay out of reach — they are the asymptotes.

Drag the point on the plot. The orange line is the tangent: its slope is the derivative $\sigma'(x)$. The climb is steepest at the centre, while at the edges the road is almost flat — the derivative there is close to zero.

Figure 1. The sigmoid, its tangent and its derivative. Drag the blue point, or use the arrow keys when it has focus. The maximum of the derivative, $0.25$, sits exactly under the centre $x=0$.
What to notice

At $x=4$ the sigmoid is already $0.982$, while the derivative is only $0.018$, 14 times smaller than at the centre. This is saturation: the input keeps growing, but the output barely changes.

The formula, bone by bone

Let us assemble the sigmoid from three simple steps and follow what each one does to the number $x$.

$$x\;\xrightarrow{\;\cdot(-1)\;}\;-x\;\xrightarrow{\;\exp\;}\;e^{-x}\in(0,\,\infty)\;\xrightarrow{\;+1\;}\;1+e^{-x}\in(1,\,\infty)\;\xrightarrow{\;1/\cdot\;}\;\sigma(x)\in(0,\,1)$$
$e^{-x}$
the exponential is always positive: as $x\to+\infty$ it tends to 0, as $x\to-\infty$ to infinity;
$1+e^{-x}$
the denominator is always greater than 1 — so the fraction is always less than 1;
$\frac{1}{1+e^{-x}}$
the reciprocal of a positive number greater than 1 lies strictly between 0 and 1.

It pays to recognise the same function in other forms:

$$\sigma(x)=\frac{1}{1+e^{-x}}=\frac{e^{x}}{1+e^{x}}=\frac{1}{2}\Bigl(1+\tanh\frac{x}{2}\Bigr)$$

The second form comes from multiplying the numerator and the denominator by $e^x$; it is convenient for negative $x$ (see the section on code). The third links the sigmoid to the hyperbolic tangent: $\tanh x=2\sigma(2x)-1$ is the same S-curve, squeezed horizontally by 2, stretched twice as tall and shifted down by 1.

$x$$\sigma(x)$$\sigma'(x)$
−60.00250.0025
−40.01800.0177
−20.11920.1050
−10.26890.1966
00.50000.2500
10.73110.1966
20.88080.1050
40.98200.0177
60.99750.0025

The table shows two symmetries: the sigmoid values at $\pm x$ add up to one, and the derivative is an even function.

Properties and shape

  • Domain: all real numbers; range: the open interval $(0,\,1)$.
  • Monotonicity: strictly increasing, since $\sigma'(x)>0$ for every $x$.
  • Asymptotes: $\lim_{x\to-\infty}\sigma(x)=0$ and $\lim_{x\to+\infty}\sigma(x)=1$.
  • Point symmetry about $(0,\,0.5)$: $\sigma(-x)=1-\sigma(x)$.
  • Inflection point: a single one, at $x=0$; the function is convex on the left and concave on the right.
  • Lipschitz continuity: $|\sigma(a)-\sigma(b)|\le\tfrac14|a-b|$ — the output changes no faster than a quarter of the change in the input.
Why σ(−x) = 1 − σ(x)
$$1-\sigma(x)=1-\frac{1}{1+e^{-x}}=\frac{e^{-x}}{1+e^{-x}}=\frac{1}{e^{x}+1}=\sigma(-x)$$

In the second-to-last step the numerator and the denominator are multiplied by $e^{x}$.

Weight and bias: how a neuron reshapes the sigmoid

In a neuron the sigmoid receives not $x$ but $z=wx+b$. The weight $w$ stretches the curve horizontally, the bias $b$ shifts it. The centre, where the output equals $0.5$, lands at $x_0=-b/w$, and the slope at the centre is $w/4$.

Figure 2. $\sigma(wx+b)$. For large $|w|$ the curve becomes almost a step; for $w<0$ it flips. The pale curves are $\sigma\bigl((wx+b)/4\bigr)$ and $\sigma\bigl((wx+b)/2\bigr)$: the same centre, but a slope 4 and 2 times smaller.
A step as the limit

As $w\to+\infty$, $\sigma(w x)$ tends to the Heaviside step: 0 to the left of zero, 1 to the right (at $x=0$ itself the value is always $0.5$). That is how the sigmoid historically entered neural networks — as a smooth, differentiable replacement for the McCulloch–Pitts threshold neuron.

The derivative: σ′ = σ(1 − σ)

This is the key formula of the page. Let us derive it in two ways — head-on and elegantly.

Method 1. The chain rule, step by step

Write $\sigma(x)=(1+e^{-x})^{-1}$ and apply the chain rule:

$$\sigma'(x)=-(1+e^{-x})^{-2}\cdot\bigl(1+e^{-x}\bigr)'=-(1+e^{-x})^{-2}\cdot(-e^{-x})=\frac{e^{-x}}{(1+e^{-x})^{2}}$$

Split the fraction into a product of two factors:

$$\frac{e^{-x}}{(1+e^{-x})^{2}}=\underbrace{\frac{1}{1+e^{-x}}}_{\sigma(x)}\cdot\underbrace{\frac{e^{-x}}{1+e^{-x}}}_{1-\sigma(x)}$$

The second factor is $1-\sigma(x)$, as shown in the section on properties.

Method 2. Through the logarithm

Take the logarithm: $\ln\sigma(x)=-\ln(1+e^{-x})$. Differentiate both sides:

$$\frac{\sigma'(x)}{\sigma(x)}=\frac{e^{-x}}{1+e^{-x}}=1-\sigma(x)\quad\Longrightarrow\quad\sigma'(x)=\sigma(x)\bigl(1-\sigma(x)\bigr)$$
$$\sigma'(x)=\sigma(x)\bigl(1-\sigma(x)\bigr)$$

Why this matters in practice: on the forward pass the network has already computed $s=\sigma(z)$. On the backward pass the derivative costs a single multiplication $s(1-s)$ — no new exponential.

The maximum of the derivative and the second derivative

The product $s(1-s)$ for $s\in(0,1)$ is an upside-down parabola with its vertex at $s=\tfrac12$. Hence $\max\sigma'=\tfrac12\cdot\tfrac12=\tfrac14$, reached at $x=0$. Differentiating once more:

$$\sigma''(x)=\sigma(x)\bigl(1-\sigma(x)\bigr)\bigl(1-2\sigma(x)\bigr)$$

The second derivative vanishes at $\sigma=\tfrac12$, i.e. at the inflection point $x=0$. Its extrema are at $x=\pm\ln(2+\sqrt3)\approx\pm1.317$, where the slope of the sigmoid changes fastest; the value there is $\mp\sqrt3/18\approx\mp0.096$.

The Taylor series around zero

From the link with tanh we get the expansion:

$$\sigma(x)=\frac12+\frac{x}{4}-\frac{x^{3}}{48}+\frac{x^{5}}{480}-\frac{17x^{7}}{80640}+\dots$$

Near zero the sigmoid is almost linear: $\sigma(x)\approx\tfrac12+\tfrac{x}{4}$. That is why a network of sigmoids with small weights behaves almost like a linear model. The series converges only for $|x|<\pi$: the function has singular points in the complex plane at $x=\pm i\pi$.

Figure 3. Taylor polynomials of orders 1, 3, 5 and 7. Inside the band $|x|<\pi$ accuracy improves with the order; outside it the higher the order, the faster the polynomial leaves the sigmoid. At $x=2$ the third-order approximation gives $0.833$ instead of $0.881$.

The probabilistic meaning: odds and the logit

Why is it reasonable to read the sigmoid’s output as a probability? Let $p$ be the probability of an event. The ratio $p/(1-p)$ is called the odds: at $p=0.8$ the odds are $4:1$. The logarithm of the odds is the logit:

$$\operatorname{logit}(p)=\ln\frac{p}{1-p}\qquad\Longleftrightarrow\qquad p=\sigma\bigl(\operatorname{logit}(p)\bigr)$$

The logit and the sigmoid are inverses of each other. The logit maps a probability from $(0,1)$ onto the whole real line, where contributions of features are easy to add up. Logistic regression assumes exactly that: the log-odds depend linearly on the features, $\ln\frac{p}{1-p}=w^\top x+b$. Hence the sigmoid at the output.

Figure 4. On the left the sigmoid maps the logit $z$ to a probability $p$; on the right the logit maps it back. At $p=0.8$ the odds are 4 and the logit is $\ln4\approx1.386$. Note how fast the logit grows near the edges — from $p=0.99$ to $p=0.999$ it changes by $2.3$.
Another interpretation

The sigmoid is the cumulative distribution function of the logistic law: if the noise $\varepsilon$ is logistic, then $P(\varepsilon\le x)=\sigma(x)$. The similar model with normal noise, $\Phi(x)$, is called probit regression; its curve nearly coincides with $\sigma(1.7x)$.

The sigmoid in many dimensions

A neuron has many inputs: $z=w_1x_1+w_2x_2+\dots+b$. The sigmoid of such a linear function is a “fold” that rises from 0 to 1 across the boundary $w^\top x+b=0$ and stays constant along it. The weight vector $w$ points in the direction of the steepest ascent, and its length sets how steep the fold is.

Figure 5. Logistic regression on two features. On the left, the probability surface in 3D (you can rotate it); the points sit at the height of their class. On the right, the view from above: the solid line is the boundary $p=0.5$, the dashed lines are $p=0.1$ and $p=0.9$, the arrow is the direction of $w$. Press “Play”: gradient descent on BCE with step $0.5$ finds the weights by itself.

Training uses the same derivative. For the BCE loss the gradient with respect to the logit is $\sigma(z)-y$ (derived on the BCE page), so a gradient-descent step on the weights is:

$$w\leftarrow w-\eta\,\frac1n\sum_{i=1}^{n}\bigl(\sigma(w^\top x_i+b)-y_i\bigr)\,x_i$$
Linearly separable data

If a line separates the classes perfectly, BCE keeps decreasing as $\|w\|$ grows: the fold gets steeper and tends to a step, and the weights run off to infinity. In practice this is cured with regularization ($L_2$) or early stopping.

The sigmoid in training: saturation and vanishing gradients

If a neuron’s inputs $z$ are large in magnitude, the sigmoid works on its flat tails, where $\sigma'(z)\approx0$. Hardly any gradient flows through such a neuron — it is saturated. Saturation, $\sigma'<0.01$, starts at $|z|>4.6$.

Figure 6. The blue area is the distribution of the inputs $z\sim N(\mu,\,s^2)$, the orange one is the derivative (the blue curve’s height is in arbitrary units). At $s=1$ the mean derivative is $0.207$ and there are almost no saturated inputs; at $s=4$ the mean derivative drops to $0.091$, and a quarter of the inputs ($25\%$) are already saturated.

This gives the initialization rule: weights are chosen so that the variance of $z$ is of order one (LeCun initialization, $\operatorname{Var}w=1/n_{\text{in}}$, or Glorot (Xavier) initialization, $\operatorname{Var}w=2/(n_{\text{in}}+n_{\text{out}})$), and the data are normalized.

Vanishing gradients in a deep network

Let $h_k=\sigma(z_k)$, $z_k=W_kh_{k-1}$. By the chain rule the gradient of the loss $\mathcal L$ with respect to the output of layer $l$ is a product of the Jacobians of all layers above it, and each of them contains $\operatorname{diag}\bigl(\sigma'(z_k)\bigr)$:

$$\frac{\partial \mathcal L}{\partial h_l}=\frac{\partial \mathcal L}{\partial h_L}\,\frac{\partial h_L}{\partial h_{L-1}}\cdots\frac{\partial h_{l+1}}{\partial h_l},\qquad \frac{\partial h_k}{\partial h_{k-1}}=\operatorname{diag}\bigl(\sigma'(z_k)\bigr)\,W_k$$

For the sigmoid every $\sigma'\le\tfrac14$, so after 10 layers the factor from the derivatives alone is at most $0.25^{10}\approx9.5\cdot10^{-7}$. With Glorot initialization the weights $W_k$ do not compensate for it: they keep the norm of the signal at roughly one.

Figure 7. The gradient norm at every layer of a random network of width 64 (Glorot initialization for sigmoid and tanh, He for ReLU). The vertical scale is logarithmic; the dashed line is the estimate $0.25^{L-l}$. At depth 10 the sigmoid’s gradient at the input is $2.4\cdot10^{-6}$ times its value at the output; for tanh the ratio is about $0.2$, for ReLU about $2.4$ (the gradient even grows a little).
Why the sigmoid left the hidden layers

Before 2010 deep networks with sigmoids trained poorly unless one resorted to layer-wise pre-training (Hinton et al., 2006). Glorot and Bengio (2010) showed the role of saturation and proposed an initialization, and ReLU (Nair and Hinton, 2010; Glorot et al., 2011) all but removed the problem. Today the sigmoid lives where a share between 0 and 1 is exactly what is needed: at the output of a binary classifier and in gates.

In code: stable and without surprises

The naive formula $1/(1+e^{-x})$ at $x=-1000$ computes $e^{1000}$ — an overflow. The result still comes out as 0, but with a warning, and $\log\sigma(x)$ already yields $-\infty$. The second problem is loss of precision: $1-\sigma(40)$ in float64 is exactly 0, while the true value $\sigma(-40)\approx4.25\cdot10^{-18}$.

pythonimport numpy as np

def sigmoid(x):
    """Stable sigmoid: exp never gets a large positive argument."""
    x = np.asarray(x, dtype=float)
    out = np.empty_like(x)
    pos = x >= 0
    out[pos] = 1.0 / (1.0 + np.exp(-x[pos]))
    ex = np.exp(x[~pos])
    out[~pos] = ex / (1.0 + ex)
    return out

def sigmoid_grad(x):
    s = sigmoid(x)
    return s * (1.0 - s)

def log_sigmoid(x):
    # log σ(x) = −softplus(−x) = −log(1 + e^(−x)), without log(0)
    return -np.logaddexp(0.0, -x)

print(sigmoid([-40.0, 0.0, 40.0]))        # [4.24835426e-18 5.00000000e-01 1.00000000e+00]
print(1 - sigmoid(40.0), sigmoid(-40.0))  # 0.0 4.248354255291589e-18 — the subtraction ate everything
print(log_sigmoid(-1000.0))               # -1000.0 (a naive np.log(sigmoid) would give -inf)
pythonimport torch
import torch.nn as nn

z = torch.tensor([-2.0, 0.0, 2.0], requires_grad=True)
p = torch.sigmoid(z)            # tensor([0.1192, 0.5000, 0.8808])
p.sum().backward()
print(z.grad)                   # tensor([0.1050, 0.2500, 0.1050]) = σ(1 − σ)

# For classification pass the logits to the loss, not σ(z):
loss_fn = nn.BCEWithLogitsLoss()  # a stable log σ(z) inside
loss = loss_fn(z, torch.tensor([0.0, 1.0, 1.0]))
The rule

If a logarithm follows, do not compute $\sigma$ separately. Use $\log\sigma(x)=-\operatorname{softplus}(-x)$ or ready-made losses on logits: BCEWithLogitsLoss in PyTorch, from_logits=True in Keras.

Common mistakes

  1. Sigmoids in the hidden layers of a deep network — vanishing gradients and shifted (non-centred) activations. Use ReLU, GELU, SiLU; keep the sigmoid for the output or for gates.
  2. Sigmoids instead of softmax for mutually exclusive classes. For $K>2$ mutually exclusive classes you need softmax; a sigmoid on every output means multi-label, where the classes are independent.
  3. A double sigmoid: the model already returns a probability and the loss applies σ again (for example, BCEWithLogitsLoss on top of sigmoid). Training runs, but the “probabilities” are squeezed into $(0.5,\,0.73)$, the loss cannot get small, and the gradients are distorted.
  4. The “default” 0.5 threshold. For calibrated probabilities it minimizes the error rate, but only when both kinds of error cost the same. With unequal costs, or for F1 or recall on imbalanced classes, the best threshold is different — tune it for your metric on validation data.
  5. Reading “σ(z) = 0.9 means the model is 90% sure” without calibration. The sigmoid gives a number in $(0,1)$, but calibration is a property of training (BCE encourages it, overfitting spoils it).
  • tanh: $\tanh x=2\sigma(2x)-1$ — a centred sigmoid with maximum slope 1.
  • Softmax: for two classes $\operatorname{softmax}(z_1,z_2)_1=\sigma(z_1-z_2)$.
  • BCE: paired with the sigmoid it gives the gradient $\hat y-y$ with respect to the logit — without the factor $\sigma'$, so no saturation while the model is wrong.
  • SiLU / Swish: $x\,\sigma(x)$ — the sigmoid as a “soft gate” for the input itself.
  • Focal Loss: usually computed from the probability of the correct class $p_t$: $\sigma(z)$ for $y=1$ and $1-\sigma(z)=\sigma(-z)$ for $y=0$.

Summary

1) $\sigma(x)=1/(1+e^{-x})$ maps $\mathbb R$ to $(0,1)$, passes through $(0,\,0.5)$ and is symmetric: $\sigma(-x)=1-\sigma(x)$. 2) $\sigma'=\sigma(1-\sigma)\le\tfrac14$: backprop is cheap, but the gradient dies on the tails. 3) The sigmoid is the inverse of the logit: logistic regression models the log-odds with a linear function. 4) In many dimensions it is a fold along the hyperplane $w^\top x+b=0$. 5) In code — stable forms and losses on logits.

Check yourself

1. What is $\sigma(-3)$ if $\sigma(3)\approx0.953$?
2. What is the largest value of the sigmoid’s derivative?
3. A neuron computes $\sigma(wx+b)$ with $w=2$, $b=-4$. Where is the output $0.5$?
4. Why does PyTorch recommend BCEWithLogitsLoss over sigmoid + BCELoss for binary classification?
5. What is the best-case gradient factor through a chain of 5 sigmoids?