A model computes a score from its inputs. That score can be any real number: , , . But often we need something tamer. A probability must be between 0 and 1. A gate that decides “how much to let through” must be between 0 and 1. A feature that should not explode should stay in a small range.
The tool for this is a squashing function: a function that takes any real number and returns a number in a fixed, bounded range. In this lesson a squashing function is an S-shaped curve that rises (or at least never falls) and levels off at both ends. This is the last lesson of the precalculus module, so it uses everything before it: functions and transformations (P1.A1), (P1.A2) and notation (P1.A4). And it ends with a question, “how steep is this curve?”, that is the doorway to calculus.
Build the sigmoid, one step at a time
The most famous squashing function is the sigmoid (also called the logistic function):
( is the Greek letter sigma; in this course it is the sigmoid, as in P1.A4. The name comes from “S-shaped”.) Build it in four small steps, starting from :
- Flip the sign: .
- Exponentiate: . This is always positive. It is huge when is very negative and tiny when is large and positive (P1.A2).
- Add 1: . Now the number is always greater than 1.
- Take the reciprocal: . A number greater than 1 has a reciprocal between 0 and 1.
Try it on a few values:
| −6 | 403.43 | 404.43 | 0.0025 |
| −4 | 54.60 | 55.60 | 0.0180 |
| −2 | 7.389 | 8.389 | 0.1192 |
| 0 | 1 | 2 | 0.5 |
| 2 | 0.1353 | 1.1353 | 0.8808 |
| 4 | 0.0183 | 1.0183 | 0.9820 |
| 6 | 0.0025 | 1.0025 | 0.9975 |
Look down the last column: it climbs from near 0 to near 1, passing 0.5 at . That is the S-curve.
What the table tells you
- Range . Step 2 gives a positive number, so the denominator is strictly greater than 1, so is strictly between 0 and 1. It never reaches 0 or 1, but gets as close as you like. The lines and are horizontal asymptotes: lines the curve approaches but never touches.
- , because and . Zero score means “undecided”.
- Always increasing. Bigger makes smaller, so is bigger.
- Symmetry: . Check with : and , and . Proof: . Multiply top and bottom by to get , and that is . In words: the curve is balanced around the point . Flip it left-to-right and the result is the same as flipping it upside-down about the height 0.5.
The sigmoid as a probability, and the logit
Because the output is in , we can read it as a probability: means “88% likely”. The input is called the logit (or log-odds) when used this way. The reason is below.
If an event has probability , its odds are . For the odds are (“4 to 1”). The logit is the natural log of the odds:
The logit undoes the sigmoid. Start from and solve for : , so , so , so . Numerically: gives , and . So turns a score into a probability, and the logit turns the probability back into the score. Equal odds () give logit , which matches .
tanh: the zero-centred cousin
The hyperbolic tangent, written , is another S-curve:
- Range : when is large, is tiny and the fraction is about . When is very negative, it is about .
- : the top is . It is zero-centred: its outputs are centred on 0, not on 0.5. One reason often given for preferring it over the sigmoid in hidden layers is that outputs centred on 0 are easier for the next layer to work with (more in P4.4).
- Odd function: . The graph is unchanged if you rotate it half a turn about the origin. (Swap in the formula: the top changes sign, the bottom stays the same.)
tanh is a transformed sigmoid
From P1.A1: you can build new curves by shifting and stretching old ones. It turns out
Derivation: . Multiply top and bottom by and you get . That is .
Read it with the rules of P1.A1: the inside squeezes the curve sideways by a factor 2; the outside stretches it twice as tall (range ); the outside moves it down (range ). Number check: , so . So tanh and sigmoid are not unrelated: they are the same S-curve in different clothes.
Play with the curves
Drag the input along the curves. Watch the outputs, and watch the orange slope line. It shows how steeply the chosen curve is rising at ; we will explain the number next. Turn on the other curves to compare.
Things to try: put at 0, then at 2, then at 5, and watch the orange slope shrink. Switch the slope line from sigmoid to tanh. Then drag to .
Saturation: where the curve goes flat
Look at the table again. Going from to changes from 0.8808 to 0.9820, a gain of 0.10. Going from to changes it from 0.9820 to 0.9975, a gain of only 0.016. The curve is flattening out. This flattening is called saturation: for large the output is “full” and hardly reacts to a change in the input. It is the same at the left end ( gives 0.0025, nearly 0).
Measuring steepness with numbers (no calculus yet)
How do we say “how steep” with a number? Use the idea of slope you know from straight lines: rise over run. For a curve we use a tiny run. The local slope of at is about
(“how much does the output change, per unit of input, if I nudge the input by 0.01?”). The widget shows this in orange. Some values:
| slope | slope | |
|---|---|---|
| 0 | 0.250 | 1.000 |
| 1 | 0.196 | 0.417 |
| 2 | 0.105 | 0.070 |
| 4 | 0.018 | 0.001 |
| 6 | 0.0025 | 0.000 |
(Rounded. The exact slopes at and at are the same, because both curves are symmetric: the left half is the right half turned around. The measured slopes differ slightly in the third or fourth decimal, because the measuring step only looks to the right.) Two facts to remember:
- The slope is largest at : for the sigmoid and for tanh. (tanh is steeper because of the stretch in .)
- The slope is nearly 0 far from 0, for both curves, and for tanh it falls faster.
This is the heart of saturation: where the slope is near 0, the output barely responds to the input, and (as you will see in calculus) learning signals that flow through such a spot are cut down too.
A first look at why this matters for training
In a neural network, training adjusts a weight by looking at how much the final output changes when that weight changes. If the signal passes through a saturated sigmoid, it is multiplied by a slope of about (at ). Even in the best case (the slope at ), each sigmoid layer multiplies the signal by at most . Stack 5 layers and the factor is ; stack 10 and it is . (This is a simplified picture that ignores the weights; the full story, with the chain rule, is in P1.C3, and the effect itself is the vanishing gradient problem of P4.16.) Part of why modern networks use other activations, such as ReLU, is to avoid this (P4.4).
The exact slope of a curve is the derivative, and measuring it with numbers is the first step to the idea of P1.C1: shrink the 0.01 towards 0.
Other squashing and S-shaped functions
Sigmoid and tanh are the stars, but you will meet several relatives. All of these map every real number to a bounded range:
| Name | Formula | Range | Notes |
|---|---|---|---|
| step | if , else | A hard yes/no. The value at exactly is a convention (0, 0.5 or 1). Slope is 0 everywhere except a jump. | |
| hard sigmoid | A cheap straight-line version of that reaches 0 and 1 exactly. Definitions vary between libraries (the slope here is the one in PyTorch; some older libraries use 0.2). | ||
| softsign | Like tanh, but it approaches slowly: gives 0.909, while . | ||
| scaled arctan | Another slow-approaching S-curve; gives 0.937. |
(Check at : softsign , scaled arctan , .) Turn them on in the widget above to compare. The step is the odd one out: it has no “in-between”, and its slope is 0 almost everywhere, which gives a learning method based on slopes nothing to work with. That is why smooth curves like replaced it in neural networks.
The step as a limit of the sigmoid
Multiply the input by a big number : . Take :
| 1 | 5 | 20 | 100 | |
|---|---|---|---|---|
| 0.622 | 0.924 | 0.99995 | 1.000 (to 3 decimals) |
As grows the S gets steeper and steeper, and in the limit it becomes the step for every . (At it stays exactly 0.5 for every .) So the step is the “infinitely steep” sigmoid. You can try this with the slider below.
Softmax: the sigmoid for many classes
A sigmoid turns one score into a probability of “yes” versus “no”. For more than two classes, softmax (P3.A8) turns a list of scores into probabilities that sum to 1: . With two classes it is just a sigmoid of the score difference:
(Divide top and bottom by .) Check with : and .
Stretch and shift: σ(a·z + b)
In models the sigmoid is almost never applied to a bare . It is applied to a linear score : a multiplier and an offset (these are a weight and a bias in P3.A7). By the rules of P1.A1 these are transformations inside the function:
- changes the steepness: a large squeezes the S sideways; a negative mirrors it (recall ).
- moves the curve left or right (inside changes act backwards): with .
- The curve crosses the height 0.5 exactly where the input of is 0: , i.e. .
Worked example: . The crossing is at . Check: . Also and . Make the curve steeper with a larger and the crossing stays at if is scaled along with it.
Notice: the slope at the crossing is about (the plain sigmoid has , and stretching sideways by multiplies the steepness by ). With the slope is 1. And is a decision point: for logistic regression it is where the model switches from “more likely no” to “more likely yes” (P3.A7).
Numbers in code: overflow and the stable form
Here is the sigmoid as code, straight from the formula:
def sigmoid_naive(z):
return 1 / (1 + np.exp(-z))
Problem: is enormous when is very negative, and a computer number has a limit. In standard double precision, math.exp(709) works (about ) but math.exp(1000) raises OverflowError. NumPy does not raise: np.exp(1000) gives inf with a RuntimeWarning. For the naive sigmoid at , that gives , which happens to be the right answer, but with a warning (and with Python’s math module it would crash). Warnings and infinities cause real trouble when they flow into the next calculation (this is previewed in P1.G2).
The fix is to never compute the exponential of a large positive number. Use two equal forms:
They are equal: multiply the top and bottom of the first by . In both branches the exponent is , so and nothing overflows. This is the stable version, and it is how libraries do it.
One more fact that surprises people: in floating point, is exactly 1.0 for whole numbers (the rounding to 1.0 starts between and ), because is too small to change . So the “never reaches 1” rule is a statement about real numbers, not about computers. This matters when you take later (P1.G2, P3.A7).
Try it in Python
Run the cell: it builds sigmoid and tanh, checks the identities numerically, measures slopes, and shows the overflow and the stable version. Then change the numbers.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Challenge: change at to and check that the slope matches to two decimals (symmetry; the measured slopes differ a little after that, because the step only looks to the right). Then find the smallest whole number for which sigmoid(z) == 1.0.
Intuition
A squashing function is a soft switch. Far to the left it says “off” (about 0), far to the right it says “on” (about 1), and near 0 it blends between the two. The steepness controls how sudden the switch is; the shift controls where it flips. The flat ends are what make the output bounded, and also what makes the output insensitive there (saturation). Where the picture breaks: a real switch is exactly on or off; a sigmoid never quite is.
Math
Limits: as and as ; . For a score with , the crossing of 0.5 is at . Two classes of softmax: .
Code
import numpy as np
def sigmoid(z): # stable form
z = np.asarray(z, dtype=float)
e = np.exp(-np.abs(z)) # exponent is never positive
return np.where(z >= 0, 1 / (1 + e), e / (1 + e))
sigmoid(0.0) # 0.5
np.tanh(1.0) # 0.7616 = 2*sigmoid(2) - 1
sigmoid(-1000.0) # 0.0, no warningGo deeper Preview: the exact slope of σ and tanh
In calculus (P1.C1 to P1.C3) you will show that the slope of the sigmoid at has a neat closed form, , and for tanh it is . You do not need to prove them now: just check them against the numbers above.
- At : and . These match the measured slopes and .
- At : (measured ), and (measured ).
The measured numbers are very slightly lower because a step of 0.01 is not infinitely small and the curve bends. This also explains why the largest slope of is : the product is largest when , where it equals .
Go deeper Why the logistic curve, and where tanh shows up
The sigmoid is exactly the curve that turns log-odds into a probability. If a model assumes the log-odds of “yes” is a linear score , then the probability is : that is logistic regression (P3.A7). The LSTM (P6.7) uses sigmoids for gates, numbers between 0 and 1 that multiply a signal to let a fraction of it through, and tanh to produce candidate values between and .
Exercises
- Compute and and check that they add up to 1.
Show answer
and . Sum (by ). - A model says the probability of rain is . What logit (score) does that correspond to?
Show answer
. Check: . - Use and the identity to compute .
Show answer
(more exactly with ). - Where does cross 0.5? What are its values at and ?
Show answer
. At : . At : . - A stack of 10 sigmoid layers, each with its best-case slope . By what factor (at most) does the signal shrink in this simplified picture?
Show answer
, less than one millionth. (Simplified: ignores the weights.) - A two-class softmax has scores . What is the probability of class 2?
Show answer
. Directly: . Class 1 gets . - In floating point, is equal to 1? Is it mathematically? And is equal to 0 in floating point?
Show answer
In float64, rounds to exactly 1.0, and . Mathematically always: . This is why stable code computes rather than when the small number matters. - The hard sigmoid at gives what, and how close is it to ?
Show answer
, versus . About apart. - Which of these is not a squashing function: softsign, , ReLU, step?
Show answer
ReLU: its outputs are unbounded above. The other three are bounded (softsign and arctan in , step in ). - Why does a naive risk trouble for in Python’s
mathmodule?Show answer
is bigger than the largest double (), somath.exp(1000)raisesOverflowError. NumPy returnsinfwith a warning instead. The stable form uses for negative , where is tiny.
Quiz
Check your understanding
What values can the sigmoid output (mathematically, as real numbers)?
Since , the denominator is strictly greater than 1, so the output is strictly between 0 and 1. It approaches 0 and 1 but never reaches them (in floating-point code it can round to exactly 1.0).
If , what is ?
Symmetry: , so .
Using and , what is ?
Put : .
Why can deep stacks of sigmoid or tanh layers learn slowly?
This is saturation. A near-zero slope means a change in the input barely changes the output, and learning signals passing through are shrunk (P4.16). The curves remain increasing and defined everywhere, and they never output exactly 0 or 1 mathematically.
Which of these is a squashing function (it maps every real number into a bounded range)?
Softsign always lies strictly between −1 and 1. ReLU, and all grow without bound for large positive .
Putting it together
A squashing function turns any real number into a bounded output. The sigmoid lives in , equals 0.5 at 0, satisfies , and is read as a probability; its inverse is the logit . tanh lives in and is . Both saturate: far from 0 the curve is flat, and the slope, which is largest at 0 (0.25 and 1), is nearly 0. crosses 0.5 at , and a huge gives a step. Softmax with two classes is a sigmoid. In code, use the stable form to avoid overflow.
Where next. You have measured steepness with a tiny step of 0.01. Calculus (P1.C1) turns this into an exact tool: the derivative is what you get as the step shrinks to zero, and the chain rule (P1.C3) explains how slopes multiply through layers. Then the sigmoid appears as the output of logistic regression (P3.A7) and as an activation in neural networks (P4.4).