Skip to main content
LearnMLAcademy
Advanced10 min read

Activation Functions

Compare non-linear activation functions including ReLU, LeakyReLU, and GeLU, with tensor walkthroughs, gradient calculations, and PyTorch practice.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Deep Learning · Beginner Lesson

Activation Functions: From a Neuron’s Score to Its Output

An activation function is a mathematical rule that changes a neuron’s raw score into the value it sends forward. In this lesson, you will calculate that value by hand, locate it on a graph, and learn which rule fits hidden layers, yes-or-no predictions, multiple classes, and number predictions.

What Is an Activation Function?

A neuron first multiplies its inputs by weights, adds those results, and adds a bias. This produces one raw number called the weighted sum, usually written as z. An activation function then changes z into the signal the neuron sends onward.

z = (inputs × weights) + bias   →   output = activation(z)

You can think of it as a signal shaper. Depending on the chosen function, it may block a value, keep it, smooth it into a probability-like number, or compare it with other class scores.

x or z

The raw number entering the activation function. In a neuron this is normally the weighted sum plus bias.

g(x), f(x) or a

The value produced by the function. This becomes the neuron’s outgoing signal.

Where the activation function sits inside a neuronInputs are multiplied by weights, bias is added, and the resulting weighted sum passes through an activation function to become the neuron output.x₁w1x₂w2x₃w3Σ + bweighted sumcall this zACTIVATIONa = g(z)changes z into a signaloutputainputsweightsThe activation function works here—after the weighted sum.
Figure 1: The exact position of an activation function inside one artificial neuron.

A useful correction: an activation function does not literally decide whether information is “important.” It applies the same mathematical rule to every input. Training changes the weights so useful signals tend to reach the function in useful forms.

Why Do We Need to Study Activation Functions?

The activation function is not a decorative formula. It changes both what a network can learn and how easily the network can learn it.

1

Learn complex patterns

Without a non-linear activation, even a network with many layers collapses into one linear calculation. It cannot build the curved boundaries needed for images, speech, language, and many real-life patterns.

2

Control the signal

An activation decides the form of the outgoing signal: blocked or passed, bounded between −1 and 1, converted to a probability, or left as an unrestricted number.

3

Make training possible

Backpropagation needs useful slopes called gradients. A function with flat regions can slow learning; a function with a useful slope can let error information travel through more layers.

4

Match the prediction

Different outputs need different shapes. Yes/no predictions, one-of-many classes, and continuous numbers should not all use the same output activation.

The two questions to ask about every activation

Forward pass: What output does this function produce from an input?

Learning: What gradient does it send backward when the model makes a mistake?

Learn With a Simple Example: The Smart Security Light

Imagine a light that should turn on for a person at night, but stay off for a moving leaf or a small insect. The sensor sees several clues; the neuron combines them; the activation function shapes the final response.

Signals coming in

Motion + object size + darkness

The sensor combines several readings into one score. A person at night may create a strong positive score; a leaf may create a weak or negative score.

→

Activation changes the score

Step: OFF or ON

Sigmoid: chance of a person

ReLU: strength above zero

Step 1

Read the clues

Motion = strong, object size = large, darkness = high.

Step 2

Combine them

After weights and bias, suppose the neuron produces z = 2.

Step 3

Apply a function

Step gives 1; sigmoid gives 0.88; ReLU gives 2.

Result

Interpret the output

Step says ON, sigmoid says 88% confidence, ReLU preserves signal strength 2.

The input score is identical, but each function answers a different question. That is why there is no single activation function that is best everywhere.

Why Non-Linearity Matters

A linear rule can draw only a straight decision boundary. Stacking many linear layers does not solve this: their calculations combine into another linear rule. Many real patterns need bends, corners, separate regions, or much more complicated boundaries.

Only linear layers

One straight line cannot separate both groups.

Layers with non-linear activations

Several pieces can form a non-linear boundary.

This ability is essential for patterns in pictures, speech, language, sensor readings, and other complex data. Non-linearity is not magic—it simply gives the network building blocks more flexible than straight lines.

How the Main Activation-Function Families Differ

The names are easier to remember when they are grouped by the job they perform.

Hard decision

Step

Produces an immediate 0 or 1. Useful for intuition, not normal gradient training.

Bounded S-curves

Sigmoid · Tanh

Compress huge inputs into a small range. Helpful when a bounded output has meaning.

