Overview
The sigmoid turns a score of any size into something that can be read as a probability. A score of zero maps to 0.5. Large positive scores approach 1 and large negative scores approach 0, in an S-shaped curve. The score itself is the log-odds: each extra unit multiplies the odds by . The temperature divides the score first. A temperature above 1 flattens the curve so outputs stay nearer 0.5, and a temperature below 1 sharpens it toward a hard step.
A short history
Pierre François Verhulst introduced the logistic function in the 1830s and 1840s to describe population growth that levels off. Statisticians later built logistic regression on it. It became the standard neural network activation when Rumelhart, Hinton and Williams popularised backpropagation in 1986, because it is smooth and differentiable. It was later replaced in hidden layers by ReLU, since it saturates and shrinks gradients, but it remains the usual choice for outputs and gates.
How it works
- Take the input and divide it by the temperature .
- Compute . The template does this through
logaddexpso that large inputs cannot overflow. - Read the result as a number strictly between 0 and 1.
- During training, multiply the incoming gradient by , where is the output just computed.
Watch out for
- The slope is at most and nearly zero for large inputs of either sign. Stacked sigmoids multiply these small factors, which makes gradients vanish in deep networks.
- Outputs are always positive, so the next layer receives inputs that are not centred on zero. That slows gradient descent compared with tanh.
- Feeding sigmoid outputs into a logarithm loses precision when the output rounds to 0 or 1. Use a loss that takes the raw score, such as binary cross-entropy from logits.
- Sigmoid outputs for several classes do not sum to 1. For one label among many, softmax is the right function.
Use cases
When to use it
The output of a binary or multi-label classifier, and gates inside LSTMs and gated units, where a value between 0 and 1 is needed. It is rarely the best choice for hidden layers.
In industry
- Credit and lending
- Logistic regression scorecards pass a weighted sum of applicant features through a sigmoid to produce a probability of default.
- Medical imaging
- Classifiers that flag several possible findings on one scan use a sigmoid per finding, since more than one can be present at once.
- Sequence models
- LSTM and GRU networks use sigmoids as gates that decide how much of each value to keep, forget or output.
Choosing it: what must hold
- A quantity that should lie between 0 and 1: a probability for a yes or no label, or a gate.
- Use at the output or in a gate, not as the activation of many stacked hidden layers.
- A loss that takes the raw score, such as binary cross-entropy with logits, to avoid numerical trouble at the extremes.
When to choose something else
| If | Use instead |
|---|---|
| Exactly one of several classes is correct | Softmax |
| You need a hidden layer activation in a deep network | ReLU or GELU |
| You need a bounded output centred on zero | Tanh |
Math foundations
The function
The logistic curve with temperature . At it is the standard sigmoid . It equals 0.5 at for every .
The input is the log-odds
The inverse of the standard sigmoid is the logit. This is why the raw score of a binary classifier is called a logit: it is the log of the odds the model assigns.
Symmetry
Flipping the sign of the score swaps the probability with its complement. It also means the curve is point-symmetric about its centre at 0.5.
Its slope
The slope is written in terms of the output itself, so no extra exponential is needed. This is what
backwardcomputes.The largest slope
The product peaks at . At no input passes more than a quarter of the gradient, which is the root of the vanishing gradient problem.
Symbols
- the input score, also called the logit
- the temperature,
temperaturein the config, default 1 - the standard sigmoid, the case T = 1
- the sigmoid with temperature T
- the output of the sigmoid, a number between 0 and 1
Worked by hand
Compute the sigmoid and its slope at with . Use .
A score of 2 maps to 0.8808 and passes only about a tenth of the gradient. By symmetry a score of maps to 0.1192 with the same slope.
Visual example
Loading the example.
Try this
- Move across the curve and read the output and the slope together.
- Find where the slope is close to zero: a unit there has stopped learning.
Code sample
import numpy as np
from impl import Sigmoid
from config import SigmoidConfig
act = Sigmoid(SigmoidConfig(temperature=1.0))
p = act.forward(np.array([-2.0, 0.0, 2.0])) # [0.1192, 0.5, 0.8808]
dp = act.backward(np.array([-2.0, 0.0, 2.0])) # [0.105, 0.25, 0.105]Read the implementation (39 lines)
"""Sigmoid: logistic function, f(x) = 1 / (1 + exp(-x / temperature)).
NumPy only. `forward` computes the activation, `backward` the gradient with respect to the input.
"""
from __future__ import annotations
import numpy as np
try:
from .config import SigmoidConfig
except ImportError: # run from the template's own folder
from config import SigmoidConfig
def _sigmoid(x: np.ndarray) -> np.ndarray:
"""Logistic function 1 / (1 + exp(-x)), written so that large |x| cannot overflow."""
return np.exp(-np.logaddexp(0.0, -x))
class Sigmoid:
"""f(x) = 1 / (1 + exp(-x / temperature)), output in (0, 1)."""
def __init__(self, config: SigmoidConfig | None = None) -> None:
self.config = config or SigmoidConfig()
def forward(self, x: np.ndarray) -> np.ndarray:
"""Apply the activation element by element. x: any shape. Returns the same shape."""
x = np.asarray(x, dtype=float)
return _sigmoid(x / self.config.temperature)
def backward(self, x: np.ndarray, grad_output: np.ndarray | None = None) -> np.ndarray:
"""d f / d x at x, times `grad_output` when given (the chain rule step of backpropagation).
f'(x) = f(x) * (1 - f(x)) / temperature.
"""
s = self.forward(x)
local = s * (1.0 - s) / self.config.temperature
return local if grad_output is None else local * np.asarray(grad_output, dtype=float)
__call__ = forward- Repository
- gitlab.com/designsbyduhart/solomon-templates/activation-sigmoid
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Build Sigmoid(SigmoidConfig(temperature=1.0)) and call forward on -1000, 0 and 1000 to confirm there is no overflow. Then compare backward at 0 for temperatures 0.5, 1 and 2 with the formula .
Check on learning
- A ten-layer network uses sigmoid in every hidden layer. Estimate the largest possible factor by which the activations alone scale the gradient from the last layer to the first.
A way to think about it
Each layer contributes at most 0.25. Raise that to the tenth power, and note that weights can offset this only if they are large.
- Why is it safer to give a loss function the raw score than the sigmoid output?
A way to think about it
Compute in double precision and then . Compare with a formula that works on the score directly.
- You lower the temperature toward zero. What does the function become, and what happens to its usefulness for training?
A way to think about it
The curve approaches a step at zero. Look at the slope formula: it is huge in a vanishing band and zero elsewhere.
- When would you put a sigmoid on each of five outputs rather than a softmax across them?
A way to think about it
Ask whether the five labels exclude one another. Independent yes or no questions need independent probabilities that do not have to sum to 1.