Activation functions
激活函数
Connect nonlinear representations to derivative conventions, stable sigmoid/GELU/SiLU computation, and the second moments behind rectifier initialization.
activation-functionsTwo small bends can represent XOR
A linear score cannot strictly separate the raw XOR inputs: and belong together, while and belong to the other class. Adding another affine layer alone will not help. For column vectors, two such layers collapse to
The result is still affine. A narrow hidden layer may even restrict the rank of the resulting matrix. Extra parameters do not automatically create a richer function class.
Now introduce . Construct two hidden units, and , followed by output . On the four Boolean inputs, the outputs are : exactly XOR. The bends make a difference that another affine layer cannot. These are hand-chosen weights, not evidence that a particular training run will find them. D2L, Section 5.1.1.3 derives the affine collapse and the role of a nonlinear hidden transformation.
An activation function acts on the preactivation , producing . The weighted sum and bias belong to the preceding affine operation. The function need not merely switch a neuron on or off: it can produce a graded, negative or unbounded value.
Compare values and derivatives separately
The following functions act independently on each scalar input. Write for the logistic sigmoid, for the standard normal CDF, and for its density.
| Function | Value | Derivative away from corners |
|---|---|---|
| Sigmoid | ||
| Tanh | ||
| ReLU | 0 for ; 1 for | |
| Fixed leaky ReLU | for ; for | 1 for ; for |
| SiLU | ||
| Standard GELU |
For the leaky function here, is fixed. PReLU instead learns its negative-side slope as a model parameter. The sigmoid derivative follows by differentiating its reciprocal expression; the last two rows follow directly from the product rule and . D2L, Section 5.1.2 develops the first four families. Elfwing, Uchibe and Doya, equations 9–11 give SiLU and its derivative; their dSiLU is an additional activation that uses that derivative as its forward function.
ReLU has left derivative 0 and right derivative 1 at zero, so it has no ordinary derivative there. A program still needs a backward rule. Our implementation chooses zero. This is one element of the convex ReLU subgradient interval , not a claim that the missing ordinary derivative equals zero. For fixed leaky ReLU, the program chooses the left derivative at zero. Exact zeros can occur through initialization, quantization or cancellation; a measure-zero argument does not make them impossible in a computer.
GELU and SiLU have the same value zero and derivative at the origin, but they are different functions. At , GELU is approximately 0.841345 and SiLU approximately 0.731059. The standard GELU definition is ; Hendrycks and Gimpel, Section 2 also gives the often-used approximation
A second approximation is . Neither is an exact identity. If a program uses an approximation, its backward calculation should differentiate that approximation. The paper motivates GELU using the expectation of a random input-dependent mask; the usual activation itself is deterministic.
Swish is the family , with fixed or learned . It equals SiLU at and the linear function at . Its derivative is . Ramachandran, Zoph and Le, Section 4 makes this parameter distinction explicit. Similar plots do not justify silently replacing one definition with another.
Return the value and the selected backward value
This complete standard-library program implements six named choices. It uses a branched sigmoid and evaluates its derivative as , avoiding early cancellation in . For tanh, an equivalent derivative formula based on avoids subtracting a rounded value of one. The normal CDF is computed as , which avoids the negative-tail subtraction in .
import math
def activation(x,name,alpha=.1):
x = float(x)
if not math.isfinite(x):
raise ValueError("finite input required")
def sigmoid(z):
if z >= 0:
return 1/(1+math.exp(-z))
e = math.exp(z)
return e/(1+e)
if name == "relu":
return max(0.0,x),float(x>0) # chosen backward value 0 at x=0
if name == "leaky":
if not math.isfinite(alpha) or not 0 < alpha < 1:
raise ValueError("this example uses a fixed 0 < alpha < 1")
return (x,1.0) if x>0 else (alpha*x,alpha)
if name == "sigmoid":
p,q = sigmoid(x),sigmoid(-x)
return p,p*q
if name == "tanh":
e = math.exp(-2*abs(x))
return math.tanh(x),4*e/(1+e)**2
if name == "silu":
p,q = sigmoid(x),sigmoid(-x)
return x*p,p+x*(p*q)
if name == "gelu":
cdf = .5*math.erfc(-x/math.sqrt(2))
density = math.exp(-.5*x*x)/math.sqrt(2*math.pi)
return x*cdf,cdf+x*density
raise ValueError("unknown activation")
assert activation(0,"sigmoid") == (.5,.25)
assert activation(0,"tanh") == (0,1)
assert activation(0,"relu") == (0,0)
assert activation(0,"silu") == (0,.5)
assert activation(0,"gelu") == (0,.5)
assert math.isclose(activation(1,"gelu")[0],.8413447460685429)
assert math.isclose(activation(1,"silu")[0],.7310585786300049)
for name in ("relu","leaky","sigmoid","tanh","silu","gelu"):
for x in (-1000,1000):
assert all(math.isfinite(v) for v in activation(x,name))
# Constructed hidden units: these weights have not been learned.
for x1,x2,target in ((0,0,0),(0,1,1),(1,0,1),(1,1,0)):
h1 = activation(x1+x2,"relu")[0]
h2 = activation(x1+x2-1,"relu")[0]
assert h1-2*h2 == target
The pair returned by activation contains a forward value and the chosen scalar backward value. The special cases at zero are deliberate. The implementation evaluates the standard CDF definition of GELU, rather than the tanh approximation; erfc is still a floating-point library function, not exact real arithmetic. Extreme tails can underflow to zero even though the mathematical quantity is nonzero. Stable formulas remove avoidable overflow without removing the finite range of the number format.
Applying a scalar activation to values takes scalar operations and storage if both output arrays are retained. Exponential and special-function costs differ from a simple comparison. This count is separate from the cost of the preceding matrix multiplication.
To check a smooth derivative, compare it with a centered finite difference at moderate inputs. Do not cross a ReLU corner and then treat the resulting secant as its ordinary derivative: the symmetric difference at zero returns , while this program’s backward convention is zero. Even graph-level conventions need care. The expression equals , yet choosing zero at both component corners gives a backward value zero there, whereas the complete function has derivative one. A rule for a nondifferentiable component is not a proof about every possible composition.
Gradient size also depends on weights and input scale
Sigmoid outputs lie in in exact arithmetic and its derivative is at most . Tanh outputs lie in , with derivative at most 1. Both become locally flat at large absolute inputs. Along a scalar chain of sigmoid units with unit weights, the derivative product is at most . A general network also contains weight matrices, sums over paths and possibly skip connections; activation derivatives alone do not determine its complete gradient.
ReLU avoids positive-side saturation, but gives zero derivative on the negative side. A unit whose preactivation is negative for every current training example receives no input-parameter gradient from that task loss through this path. Changes in earlier layers, momentum or other updates can still alter its state. Leaky variants change that local behavior, without guaranteeing successful learning. SiLU and GELU are nonmonotonic: at their derivatives are negative, while GELU at 1 and SiLU at 2 have derivatives above one. Smoothness is not the same as a positive derivative bounded by one.
Initialization must account for the activation. For a random variable symmetric about zero with finite second moment , set . Then
The second moment halves; the variance generally does not. For equally likely , the input second moment is , while , and .
With inputs and independent zero-mean initial weights of the same variance, independent of those inputs, the next preactivation variance is when the input second moments are equal. With symmetric preactivations and zero biases, this becomes . Keeping this scale equal to motivates
He and colleagues, Section 2.2, equations 9–12 explicitly distinguish the second moment from variance. This reasoning concerns initial moment propagation across rectifier layers; it is not a training-convergence guarantee. A fixed negative slope changes the factor to . GELU and SiLU do not have the same constant factor at every input scale.
Predict a bend, a slope and a moment
- Why does the ReLU backward value zero at the origin not follow from ordinary differentiation? Answer: the left and right derivatives are 0 and 1, so an ordinary derivative does not exist. Zero is an explicit computational choice.
- Evaluate the constructed XOR network at . Answer: the hidden values are 2 and 1, and the output is . A single affine score cannot produce the same strict separation on all four XOR points.
- SiLU and GELU both have derivative at zero. Are they identical? Answer: no. At input 1 their values are approximately 0.731059 and 0.841345 respectively; one uses the logistic CDF and the other the standard normal CDF.
- For the six-point symmetric distribution above, is the ReLU output variance ? Answer: no. That is its second moment. Its mean is 1, so the variance is .
Treat the activation as one part of the model
A change of activation changes the represented functions and the derivatives used to learn them. Comparing alternatives therefore requires the same data split, a stated architecture, a suitable initialization and a clear tuning budget. A numerical check of one function does not reproduce an entire paper’s training experiment.
Choose output transformations according to what the output means: an unrestricted real number, a binary probability or a vector of mutually exclusive class probabilities impose different requirements. Softmax couples coordinates, unlike the scalar functions here. For hidden layers, investigate interactions with normalization, residual connections and optimization. The useful question is how a specified change behaves in a specified model, not which curve has a universally best shape.
Make a prediction, then check
For the article’s symmetric six-point input, ReLU output has mean1 and second moment7/3. What is its variance?
Learning objectives
- Explain how nonlinearity changes representation and distinguish values, ordinary derivatives and backward conventions at corners.
- Stably compute six activations and derive rectifier initialization scale from second moments rather than variance.
Prerequisites & connections
Explore related knowledge →References
- Dive into Deep Learning — 5.1 Multilayer Perceptrons
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023 - Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
Kaiming He; Xiangyu Zhang; Shaoqing Ren; Jian Sun · 2015 - Gaussian Error Linear Units (GELUs)
Dan Hendrycks; Kevin Gimpel · 2016 - Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning
Stefan Elfwing; Eiji Uchibe; Kenji Doya · 2017 - Searching for Activation Functions
Prajit Ramachandran; Barret Zoph; Quoc V. Le · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: source locations, independent numerical verification and full bilingual rereading; some drafts by an agent reviewed by the parent; no independent human peer review.
- Parent ran48 noncorner differences,7 Gaussian integrals,4001 GELU-approximation points, one-sided zero slopes, nonmonotonicity and extreme inputs; finite grids are not global error proofs.
- Constructed XOR, affine composition, six-point moments and independent two-input weight enumeration passed; parent compared complete bilingual definitions, derivatives, equations and four answers.
- The parent executed all19 independent learning-theory/neural tests. Structure checks compare bilingual anchors,display equations,code and sources; parent reread four answers and arguments. Historical articles make no code-execution claim.
Source locations checked:
- Dive into Deep Learning — 5.1 Multilayer Perceptrons · Writing agent read1.0.3 §§5.1.1.3 and5.1.2: affine collapse, nonlinearities and zero conventions. Parent verified all definitions and derivatives in both articles; did not adopt an unrestricted universal-approximation claim.
- Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification · Agent read conference PDF2 §2.1; PDF4–5 §2.2 equations7–16 and leaky factor. Second moment is distinguished from variance; parent independently checked six-point moments and exact joint weight enumeration.
- Gaussian Error Linear Units (GELUs) · Agent readv5 PDF1–2 §2 and PDF6 discussion; standardxΦ(x), deterministic expectation and tanh/logistic approximations. Parent independently ran Gaussian-integral comparison and derivatives.
- Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning · Agent readv3 PDF3–5 §2.2 equations6–12; SiLU versus dSiLU and derivative. Parent checked nonmonotonicity and gradients exceeding1.
- Searching for Activation Functions · Agent readv2 PDF5 §4 definition and derivative, PDF7 GELU comparison. Parent differentiatedxσ(βx), retaining β=1 as the equality condition.
Related topics