ReLU family

ReLU · Leaky ReLU · PReLU

Keeps the positive side simple and changes what happens to negative inputs.

Exponential family

ELU · SELU · Softplus

Uses smooth curves to preserve gradients or control the distribution of activations.

Modern smooth gates

GELU · SiLU / Swish

Softly scales inputs instead of making a hard cutoff; common in newer architectures.

Output specialists

Linear · Sigmoid · Softmax

Chosen according to whether the final answer is a number, a yes/no probability, or one class among many.

The Main Activation Functions, One by One

1

Step Function

The strict switch

Formula

g(x) = 0 if x < 0; otherwise 1

How to read it: Compare x with zero. A negative x returns 0; zero or a positive x returns 1. The symbol g(x) means the output produced from x.

00.51-505input xoutput g(x)1 (ON)0 (OFF)(-2, 0)Graph of g(x) = 0 if x < 0; otherwise 1

What it is

The simplest yes/no rule. It jumps from 0 to 1 at a chosen threshold.

Why we use it

It turns a score into a clear binary decision and provides the easiest starting point for understanding a neuron’s firing idea.

How it behaves

Values below the threshold produce 0; values at or above it produce 1. There is no smooth transition.

Where to use it

Use it to understand the history and intuition of a firing threshold, or for a fixed rule outside training.

Watch out

Modern neural networks are not normally trained with it. Its derivative is zero almost everywhere and undefined at the jump, so gradient-based learning gets no useful direction.

Solved mathematical example

Put x = -2 into the formula and calculate the output:

g(−2) = 0, because −2 < 0

Graph connection: the highlighted dot is the coordinate (-2, 0). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: A simple thermostat can switch a fan OFF below 30°C and ON at or above 30°C. The rule is useful, but it cannot express a gradual fan speed.

Input x−2−0.102
Output g(x)0011
2

Sigmoid Function

The smooth yes/no output

Formula

σ(x) = 1 / (1 + e⁻ˣ)

How to read it: e is Euler’s number, approximately 2.718. The negative exponent makes large positive inputs approach 1 and large negative inputs approach 0.

00.51-505input xoutput g(x)10(2, 0.881)Graph of σ(x) = 1 / (1 + e⁻ˣ)

What it is

A smooth S-shaped function that maps every real number to a value strictly between 0 and 1.

Why we use it

It converts an unrestricted score into an easy-to-read probability-like value while keeping the transition differentiable for learning.

How it behaves

Large negative inputs move close to 0, zero becomes 0.5, and large positive inputs move close to 1.

Where to use it

Usually use one sigmoid output for binary or independent multi-label predictions—for example, spam versus not spam.

Watch out

At very negative or positive inputs, the curve becomes flat. Gradients become tiny there, which can slow learning when sigmoid is repeated through deep hidden layers.

Solved mathematical example

Put x = 2 into the formula and calculate the output:

σ(2) = 1 / (1 + e⁻²) = 1 / (1 + 0.1353) = 0.881

Graph connection: the highlighted dot is the coordinate (2, 0.881). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: An email model produces a raw spam score of 2.2. Sigmoid converts it to about 0.90, which can be read as strong confidence that the email is spam.

Input x−5−1015
Output g(x)0.0070.2690.5000.7310.993
3

Tanh Function

The balanced S-curve

Formula

tanh(x) = (eˣ − e⁻ˣ) / (eˣ + e⁻ˣ)

How to read it: The same exponential terms appear above and below the fraction. Their ratio keeps every output between −1 and +1.

-101-505input xoutput g(x)+1−1(1, 0.762)Graph of tanh(x) = (eˣ − e⁻ˣ) / (eˣ + e⁻ˣ)

What it is

Hyperbolic tangent is another smooth S-curve. Unlike sigmoid, its output is centered around zero.

Why we use it

Its negative, neutral, and positive outputs make it useful when the sign of a hidden state carries meaning and zero-centred signals are helpful.

How it behaves

Strong negative inputs approach −1, zero stays 0, and strong positive inputs approach +1.

Where to use it

Tanh remains common inside recurrent units and can suit hidden states where bounded, zero-centered signals are useful.

Watch out

Its ends are also flat, so it can suffer from vanishing gradients. ReLU-family functions are a more common first choice for ordinary deep feedforward hidden layers.

Solved mathematical example

