AI Wiki中文/EN

Activation functions

激活函数

Connect nonlinear representations to derivative conventions, stable sigmoid/GELU/SiLU computation, and the second moments behind rectifier initialization.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two small bends can represent XOR

A linear score cannot strictly separate the raw XOR inputs: (0,0)(0,0) and (1,1)(1,1) belong together, while (0,1)(0,1) and (1,0)(1,0) belong to the other class. Adding another affine layer alone will not help. For column vectors, two such layers collapse to

W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2).W_2(W_1x+b_1)+b_2=(W_2W_1)x+(W_2b_1+b_2).

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 ReLU⁡(z)=max⁡(0,z)\operatorname{ReLU}(z)=\max(0,z). Construct two hidden units, h1=ReLU⁡(x1+x2)h_1=\operatorname{ReLU}(x_1+x_2) and h2=ReLU⁡(x1+x2−1)h_2=\operatorname{ReLU}(x_1+x_2-1), followed by output h1−2h2h_1-2h_2. On the four Boolean inputs, the outputs are 0,1,1,00,1,1,0: 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 z=Wx+bz=Wx+b, producing h=f(z)h=f(z). 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 σ(x)=1/(1+e−x)\sigma(x)=1/(1+e^{-x}) for the logistic sigmoid, Φ\Phi for the standard normal CDF, and ϕ(x)=e−x2/2/2π\phi(x)=e^{-x^2/2}/\sqrt{2\pi} for its density.

FunctionValueDerivative away from corners
Sigmoidσ(x)\sigma(x)σ(x)(1−σ(x))\sigma(x)(1-\sigma(x))
Tanhtanh⁡(x)\tanh(x)1−tanh⁡2(x)1-\tanh^2(x)
ReLUmax⁡(0,x)\max(0,x)0 for x<0x<0; 1 for x>0x>0
Fixed leaky ReLUxx for x≥0x\ge0; axax for x<0x<01 for x>0x>0; aa for x<0x<0
SiLUxσ(x)x\sigma(x)σ(x)+xσ(x)(1−σ(x))\sigma(x)+x\sigma(x)(1-\sigma(x))
Standard GELUxΦ(x)x\Phi(x)Φ(x)+xϕ(x)\Phi(x)+x\phi(x)

For the leaky function here, 0<a<10<a<1 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 Φ′=ϕ\Phi'=\phi. 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 [0,1][0,1], not a claim that the missing ordinary derivative equals zero. For fixed leaky ReLU, the program chooses the left derivative aa 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 1/21/2 at the origin, but they are different functions. At x=1x=1, GELU is approximately 0.841345 and SiLU approximately 0.731059. The standard GELU definition is xΦ(x)x\Phi(x); Hendrycks and Gimpel, Section 2 also gives the often-used approximation

GELU⁡(x)≈x2[1+tanh⁡ ⁣(2π(x+0.044715x3))].\operatorname{GELU}(x)\approx\frac x2\left[1+\tanh\!\left(\sqrt{\frac2\pi}(x+0.044715x^3)\right)\right].

A second approximation is xσ(1.702x)x\sigma(1.702x). 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 xσ(βx)x\sigma(\beta x), with fixed or learned β\beta. It equals SiLU at β=1\beta=1 and the linear function x/2x/2 at β=0\beta=0. Its derivative is σ(βx)+βxσ(βx)(1−σ(βx))\sigma(\beta x)+\beta x\sigma(\beta x)(1-\sigma(\beta x)). 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 σ(x)σ(−x)\sigma(x)\sigma(-x), avoiding early cancellation in 1−σ(x)1-\sigma(x). For tanh, an equivalent derivative formula based on e−2∣x∣e^{-2|x|} avoids subtracting a rounded value of one. The normal CDF is computed as erfc⁡(−x/2)/2\operatorname{erfc}(-x/\sqrt2)/2, which avoids the negative-tail subtraction in 1+erf⁡(x/2)1+\operatorname{erf}(x/\sqrt2).

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 QQ values takes O(Q)O(Q) scalar operations and O(Q)O(Q) 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 1/21/2, while this program’s backward convention is zero. Even graph-level conventions need care. The expression ReLU⁡(x)−ReLU⁡(−x)\operatorname{ReLU}(x)-\operatorname{ReLU}(-x) equals xx, 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 (0,1)(0,1) in exact arithmetic and its derivative is at most 1/41/4. Tanh outputs lie in (−1,1)(-1,1), with derivative at most 1. Both become locally flat at large absolute inputs. Along a scalar chain of LL sigmoid units with unit weights, the derivative product is at most 4−L4^{-L}. 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 x=−2x=-2 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 ZZ symmetric about zero with finite second moment qq, set H=ReLU⁡(Z)H=\operatorname{ReLU}(Z). Then

E[H2]=q2,Var⁡(H)=q2−(E[H])2.E[H^2]=\frac q2,\qquad\operatorname{Var}(H)=\frac q2-(E[H])^2.

The second moment halves; the variance generally does not. For equally likely Z∈{−3,−2,−1,1,2,3}Z\in\{-3,-2,-1,1,2,3\}, the input second moment is 14/314/3, while E[H]=1E[H]=1, E[H2]=7/3E[H^2]=7/3 and Var⁡(H)=4/3\operatorname{Var}(H)=4/3.

With mm inputs and independent zero-mean initial weights of the same variance, independent of those inputs, the next preactivation variance is mVar⁡(W)E[H2]m\operatorname{Var}(W)E[H^2] when the input second moments are equal. With symmetric preactivations and zero biases, this becomes mVar⁡(W)q/2m\operatorname{Var}(W)q/2. Keeping this scale equal to qq motivates

Var⁡(W)=2m,sd⁡(W)=2m.\operatorname{Var}(W)=\frac2m,\qquad\operatorname{sd}(W)=\sqrt{\frac2m}.

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 aa changes the factor 1/21/2 to (1+a2)/2(1+a^2)/2. GELU and SiLU do not have the same constant factor at every input scale.

Predict a bend, a slope and a moment

  1. 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.
  2. Evaluate the constructed XOR network at (1,1)(1,1). Answer: the hidden values are 2 and 1, and the output is 2−2(1)=02-2(1)=0. A single affine score cannot produce the same strict separation on all four XOR points.
  3. SiLU and GELU both have derivative 1/21/2 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.
  4. For the six-point symmetric distribution above, is the ReLU output variance 7/37/3? Answer: no. That is its second moment. Its mean is 1, so the variance is 7/3−1=4/37/3-1=4/3.

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?

Choose one answer

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

  1. Dive into Deep Learning — 5.1 Multilayer Perceptrons
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023
  2. Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
    Kaiming He; Xiangyu Zhang; Shaoqing Ren; Jian Sun · 2015
  3. Gaussian Error Linear Units (GELUs)
    Dan Hendrycks; Kevin Gimpel · 2016
  4. Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning
    Stefan Elfwing; Eiji Uchibe; Kenji Doya · 2017
  5. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.