Put x = 1 into the formula and calculate the output:

tanh(1) = (2.718 − 0.368) / (2.718 + 0.368) = 2.350 / 3.086 = 0.762

Graph connection: the highlighted dot is the coordinate (1, 0.762). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: A sentence-state unit can represent negative sentiment near −1, neutral sentiment near 0, and positive sentiment near +1.

Input x−3−1013
Output g(x)−0.995−0.76200.7620.995
4

ReLU — Rectified Linear Unit

The fast hidden-layer default

Formula

ReLU(x) = max(0, x)

How to read it: max(0, x) means choose whichever is larger: zero or x. Therefore negative inputs are replaced by zero and positive inputs pass unchanged.

024-505input xoutput g(x)positive: keep xnegative: 0(-3, 0)Graph of ReLU(x) = max(0, x)

What it is

ReLU returns 0 for a negative input and returns the input unchanged when it is positive.

Why we use it

It is simple to compute and its positive side does not flatten, so gradients can travel more effectively than through saturated sigmoid or tanh units.

How it behaves

Its positive side has a constant slope, which supports useful gradient flow and is cheap to calculate. Zero outputs also create sparse activations.

Where to use it

It is a strong starting choice for hidden layers in many dense and convolutional networks.

Watch out

A neuron that stays on the negative side can output 0 repeatedly and stop receiving a useful gradient. This is the dying-ReLU problem. ReLU reduces some vanishing-gradient difficulties; it does not guarantee that every deep model avoids them.

Solved mathematical example

Put x = -3 into the formula and calculate the output:

ReLU(−3) = max(0, −3) = 0

Graph connection: the highlighted dot is the coordinate (-3, 0). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: In an image network, one hidden neuron may measure how strongly an edge is present. A negative score becomes 0; a strong edge score such as 3.4 passes forward unchanged.

Input x−4−1014
Output g(x)00014

More Activation Functions You Will Meet

5

Linear / Identity Function

The unchanged numeric output

Formula

g(x) = x

How to read it: The output equals the input. No part of the number is blocked, squeezed, or curved.

-404-505input xoutput g(x)positivenegative(-2, -2)Graph of g(x) = x

What it is

The linear function returns exactly the number it receives. There is no squeezing, clipping, or curve.

Why we use it

Some predictions must remain unrestricted. A house price, temperature, or future demand may be any reasonable positive or negative number.

How it behaves

Input −3 becomes −3, input 0 becomes 0, and input 3 becomes 3. Its slope is always 1.

Where to use it

Use it mainly in the output layer of a regression model that predicts a continuous value.

Watch out

Do not use linear activations throughout hidden layers. Several linear layers combine into one linear calculation, so depth adds no ability to learn curved patterns.

Solved mathematical example

Put x = -2 into the formula and calculate the output:

g(−2) = −2

Graph connection: the highlighted dot is the coordinate (-2, -2). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: A model predicting tomorrow’s temperature should be allowed to output −4.2°C, 18.6°C, or 37.1°C rather than forcing the answer between 0 and 1.

Input x−2−1012
Output g(x)−2−1012
6

Leaky ReLU and PReLU

ReLU with a path for negative values

Formula

g(x) = x if x > 0; otherwise αx

How to read it: α (alpha) is the small negative-side slope. This lesson uses α = 0.01. PReLU differs because the model learns α during training.

024-505input xoutput g(x)positive: xnegative: αx(-2, -0.02)Graph of g(x) = x if x > 0; otherwise αx

What it is

Leaky ReLU keeps ReLU’s positive side but replaces the flat negative side with a small slope. PReLU is the same idea, except training learns the slope α.

Why we use it

The negative slope keeps a small gradient alive, which may revive units that would become permanently inactive under ordinary ReLU.

How it behaves

With α = 0.01, input −2 becomes −0.02 instead of 0. Positive values still pass through unchanged.

Where to use it

Try it when diagnostics show many ReLU units always output zero, or when an established architecture already uses it.

Watch out

It is not an automatic improvement over ReLU. A fixed or learned negative slope adds another design choice and should be validated on your data.

Solved mathematical example

Put x = -2 into the formula and calculate the output:

g(−2) = αx = 0.01 × (−2) = −0.02

Graph connection: the highlighted dot is the coordinate (-2, -0.02). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: An image feature detector with a negative score of −2 still sends a tiny signal of −0.02 backward and forward instead of becoming completely silent.

Input x−2−1012
Output g(x)−0.02−0.01012
7

ELU — Exponential Linear Unit

A smooth negative branch

Formula

ELU(x) = x if x > 0; otherwise α(eˣ − 1)

How to read it: Positive x passes unchanged. For negative x, the exponential branch bends smoothly toward −α. Here α = 1.

-1024-505input xoutput g(x)positive: xapproaches −α(-1, -0.632)Graph of ELU(x) = x if x > 0; otherwise α(eˣ − 1)

What it is

ELU behaves like ReLU for positive inputs, but uses a smooth exponential curve for negative inputs.

Why we use it

Negative outputs can keep activations closer to zero on average, while the smooth branch avoids a completely dead negative side.

How it behaves

With α = 1, positive inputs pass unchanged. Negative inputs bend smoothly and approach −1 without going below it.

Where to use it

Consider it for hidden layers when ReLU is unstable or dead units are a measured problem and extra computation is acceptable.

Watch out

The exponential calculation is slower than ReLU, and the best result still depends on initialization, normalization, and the dataset.

Solved mathematical example

Put x = -1 into the formula and calculate the output:

ELU(−1) = 1(e⁻¹ − 1) = 0.368 − 1 = −0.632

Graph connection: the highlighted dot is the coordinate (-1, -0.632). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: A sensor-feature neuron may pass strong positive evidence directly, while weak negative evidence is compressed smoothly rather than discarded.

Input x−3−1013
Output g(x)−0.950−0.632013
8

SELU — Scaled ELU

Built for self-normalizing networks

Formula

SELU(x) = λx if x > 0; otherwise λα(eˣ − 1)

How to read it: λ (lambda) scales both branches and α shapes the negative branch. Standard SELU uses λ ≈ 1.0507 and α ≈ 1.6733.

-1024-505input xoutput g(x)scaled positivescaled negative(1, 1.051)Graph of SELU(x) = λx if x > 0; otherwise λα(eˣ − 1)

What it is

SELU is a carefully scaled ELU with fixed constants. Under the right conditions, activations tend to move toward a stable mean and variance.

Why we use it

The self-normalizing effect can help deep fully connected networks keep signals from growing or shrinking too much.

How it behaves

It scales both branches: roughly 1.05x for positive values and a curved negative branch approaching about −1.76.

Where to use it

Use it in compatible dense self-normalizing networks with LeCun-normal initialization and AlphaDropout.

Watch out

Those conditions matter. Ordinary dropout, incompatible initialization, or some architectures can break the intended self-normalizing behavior.

Solved mathematical example

Put x = 1 into the formula and calculate the output:

SELU(1) = λx = 1.0507 × 1 = 1.0507 ≈ 1.051

Graph connection: the highlighted dot is the coordinate (1, 1.051). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: In a deep tabular network designed specifically for SELU, each layer can keep its activation scale steadier without adding batch normalization everywhere.

Input x−3−1013
Output g(x)−1.670−1.11101.0513.152
9

Softplus Function

A smooth version of ReLU

Formula

Softplus(x) = log(1 + eˣ)

How to read it: eˣ is always positive, so 1 + eˣ is positive and its natural logarithm is defined. The result stays above zero and changes smoothly.

024-505input xoutput g(x)positive and smoothapproaches 0(0, 0.693)Graph of Softplus(x) = log(1 + eˣ)

What it is

Softplus is a smooth curve that always produces a positive output. It looks like ReLU with the sharp corner rounded off.

Why we use it

Its derivative changes smoothly everywhere, which can be useful when a model or physical quantity needs smooth optimization and a positive output.

How it behaves

Large negative inputs approach 0; at x = 0 the output is about 0.693; large positive inputs behave almost like x.

Where to use it

Use it when an output must be positive—such as a scale or rate—or when a smooth ReLU-like function is helpful.

Watch out

It is more expensive than ReLU and never outputs exact zero, so it does not create the same sparse activations.

Solved mathematical example

Put x = 0 into the formula and calculate the output:

Softplus(0) = log(1 + e⁰) = log(1 + 1) = log(2) = 0.693

Graph connection: the highlighted dot is the coordinate (0, 0.693). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: A model predicting an event rate can use Softplus so its output stays positive while still changing smoothly during training.

Input x−3−1013
Output g(x)0.0490.3130.6931.3133.049
10

GELU — Gaussian Error Linear Unit

A smooth gate common in transformers

Formula

GELU(x) = x · Φ(x)

How to read it: Φ(x) is the standard normal cumulative distribution function: a smooth gate between 0 and 1. Multiplying x by that gate softly scales the input.

024-505input xoutput g(x)large positives passsmall negative dip(1, 0.841)Graph of GELU(x) = x · Φ(x)

What it is

GELU smoothly scales an input according to its size instead of making ReLU’s hard keep-or-zero decision.

Why we use it

The smooth probabilistic-style gate works well in many transformer architectures and allows small negative signals to remain.

How it behaves

Very negative inputs approach 0, moderate negative inputs become small negatives, and large positive inputs pass almost unchanged.

Where to use it

Use it when reproducing transformer architectures such as BERT-style models, or when experiments show it beats a ReLU baseline.

Watch out

It costs more to compute than ReLU. Choose it because the architecture or measurements support it, not merely because it is newer.

Solved mathematical example

Put x = 1 into the formula and calculate the output:

GELU(1) = 1 × Φ(1) = 1 × 0.8413 = 0.8413 ≈ 0.841

Graph connection: the highlighted dot is the coordinate (1, 0.841). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: A language model can softly reduce a weak token feature instead of abruptly erasing every feature whose score falls just below zero.

Input x−3−1013
Output g(x)−0.004−0.15900.8412.996
11

SiLU / Swish Function

The input multiplied by its own gate

Formula

SiLU(x) = x · sigmoid(x)

How to read it: First use sigmoid to create a gate between 0 and 1, then multiply the original input by that gate.

024-505input xoutput g(x)smooth positive sidesmall negatives(1, 0.731)Graph of SiLU(x) = x · sigmoid(x)

What it is

SiLU, also called Swish when used without extra parameters, multiplies each input by its sigmoid value.

Why we use it

It creates a smooth, non-monotonic curve that preserves a little negative information and has performed well in several modern vision and language architectures.

How it behaves

Large negative inputs approach 0 from below, zero remains 0, and large positive inputs become almost unchanged.

Where to use it

Use it when following architectures such as EfficientNet-style models or when a controlled comparison shows an improvement.

Watch out

It requires more computation than ReLU, and its benefit is task-dependent. It should not replace a simple baseline without evidence.

Solved mathematical example

Put x = 1 into the formula and calculate the output:

SiLU(1) = 1 × sigmoid(1) = 1 × 0.731 = 0.731

Graph connection: the highlighted dot is the coordinate (1, 0.731). Its horizontal position is the input; its vertical position is the calculated output.

Practical scenario: A vision network can softly dampen a weak negative texture response while letting a strong positive edge response pass almost fully.

Input x−3−1013
Output g(x)−0.142−0.26900.7312.858
12

Softmax: One Choice From Many Classes

The probability distributor

Softmax works on a group of output scores, not one number in isolation. It turns them into values between 0 and 1 that add up to exactly 1.

Formula

softmax(zᵢ) = eᶻⁱ / Σⱼ eᶻʲ

How to read it: exponentiate the score for class i, then divide it by the sum of the exponentiated scores for every class. The symbol Σ means “add them all.”

What it is

A function that converts a vector of raw class scores, called logits, into a probability distribution.

Why we use it

It makes competing class scores comparable and ensures their probabilities total 100%.

How it behaves

Exponentiate each score, then divide by the sum. Larger scores receive a larger share.

Where to use it

The final layer when exactly one class is correct: cat, dog, or bird.

Solved mathematical example: an image model produces three raw scores

e² = 7.389, e¹ = 2.718, e⁰·¹ = 1.105
sum = 7.389 + 2.718 + 1.105 = 11.212
P(cat) = 7.389 / 11.212 = 0.659 = 65.9%

Input: raw logits

Cat2.0
Dog1.0
Bird0.1
→ exponentiate
and normalize
→

Probability bar graph

Cat65.9%
Dog24.2%
Bird9.9%

Largest score: Cat, 2.0

Largest probability: Cat, 65.9%

Check: 65.9 + 24.2 + 9.9 = 100%

Graph connection: each bar’s length equals its calculated probability. The largest input score, 2.0 for cat, produces the longest bar at 65.9%.

Use softmax when the classes are mutually exclusive, such as cat, dog, or bird. For multi-label tasks where several answers can be true at once—such as “outdoor,” “animal,” and “night”—use one sigmoid per label instead. Watch out: softmax probabilities can be overconfident and should not automatically be treated as perfectly calibrated certainty.

Comparison of All the Functions

Use this table after reading the individual explanations. On a phone, swipe horizontally to see every column.

FunctionShapeOutput rangeZero-centred?Typical layerStrong pointMain limitation
StepHard jump0 or 1NoFixed ruleEasy threshold intuitionNo useful gradient for training
SigmoidSmooth S0 to 1NoBinary/multi-label outputProbability-like resultSaturates; tiny gradients
TanhSmooth S−1 to 1YesSome recurrent hidden statesBounded and centredSaturates at both ends
ReLUFlat then line0 to +∞NoDense/CNN hiddenFast; useful positive slopeCan create dead neurons
LinearStraight line−∞ to +∞YesRegression outputUnrestricted numeric resultAdds no non-linearity
Leaky ReLU / PReLUTwo lines−∞ to +∞NoHiddenNegative-side gradientSlope choice or parameter
ELUCurved then line−α to +∞CloserHiddenSmooth negative outputsExponential computation
SELUScaled ELU≈−1.76 to +∞Self-normalizingCompatible dense hiddenCan stabilize mean/varianceRequires strict conditions
SoftplusSmooth ReLU0 to +∞NoPositive output/hiddenSmooth everywhereSlower; never exactly zero
GELUSmooth gated curveSmall negative to +∞NearTransformer hiddenSoft input weightingMore compute than ReLU
SiLU / SwishSmooth gated curveSmall negative to +∞NearModern hiddenSmooth; keeps small negativesBenefit is task-dependent
SoftmaxGroup normalizationEach 0 to 1; sum = 1NoMulti-class outputComparable class probabilitiesExclusive classes; may overconfident

Which Activation Function Should You Choose?

First identify where the function will be used

Inside the network

Hidden layer

Start with ReLU for many dense or CNN models. Follow a tested architecture when it specifies GELU, SiLU, tanh, SELU, or another function.

or

Producing the answer

Output layer

Choose from the task: sigmoid for binary or multi-label, softmax for one-of-many classes, linear for unrestricted regression, or a task-specific constrained output.

1

Hidden layers in a new dense or CNN model

Start with ReLU. Compare a modern smooth alternative only if there is a reason.

2

One yes/no output

Use sigmoid: fraud/not fraud, pass/fail, spam/not spam.

3

Several independent yes/no labels

Use one sigmoid per label: an image can contain both a person and a bicycle.

4

Exactly one class from several

Use softmax: cat, dog, or bird.

5

An unrestricted numeric prediction

Use linear output: price, temperature, or demand.

6

ReLU neurons are repeatedly stuck at zero

Try Leaky ReLU, and also check learning rate and weight initialization.

7

Transformer-style architecture

Follow the tested architecture; GELU, SiLU, or gated variants are common.

The output activation and loss function must agree.

For example, binary classification commonly pairs sigmoid with binary cross-entropy. Many libraries also offer numerically stable losses that accept raw logits, so always check the loss documentation instead of applying an activation twice.

Try Every Function in Python

activation_functions.py
import numpy as np

x = np.array([-3.0, -1.0, 0.0, 1.0, 3.0])

step = (x >= 0).astype(int)
sigmoid = 1 / (1 + np.exp(-x))
tanh = np.tanh(x)
relu = np.maximum(0, x)
leaky_relu = np.where(x > 0, x, 0.01 * x)
linear = x
elu = np.where(x > 0, x, np.exp(x) - 1)

# SELU's standard constants
selu_alpha, selu_scale = 1.67326324, 1.05070098
selu = selu_scale * np.where(
    x > 0, x, selu_alpha * (np.exp(x) - 1)
)

softplus = np.logaddexp(0, x)  # stable log(1 + exp(x))
gelu = 0.5 * x * (
    1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x**3))
)
silu = x * sigmoid

print("Step:      ", step)
print("Sigmoid:   ", np.round(sigmoid, 3))
print("Tanh:      ", np.round(tanh, 3))
print("ReLU:      ", relu)
print("Leaky ReLU:", leaky_relu)
print("Linear:    ", linear)
print("ELU:       ", np.round(elu, 3))
print("SELU:      ", np.round(selu, 3))
print("Softplus:  ", np.round(softplus, 3))
print("GELU:      ", np.round(gelu, 3))
print("SiLU:      ", np.round(silu, 3))

# Softmax works on a group of class scores.
scores = np.array([2.0, 1.0, 0.1])
stable_scores = scores - scores.max()
softmax = np.exp(stable_scores) / np.exp(stable_scores).sum()
print("Softmax:   ", np.round(softmax, 3))
# [0.659 0.242 0.099]

Using them in Keras

keras_examples.py
from keras import Sequential, layers

# Binary classification
binary_model = Sequential([
    layers.Input(shape=(20,)),
    layers.Dense(32, activation="relu"),      # hidden layer
    layers.Dense(1, activation="sigmoid")    # yes/no output
])

# Multi-class classification
class_model = Sequential([
    layers.Input(shape=(20,)),
    layers.Dense(32, activation="relu"),
    layers.Dense(5, activation="softmax")    # one of 5 classes
])

# Regression
regression_model = Sequential([
    layers.Input(shape=(20,)),
    layers.Dense(32, activation="relu"),
    layers.Dense(1, activation="linear")     # unrestricted number
])

Common Beginner Mistakes

“An activation chooses important information.”

It applies a fixed rule. Learned weights determine which patterns reach it.

“Sigmoid should be used everywhere.”

It suits certain outputs, but repeated hidden-layer sigmoid can cause tiny gradients.

“ReLU solves every gradient problem.”

It improves positive-side gradient flow but can still die, and other parts of the network can still cause unstable gradients.

“Tanh is always the best hidden activation.”

It is useful in some recurrent settings, but ReLU-family functions are a more common feedforward starting point.

“Softmax handles multiple independent labels.”

Softmax assumes competing classes. Use separate sigmoids when several labels can be true.

“The most advanced function must be best.”

Architecture, initialization, normalization, optimizer, data, and task all interact. Start with a proven baseline and measure.

Check Your Understanding

1. Why can’t several linear hidden layers learn a curved boundary?

Their linear operations combine into one linear operation. A non-linear activation is needed between layers.

2. Which output activation fits spam versus not-spam?

Sigmoid, because it produces one value between 0 and 1 for a binary outcome.

3. Which output activation fits cat, dog, or bird?

Softmax, because exactly one of the competing classes should be selected.

4. Why is the step function poor for gradient-based training?

Its derivative gives no useful slope almost everywhere and is undefined at the jump.

5. What is a dying ReLU?

A ReLU neuron whose input remains negative, so it keeps outputting zero and may stop learning.

Summary

  • An activation function transforms a neuron’s weighted sum into its outgoing signal.
  • Non-linear activations let stacked layers learn patterns more flexible than straight lines.
  • ReLU is a practical hidden-layer baseline; sigmoid, softmax, and linear serve different output tasks.
  • Tanh, Leaky ReLU, ELU, SELU, GELU, and SiLU are useful alternatives with specific trade-offs.
  • Choose the output activation from the prediction task, then pair it correctly with the loss.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Activation Functions"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Why would a deep network made only of linear layers remain limited?
Question 2 of 5numerical/formula
What is ReLU(-2)?
Question 3 of 5practical selection
Which output activation fits one binary probability?
Question 4 of 5debugging/diagnostic
What causes a dying ReLU unit?
Question 5 of 5interpretation
Why can sigmoid or tanh slow learning at large input magnitudes?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why would a deep network made only of linear layers remain limited?▼

Correct Answer: The composition is still a linear transformation

Composing linear transformations produces another linear transformation; nonlinear activations let the network model curved boundaries.

2What is ReLU(-2)?▼

Correct Answer: 0

ReLU(x)=max(0,x), so every negative input maps to zero.

3Which output activation fits one binary probability?▼

Correct Answer: Sigmoid

Sigmoid maps one logit to a value between 0 and 1, which can represent a binary probability.

4What causes a dying ReLU unit?▼

Correct Answer: It receives negative pre-activations and its derivative stays zero

On the negative side ReLU outputs zero and has zero derivative, so a unit can stop receiving useful updates.

5Why can sigmoid or tanh slow learning at large input magnitudes?▼

Correct Answer: Their derivatives become very small in saturated regions

Near their flat extremes, small derivatives shrink gradients passed to earlier layers.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next