Skip to main content

Activation Functions

What is an activation function?​

An activation function is the non-linear function a neural network applies to each unit's weighted sum of inputs before passing it on. Common ones are sigmoid, tanh, ReLU, GELU and Swish in hidden layers, and sigmoid or softmax at the output. Without them, any stack of layers would compute only a straight-line (linear) function of its input.

Four charts in a dark navy theme: sigmoid, tanh, ReLU and GELU curves drawn from x = −5 to 5; a column chart of softmax probabilities for three classes, cat, dog and bird, at 70.5%, 25.9% and 3.5%; a small neural network's output fitted to noisy points of a sine wave; and its training loss falling on a log scale

Activation curves, a softmax over three scores and a one-hidden-layer network fitted in the browser (sample data). Try the interactive version.

Key takeaways
  • A unit computes a weighted sum, then bends it with an activation function. Without that bend, stacked layers collapse into one linear layer.
  • ReLU, max(0, x), is the usual default for hidden layers. GELU and Swish are smooth relatives used in transformers and recent image models.
  • Sigmoid and tanh flatten out for large inputs, so their gradients shrink layer by layer in deep networks.
  • Softmax turns a vector of scores into probabilities that sum to 1. It belongs in the output layer of a multi-class classifier.
  • The output activation follows the task: sigmoid for yes/no, softmax for one class out of many, none (linear) for regression.

Why neural networks need non-linear activation functions​

Each unit (or neuron) in a layer multiplies its inputs by weights, adds a bias and gets a single number, the pre-activation zz. The activation function ff turns zz into the unit's output a=f(z)a = f(z), which the next layer uses as an input.

Diagram of one unit: three inputs multiplied by weights and summed with a bias into z, then bent by an activation function f into the output a, which goes to the next layer. Below, two linear layers y = 2x + 1 then z = 3y − 4 give the straight line z = 6x − 1, while the same layers with a ReLU between them give a line with a bend at x = −0.5

The weighted sum is linear, and a linear function of a linear function is still linear. Take two one-input layers, y=2x+1y = 2x + 1 followed by z=3y−4z = 3y - 4. Substituting gives z=6x−1z = 6x - 1: one straight line, so the second layer added nothing. The same holds for matrices of any size, since 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).

Put a ReLU between the layers and the result is z=3max⁡(0,2x+1)−4z = 3\max(0, 2x + 1) - 4, a line with a bend at x=−0.5x = -0.5. Each unit adds a bend of its own, and enough bends can approximate any smooth curve. The universal approximation theorems make this precise: a network with one hidden layer and a non-polynomial activation can approximate any continuous function on a bounded range, given enough units (Leshno and colleagues, 1993). The theorems don't say how many units, or whether training will find the right weights.

Common activation functions: formulas, ranges and derivatives​

The derivative matters as much as the function. Training by backpropagation multiplies the error signal by f′(z)f'(z) at every unit it passes through, so a derivative near 0 stops learning and a derivative of 1 passes the signal on untouched.

FunctionFormula f(x)f(x)Output rangeDerivative f′(x)f'(x)Typical use
Sigmoid (logistic)11+e−x\dfrac{1}{1 + e^{-x}}0 to 1σ(x) (1−σ(x))\sigma(x)\,(1 - \sigma(x)), at most 0.25Binary output layer; gates in LSTM and GRU cells
Tanhex−e−xex+e−x\dfrac{e^{x} - e^{-x}}{e^{x} + e^{-x}}−1 to 11−tanh⁡2x1 - \tanh^2 x, at most 1Recurrent hidden state; small networks
ReLUmax⁡(0,x)\max(0, x)0 to ∞0 for x<0x < 0, 1 for x>0x > 0Default for hidden layers in feed-forward and convolutional networks
Leaky ReLUxx if x>0x > 0, else αx\alpha x (α≈0.01\alpha \approx 0.01)−∞ to ∞1 or α\alphaHidden layers, when units are dying
ELUxx if x>0x > 0, else α(ex−1)\alpha(e^{x} - 1)−α-\alpha to ∞1 or αex\alpha e^{x}Hidden layers; smoother than ReLU at 0
GELUx Φ(x)x\,\Phi(x), with Φ\Phi the normal CDFabout −0.17 to ∞Φ(x)+x φ(x)\Phi(x) + x\,\varphi(x)Transformer feed-forward layers (BERT, GPT)
Swish / SiLUx σ(βx)x\,\sigma(\beta x), SiLU when β=1\beta = 1about −0.28 to ∞σ(x)+x σ(x)(1−σ(x))\sigma(x) + x\,\sigma(x)(1 - \sigma(x)) for β=1\beta = 1Image and language models; gated forms such as SwiGLU
Softplusln⁡(1+ex)\ln(1 + e^{x})0 to ∞σ(x)\sigma(x)A smooth ReLU; outputs that must be positive, such as a standard deviation
Softmaxezi∑jezj\dfrac{e^{z_i}}{\sum_j e^{z_j}} over a vectoreach 0 to 1, summing to 1pi(δij−pj)p_i(\delta_{ij} - p_j)Output layer of a multi-class classifier; attention weights

Sigmoid and tanh​

The sigmoid function (also called the logistic function) squeezes any input into the range 0 to 1, which reads naturally as a probability: σ(0)=0.5\sigma(0) = 0.5, σ(2)=0.88\sigma(2) = 0.88 and σ(−2)=0.12\sigma(-2) = 0.12. Tanh has the same S shape stretched to −1 to 1; in fact tanh⁡x=2σ(2x)−1\tanh x = 2\sigma(2x) - 1. Because tanh is centred on zero, the next layer receives inputs that average near zero, which usually makes training easier than with sigmoid. Both were the standard hidden-layer activations until about 2010.

Far from zero both curves go flat, which is called saturation. The sigmoid's slope is 0.0066 at x=5x = 5, and tanh's is 0.0099 at x=3x = 3. A unit stuck out there passes almost no gradient back.

ReLU, leaky ReLU and ELU​

The rectified linear unit, ReLU, outputs its input when it is positive and 0 otherwise. Nair and Hinton (2010) used it in restricted Boltzmann machines, and Glorot, Bordes and Bengio (2011) showed it trained deep networks well without pre-training. For positive inputs its slope is exactly 1, so it doesn't saturate there, and it costs one comparison to compute. At initialisation about half of the units output exactly 0 for a given input, which gives sparse activations. Goodfellow, Bengio and Courville's Deep Learning calls ReLU the default recommendation for modern feed-forward networks.

ReLU's flat left half has a cost. A unit whose input is negative for every training example outputs 0 and gets a gradient of 0, so it can never recover. Leaky ReLU (Maas, Hannun and Ng, 2013) keeps a small slope α\alpha for negative inputs, and PReLU learns α\alpha during training. ELU (Clevert, Unterthiner and Hochreiter, 2015) curves smoothly down to −α-\alpha, which pushes the mean output towards zero.

GELU and Swish​

GELU, the Gaussian error linear unit (Hendrycks and Gimpel, 2016), multiplies the input by the probability that a standard normal variable is below it: x Φ(x)x\,\Phi(x). Large positive inputs pass through, large negative ones are switched off, and inputs near zero are scaled down smoothly. A common fast form is 0.5x (1+tanh⁡[2/π (x+0.044715x3)])0.5x\,(1 + \tanh[\sqrt{2/\pi}\,(x + 0.044715x^{3})]). BERT and OpenAI's GPT models use GELU.

Swish, x σ(βx)x\,\sigma(\beta x), came out of an automated search for activation functions by Ramachandran, Zoph and Le (2017), who found it matched or beat ReLU on deep models in their tests. With β=1\beta = 1 it is the same function as the SiLU (sigmoid-weighted linear unit) proposed earlier. Both GELU and Swish dip slightly below zero for negative inputs, to a minimum of about −0.17 (GELU, at x≈−0.75x \approx -0.75) and −0.28 (Swish, at x≈−1.28x \approx -1.28), so their gradient is never zero everywhere on the left the way ReLU's is.

Softplus​

Softplus, ln⁡(1+ex)\ln(1 + e^{x}), is a smooth version of ReLU: it approaches 0 on the left and xx on the right, and its derivative is the sigmoid. It is rarely used in hidden layers now, but it is a handy output activation when a value must be positive.

Vanishing gradients and dying ReLU​

Backpropagation sends the error from the output back through the network, multiplying by each layer's weights and by each unit's activation derivative on the way. The two failure modes below come from that multiplication.

Bar chart of the largest share of the output gradient that reaches each of six layers, counting back from the output, ignoring the weights. Sigmoid bars fall from 1 to 0.25, 0.0625, 0.0156, 0.0039 and 0.001. ReLU bars for an active unit stay at 1 for every layer

The vanishing gradient problem​

The vanishing gradient problem is when the gradient shrinks as it travels back through the layers, so the early layers barely learn. The sigmoid's derivative is at most 0.25, reached only at x=0x = 0. Ignoring the weights, ten sigmoid layers scale the gradient by at most 0.2510≈9.5×10−70.25^{10} \approx 9.5 \times 10^{-7}, about one millionth. Saturated units make it worse, because their derivative is close to 0 rather than 0.25. Tanh's derivative reaches 1 at the centre, so it suffers less, but saturated tanh units still block the gradient. Bengio, Simard and Frasconi (1994) analysed the problem in recurrent networks, and Glorot and Bengio (2010) traced poor training of deep sigmoid networks to saturated top layers.

ReLU passes the gradient through an active unit unchanged, which is a large part of why deep networks became trainable. Careful weight initialisation (Glorot for tanh, He for ReLU), batch or layer normalisation and residual connections help as well.

The dying ReLU problem​

The dying ReLU problem is when a ReLU unit's input becomes negative for every training example. Its output is then always 0 and its gradient is always 0, so gradient descent can never move it again and the unit is dead. A large learning rate or a large negative update to the bias is the usual cause. Lu and colleagues (2019) studied how often whole networks die at initialisation. Remedies are a lower learning rate, He initialisation, leaky ReLU or ELU, or a smooth function such as GELU.

The live demo counts dead units while a ReLU network trains.

The softmax function​

The softmax function turns a vector of real-valued scores into a probability distribution. A classifier's last layer produces one score per class, called the logits; softmax exponentiates each one and divides by the total:

pi=ezi/T∑jezj/Tp_i = \frac{e^{z_i / T}}{\sum_{j} e^{z_j / T}}

Here TT is the temperature, normally 1. Every pip_i is between 0 and 1, they add up to 1, and a larger score always gets a larger probability. The name comes from its being a smooth ("soft") version of the argmax, which would put all the probability on the top class.

A worked softmax example​

An image classifier gives a photo the logits 2.0 for cat, 1.0 for dog and −1.0 for bird:

ClassLogit zzeze^{z}Probability, T=1T = 1T=0.5T = 0.5T=2T = 2
Cat2.07.38970.5%87.9%54.7%
Dog1.02.71825.9%11.9%33.1%
Bird−1.00.3683.5%0.2%12.2%
Sum10.475100%100%100%

At T=1T = 1 each probability is eze^{z} divided by 10.475: cat 7.389 / 10.475 = 0.705. A gap of one logit between cat and dog becomes a ratio of e1=2.72e^{1} = 2.72 between their probabilities, whatever the other scores are.

Softmax temperature​

Temperature divides every logit before the softmax. Below 1 it sharpens the distribution towards the top class; as TT approaches 0, softmax becomes the argmax. Above 1 it flattens the distribution; as TT grows, every class approaches the same probability. Language models expose temperature as a sampling setting for this reason, and knowledge distillation (Hinton, Vinyals and Dean, 2015) trains a small model on a large model's softmax at a high temperature, where the small differences between wrong classes are visible.

Softmax vs sigmoid​

With two classes, softmax and sigmoid are the same model: softmax(z1,z2)1=σ(z1−z2)\text{softmax}(z_1, z_2)_1 = \sigma(z_1 - z_2). Use softmax when each example has exactly one class out of several. Use a separate sigmoid per class when an example can have several labels at once (multi-label classification), such as the tags on a photo: then the outputs needn't add up to 1.

Computing softmax safely​

e1000e^{1000} overflows a 64-bit floating-point number. Softmax doesn't change if you subtract the same number from every logit, so implementations subtract the largest logit first: the logits 1000, 999 and 997 give exactly the same 70.5%, 25.9% and 3.5% as 2, 1 and −1. Training pairs softmax with the cross-entropy loss, and the gradient of the two together with respect to the logits is p−yp - y, the predicted probabilities minus the one-hot target. Libraries compute them as one fused, numerically stable step, which is why their loss functions take logits rather than probabilities.

Sigmoid vs tanh vs ReLU vs GELU: choosing an activation function​

Use ReLU or GELU in hidden layers, and choose the output activation by task: sigmoid for yes/no, softmax for one class out of many, none for regression.

PropertySigmoidTanhReLULeaky ReLU / ELUGELU / Swish
Zero-centred outputNoYesNoLeaky ReLU: no; ELU: closer to zeroNo, but closer than ReLU
Saturates (flat gradient)Both endsBoth endsLeft half only (gradient 0)Leaky ReLU: no; ELU: left side, towards −α-\alphaLeft side, slowly
Can units die?NoNoYesNoRarely
Smooth at 0YesYesNo (a corner)Leaky: no; ELU: yes when α=1\alpha = 1Yes
Cost to computeAn exponentialAn exponentialA comparisonA comparison (+ exp for ELU)An erf or exponential

Choose by where the function sits in the network:

Layer or taskUsual choiceAlternativesWhy
Hidden layers, feed-forward or convolutionalReLULeaky ReLU, ELU, GELU, SiLUCheap, and no saturation for positive inputs
Transformer feed-forward layersGELUSiLU, gated forms such as SwiGLUSmooth; used by BERT and GPT
Recurrent cells (LSTM, GRU)Tanh for the state, sigmoid for the gatesBounded state keeps the recurrence stable; gates need 0 to 1
Output, binary classificationSigmoidThe probability of the positive class
Output, one class out of manySoftmaxProbabilities that sum to 1
Output, several labels at onceSigmoid per classEach label is its own yes/no
Output, regressionNone (linear)Softplus for positive targetsThe target can be any real number

Shazeer (2020) compared gated activations such as SwiGLU in transformer feed-forward layers. If you are unsure, start with ReLU in the hidden layers and change only if training shows a problem, such as many dead units.

Training a small network with each activation​

The demo's third chart trains a network with one input, one hidden layer and one output to fit 60 noisy points of y=sin⁡2xy = \sin 2x on −3 to 3, using full-batch gradient descent with the Adam optimiser and a learning rate that falls from 0.02 to 0.002. Every run starts from the same seeded weights, so only the activation and the number of hidden units change. The noise has a variance of 0.0025, which is roughly the lowest loss a good fit can reach without memorising the noise. These figures were measured with the demo's own code:

Activation, hidden unitsLoss after 1,000 epochsAfter 5,000 epochsDead units at the end
Tanh, 80.00370.0021
Sigmoid, 80.01570.0022
GELU, 80.01160.0025
ReLU, 80.0670.0552 of 8
Leaky ReLU (α=0.1\alpha = 0.1), 80.0660.055
ReLU, 320.00490.004010 of 32

Smooth activations fit this curve with few units, and sigmoid gets there more slowly than tanh. ReLU builds the curve from straight segments, one bend per live unit, so with 8 units it settles on a rough zig-zag; leaky ReLU, which has no dead units, stalls at the same loss, so the shortage of bends matters more than the deaths here. With 32 units ReLU fits well even with 10 dead. The vanishing gradient problem doesn't arise in a network this shallow; ReLU's advantage shows in deep networks, so a toy result like this one is not a reason to drop it.

Common activation function mistakes​

Most activation bugs come from pairing the function with the wrong loss, task or weight initialisation.

  • Applying softmax twice. Many loss functions, such as a cross-entropy loss that takes logits, apply softmax themselves. Feeding them probabilities squashes the outputs and slows training. Check whether your loss expects logits or probabilities.
  • Using softmax for multi-label problems. Softmax forces the classes to compete for a total of 1. When several labels can be true, use a sigmoid per label.
  • Squashing a regression output. A sigmoid or ReLU on the last layer of a regression model can't produce values outside its range: a ReLU output can never predict a negative number. Use a linear output and scale the targets.
  • Mismatching initialisation and activation. Weights sized for tanh (Glorot initialisation) are too small for deep ReLU networks, and He initialisation is too large for sigmoid. Use the scheme designed for your activation.
  • Not watching for dead units. Track the share of ReLU units that output 0 for a whole batch. If it climbs during training, lower the learning rate or switch to leaky ReLU or GELU.
  • Reading softmax outputs as calibrated confidence. A probability of 0.95 from a deep network is often over-confident (Guo and colleagues, 2017). Check calibration on held-out data, or apply temperature scaling, before treating the numbers as real probabilities.
  • Computing softmax without subtracting the maximum. Large logits overflow to infinity and produce NaN. Subtract the largest logit, or use the library's log-softmax.

How to plot activation functions in JavaScript, React or Angular​

The demo trains its network 10 epochs per animation frame, up to 5,000, and redraws the fitted curve and the loss chart after each batch.

Tick functions in the top-left chart, or pick a group from Show, and tick Derivatives to add their slopes as dashed lines. Type three scores into Cat, Dog and Bird and drag Temperature to see the softmax change. In the bottom row, choose an Activation and a number of Hidden units: the network retrains from the same starting weights, and the loss chart keeps the previous run in grey for comparison until you Clear previous run. Pause and Reset control training. Each chart zooms with the mouse wheel, pans by dragging and resets on a double-click; hover to read values.

Here is the code for this chart. The activation functions, softmax and the network's training are plain JavaScript; SciChart.js draws the curves as line series, the softmax as a column series and the training data as a scatter series.

// Activation functions, softmax and a tiny neural network trained in the browser, charted with SciChart.js
const {
SciChartSurface,
NumericAxis,
LogarithmicAxis,
NumberRange,
EAutoRange,
EAxisAlignment,
ENumericFormat,
TextLabelProvider,
FastLineRenderableSeries,
FastColumnRenderableSeries,
XyScatterRenderableSeries,
EllipsePointMarker,
XyDataSeries,
EColumnDataLabelPosition,
WaveAnimation,
LegendModifier,
ELegendPlacement,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- The activation functions and their derivatives (plain JavaScript) ---

// The error function, needed for GELU (Abramowitz and Stegun 7.1.26; absolute error below 1.5e-7)
function erf(x) {
const sign = x < 0 ? -1 : 1;
const t = 1 / (1 + 0.3275911 * Math.abs(x));
const poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t;
return sign * (1 - poly * Math.exp(-x * x));
}
const sigmoid = (x) => 1 / (1 + Math.exp(-x));
const LEAK = 0.1; // leaky ReLU slope for x < 0 (0.01 is a common default; 0.1 makes it visible on the chart)

// f is the function, df its derivative: backpropagation multiplies the gradient by df at every unit
const ACTIVATIONS = {
sigmoid: { name: "Sigmoid", colour: "#50C7E0", f: sigmoid, df: (x) => sigmoid(x) * (1 - sigmoid(x)) },
tanh: { name: "Tanh", colour: "#F48420", f: Math.tanh, df: (x) => 1 - Math.tanh(x) ** 2 },
relu: { name: "ReLU", colour: "#3BD16F", f: (x) => Math.max(0, x), df: (x) => (x > 0 ? 1 : 0) },
leakyRelu: { name: "Leaky ReLU (α = 0.1)", colour: "#E36FD4", f: (x) => (x > 0 ? x : LEAK * x), df: (x) => (x > 0 ? 1 : LEAK) },
elu: { name: "ELU (α = 1)", colour: "#FFD54F", f: (x) => (x > 0 ? x : Math.exp(x) - 1), df: (x) => (x > 0 ? 1 : Math.exp(x)) },
gelu: {
name: "GELU",
colour: "#FF6B6B",
f: (x) => 0.5 * x * (1 + erf(x / Math.SQRT2)), // x times the standard normal CDF
df: (x) => 0.5 * (1 + erf(x / Math.SQRT2)) + (x * Math.exp(-0.5 * x * x)) / Math.sqrt(2 * Math.PI)
},
swish: { name: "Swish / SiLU", colour: "#B39DDB", f: (x) => x * sigmoid(x), df: (x) => sigmoid(x) * (1 + x * (1 - sigmoid(x))) },
softplus: { name: "Softplus", colour: "#C8D3E8", f: (x) => (x > 30 ? x : Math.log1p(Math.exp(x))), df: sigmoid }
};

// Softmax: turns scores (logits) into probabilities that sum to 1. Dividing by the temperature first makes the
// result sharper (T < 1) or flatter (T > 1). Subtracting the largest score stops Math.exp overflowing and
// doesn't change the result.
function softmax(logits, temperature) {
const scaled = logits.map((z) => z / temperature);
const max = Math.max(...scaled);
const exps = scaled.map((z) => Math.exp(z - max));
const sum = exps.reduce((a, b) => a + b, 0);
return exps.map((e) => e / sum);
}

// --- A tiny neural network: 1 input, one hidden layer, 1 linear output, trained with Adam ---

// Seeded random numbers, so every run starts from the same weights and the activations compare fairly
function makeRandom(seed) {
let s = seed;
const random = () => {
s = (s * 16807) % 2147483647;
return (s - 1) / 2147483646;
};
const gaussian = () => Math.sqrt(-2 * Math.log(random() + 1e-12)) * Math.cos(2 * Math.PI * random());
return { random, gaussian };
}

// Sample data: 60 points of y = sin(2x) on -3 to 3, plus a little seeded noise (standard deviation 0.05)
function makeTrainingData(count) {
const { gaussian } = makeRandom(4242);
const x = [];
const y = [];
for (let i = 0; i < count; i++) {
const xi = -3 + (6 * i) / (count - 1);
x.push(xi);
y.push(Math.sin(2 * xi) + 0.05 * gaussian());
}
return { x, y };
}

function createNetwork(hiddenUnits, activation) {
const { gaussian } = makeRandom(1010);
// Parameters: hidden weights w1 and biases b1, output weights w2 and bias b2
const p = { w1: [], b1: [], w2: [], b2: 0 };
for (let j = 0; j < hiddenUnits; j++) {
p.w1.push(gaussian());
p.b1.push(gaussian());
p.w2.push(gaussian() / Math.sqrt(hiddenUnits));
}
// Adam keeps a running mean (m) and mean square (v) of each parameter's gradient
const zeros = () => new Array(hiddenUnits).fill(0);
const m = { w1: zeros(), b1: zeros(), w2: zeros(), b2: [0] };
const v = { w1: zeros(), b1: zeros(), w2: zeros(), b2: [0] };
let step = 0;

const predict = (x) => {
let out = p.b2;
for (let j = 0; j < hiddenUnits; j++) out += p.w2[j] * activation.f(p.w1[j] * x + p.b1[j]);
return out;
};

// One epoch of full-batch gradient descent on the mean squared error. Returns the loss before the update.
function trainStep(xs, ys, learningRate) {
const n = xs.length;
const g = { w1: zeros(), b1: zeros(), w2: zeros(), b2: [0] };
const z = new Array(hiddenUnits);
const a = new Array(hiddenUnits);
let loss = 0;
for (let i = 0; i < n; i++) {
// Forward pass: z = w1·x + b1, a = f(z), output = w2·a + b2
let out = p.b2;
for (let j = 0; j < hiddenUnits; j++) {
z[j] = p.w1[j] * xs[i] + p.b1[j];
a[j] = activation.f(z[j]);
out += p.w2[j] * a[j];
}
const error = out - ys[i];
loss += (error * error) / n;
// Backward pass (the chain rule): the activation's derivative scales each hidden unit's gradient
const dOut = (2 * error) / n;
g.b2[0] += dOut;
for (let j = 0; j < hiddenUnits; j++) {
g.w2[j] += dOut * a[j];
const dz = dOut * p.w2[j] * activation.df(z[j]);
g.w1[j] += dz * xs[i];
g.b1[j] += dz;
}
}
// Adam update, with bias correction for the first steps
step++;
const c1 = 1 - 0.9 ** step;
const c2 = 1 - 0.999 ** step;
const adam = (values, grads, mk, vk) => {
for (let j = 0; j < values.length; j++) {
mk[j] = 0.9 * mk[j] + 0.1 * grads[j];
vk[j] = 0.999 * vk[j] + 0.001 * grads[j] * grads[j];
values[j] -= (learningRate * (mk[j] / c1)) / (Math.sqrt(vk[j] / c2) + 1e-8);
}
};
adam(p.w1, g.w1, m.w1, v.w1);
adam(p.b1, g.b1, m.b1, v.b1);
adam(p.w2, g.w2, m.w2, v.w2);
const b2 = [p.b2];
adam(b2, g.b2, m.b2, v.b2);
p.b2 = b2[0];
return loss;
}

// A ReLU unit is "dead" when its input is negative for every training point: its output and gradient are
// then always 0, so gradient descent can never revive it
const deadUnits = (xs) => p.w1.filter((w, j) => xs.every((x) => w * x + p.b1[j] <= 0)).length;

return { predict, trainStep, deadUnits };
}

// --- The charts ---
const theme = new SciChartJsNavyTheme();
const zoom = () => [new MouseWheelZoomModifier(), new ZoomPanModifier(), new ZoomExtentsModifier()];
const range = (from, to, count) => Array.from({ length: count }, (_, i) => from + ((to - from) * i) / (count - 1));

// 1. The activation functions (solid) and their derivatives (dashed), from x = -5 to 5
const fn = await SciChartSurface.create(ui.functionsDiv, { theme });
fn.sciChartSurface.xAxes.add(new NumericAxis(fn.wasmContext, { axisTitle: "Input x", visibleRange: new NumberRange(-5, 5), labelPrecision: 0 }));
fn.sciChartSurface.yAxes.add(
new NumericAxis(fn.wasmContext, { axisTitle: "f(x)", axisAlignment: EAxisAlignment.Left, visibleRange: new NumberRange(-1.25, 2.5), labelPrecision: 1 })
);
const xs = range(-5, 5, 801);
const fnLegend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopLeft });
const fnCursor = new CursorModifier({ showTooltip: true, showAxisLabels: false });
fn.sciChartSurface.chartModifiers.add(fnLegend, fnCursor, ...zoom());
const functionSeries = {};
for (const [key, a] of Object.entries(ACTIVATIONS)) {
const curve = new FastLineRenderableSeries(fn.wasmContext, {
dataSeries: new XyDataSeries(fn.wasmContext, { xValues: xs, yValues: xs.map(a.f), dataSeriesName: a.name, dataIsSortedInX: true }),
stroke: a.colour,
strokeThickness: 2.5
});
const derivative = new FastLineRenderableSeries(fn.wasmContext, {
dataSeries: new XyDataSeries(fn.wasmContext, { xValues: xs, yValues: xs.map(a.df), dataSeriesName: `${a.name} derivative`, dataIsSortedInX: true }),
stroke: a.colour,
strokeThickness: 1.5,
strokeDashArray: [6, 4]
});
fn.sciChartSurface.renderableSeries.add(curve, derivative);
functionSeries[key] = { curve, derivative };
}

// 2. Softmax: the probability of each class, as columns
const classes = ["Cat", "Dog", "Bird"];
const sm = await SciChartSurface.create(ui.softmaxDiv, { theme });
sm.sciChartSurface.xAxes.add(
new NumericAxis(sm.wasmContext, {
labelProvider: new TextLabelProvider({ labels: classes }),
autoTicks: false,
majorDelta: 1,
minorDelta: 1,
drawMajorGridLines: false,
drawMinorGridLines: false,
drawMajorBands: false,
visibleRange: new NumberRange(-1, 2.6) // room on the left for the watermark
})
);
sm.sciChartSurface.yAxes.add(
new NumericAxis(sm.wasmContext, {
axisTitle: "Probability (%)",
axisAlignment: EAxisAlignment.Left,
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(0, 112), // headroom for the labels above the columns
labelPrecision: 0
})
);
const probabilities = new XyDataSeries(sm.wasmContext, { dataSeriesName: "Softmax probability" });
sm.sciChartSurface.renderableSeries.add(
new FastColumnRenderableSeries(sm.wasmContext, {
dataSeries: probabilities,
fill: "#50C7E0CC",
stroke: "#50C7E0",
strokeThickness: 2,
dataPointWidth: 0.6,
cornerRadius: 8,
animation: new WaveAnimation({ duration: 1000 }),
dataLabels: {
color: "#FFFFFF",
style: { fontSize: 16, fontFamily: "Arial" },
precision: 1,
positionMode: EColumnDataLabelPosition.Outside
}
})
);

// 3. The network's fit: the training points and the network's output across the input range
const training = makeTrainingData(60);
const fitChart = await SciChartSurface.create(ui.fitDiv, { theme });
fitChart.sciChartSurface.xAxes.add(new NumericAxis(fitChart.wasmContext, { axisTitle: "Input x", visibleRange: new NumberRange(-3.2, 3.2), labelPrecision: 0 }));
fitChart.sciChartSurface.yAxes.add(
new NumericAxis(fitChart.wasmContext, { axisTitle: "Output y", axisAlignment: EAxisAlignment.Left, visibleRange: new NumberRange(-1.8, 1.8), labelPrecision: 1 })
);
fitChart.sciChartSurface.renderableSeries.add(
new XyScatterRenderableSeries(fitChart.wasmContext, {
dataSeries: new XyDataSeries(fitChart.wasmContext, { xValues: training.x, yValues: training.y, dataSeriesName: "Training data: sin(2x) + noise" }),
pointMarker: new EllipsePointMarker(fitChart.wasmContext, { width: 7, height: 7, fill: "#C8D3E8", stroke: "#C8D3E8" })
})
);
const fitX = range(-3.2, 3.2, 321);
const fitLine = new XyDataSeries(fitChart.wasmContext, { dataSeriesName: "Network output", dataIsSortedInX: true });
fitChart.sciChartSurface.renderableSeries.add(new FastLineRenderableSeries(fitChart.wasmContext, { dataSeries: fitLine, stroke: "#F48420", strokeThickness: 3 }));
fitChart.sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.BottomRight }),
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
...zoom()
);

// 4. The training loss (mean squared error) on a log scale, with the previous run in grey for comparison
const MAX_EPOCHS = 5000;
const lossChart = await SciChartSurface.create(ui.lossDiv, { theme });
lossChart.sciChartSurface.xAxes.add(
new NumericAxis(lossChart.wasmContext, { axisTitle: "Epoch", visibleRange: new NumberRange(0, MAX_EPOCHS), labelFormat: ENumericFormat.Engineering })
);
lossChart.sciChartSurface.yAxes.add(
new LogarithmicAxis(lossChart.wasmContext, {
axisTitle: "Mean squared error",
axisAlignment: EAxisAlignment.Left,
logBase: 10,
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(0.001, 2),
labelFormat: ENumericFormat.Decimal,
labelPrecision: 3
})
);
const previousLoss = new XyDataSeries(lossChart.wasmContext, { dataSeriesName: "Previous run", dataIsSortedInX: true });
const currentLoss = new XyDataSeries(lossChart.wasmContext, { dataSeriesName: "This run", dataIsSortedInX: true });
const previousLossLine = new FastLineRenderableSeries(lossChart.wasmContext, { dataSeries: previousLoss, stroke: "#8A9BB8", strokeThickness: 2 });
const currentLossLine = new FastLineRenderableSeries(lossChart.wasmContext, { dataSeries: currentLoss, stroke: "#F48420", strokeThickness: 2.5 });
lossChart.sciChartSurface.renderableSeries.add(previousLossLine, currentLossLine);
const lossLegend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopRight });
lossChart.sciChartSurface.chartModifiers.add(
lossLegend,
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
...zoom()
);

// --- The controls ---

// Chart 1: show the ticked functions, and their derivatives when "Derivatives" is ticked
function onFunctionsChanged() {
const showDerivatives = ui.input("derivatives").checked;
const inLegend = [];
for (const key of Object.keys(functionSeries)) {
const { curve, derivative } = functionSeries[key];
const shown = ui.input(key).checked;
curve.isVisible = shown;
derivative.isVisible = shown && showDerivatives;
if (shown) inLegend.push(curve);
fnCursor.includeSeries(derivative, shown && showDerivatives);
}
fnLegend.sciChartLegend?.setRenderableSeriesArray(inLegend); // the dashed derivatives share their function's colour
}

// Presets tick a group of functions at once
const PRESETS = {
classic: ["sigmoid", "tanh"],
relu: ["relu", "leakyRelu", "elu"],
smooth: ["gelu", "swish", "softplus"],
all: Object.keys(ACTIVATIONS)
};
function onPresetChanged() {
const keys = PRESETS[ui.select("preset").value];
if (!keys) return;
for (const key of Object.keys(ACTIVATIONS)) ui.input(key).checked = keys.includes(key);
onFunctionsChanged();
}

// Chart 2: recompute the softmax from the three scores and the temperature
function onSoftmaxChanged() {
const logits = ["logitA", "logitB", "logitC"].map((id) => Number(ui.input(id).value) || 0);
const temperature = Number(ui.input("temperature").value);
ui.input("temperature").nextElementSibling.textContent = `T = ${temperature.toFixed(1)}`;
const p = softmax(logits, temperature);
probabilities.clear();
probabilities.appendRange([0, 1, 2], p.map((value) => 100 * value));
const exps = logits.map((z) => Math.exp(z / temperature));
const sum = exps.reduce((a, b) => a + b, 0);
ui.softmaxReadout.textContent =
`e^(z/T): ${exps.map((e) => (e < 1000 ? e.toFixed(2) : e.toExponential(2))).join(", ")} · ` +
`sum ${sum < 1000 ? sum.toFixed(2) : sum.toExponential(2)} · each probability = e^(z/T) / sum`;
}

// Charts 3 and 4: train the network a few epochs per animation frame, until MAX_EPOCHS
// The learning rate falls from 0.02 to 0.002 over the run, which settles the fit without late loss spikes
const learningRate = (epoch) => 0.02 * Math.pow(0.1, epoch / MAX_EPOCHS);
const EPOCHS_PER_FRAME = 10;
let network;
let epoch = 0;
let running = true;
let lastLoss = NaN;
let runLabel = "";
let lossHistory = { x: [], y: [] }; // a copy of this run's loss curve, kept for the "previous run" line

function drawFit() {
fitLine.clear();
fitLine.appendRange(fitX, fitX.map(network.predict));
}

function showStatus() {
const key = ui.select("activation").value;
const dead = key === "relu" ? ` · dead units ${network.deadUnits(training.x)} of ${ui.select("units").value}` : "";
ui.status.textContent = `Epoch ${epoch.toLocaleString("en-GB")} · loss (MSE) ${Number.isFinite(lastLoss) ? lastLoss.toFixed(4) : "–"}${dead}`;
ui.button("train").textContent = running ? "Pause" : epoch >= MAX_EPOCHS ? "Done" : "Train";
}

// Start again from the same seeded weights. If the settings changed, keep the old loss curve in grey.
function resetNetwork() {
const key = ui.select("activation").value;
const units = Number(ui.select("units").value);
const label = `${ACTIVATIONS[key].name}, ${units} units`;
if (lossHistory.x.length > 0 && label !== runLabel) {
previousLoss.clear();
previousLoss.appendRange(lossHistory.x, lossHistory.y);
previousLoss.dataSeriesName = `Previous: ${runLabel}`;
}
lossHistory = { x: [], y: [] };
currentLoss.clear();
currentLoss.dataSeriesName = label;
runLabel = label;
// Rebuild the legend so it shows the new names, and the previous run only once there is one
lossLegend.sciChartLegend?.setRenderableSeriesArray(previousLoss.count() > 0 ? [previousLossLine, currentLossLine] : [currentLossLine]);
network = createNetwork(units, ACTIVATIONS[key]);
epoch = 0;
lastLoss = NaN;
running = true;
drawFit();
showStatus();
}

function trainFrame() {
if (lossChart.sciChartSurface.isDeleted) return; // stop when the chart is removed from the page
if (running) {
for (let k = 0; k < EPOCHS_PER_FRAME && epoch < MAX_EPOCHS; k++) {
lastLoss = network.trainStep(training.x, training.y, learningRate(epoch));
epoch++;
if (epoch % 5 === 0 || epoch === 1) {
currentLoss.append(epoch, lastLoss);
lossHistory.x.push(epoch);
lossHistory.y.push(lastLoss);
}
}
if (epoch >= MAX_EPOCHS) running = false;
drawFit();
showStatus();
}
requestAnimationFrame(trainFrame);
}

ui.select("preset").addEventListener("change", onPresetChanged);
for (const key of Object.keys(ACTIVATIONS)) {
ui.input(key).addEventListener("change", () => {
ui.select("preset").value = "custom"; // a hand-ticked set
onFunctionsChanged();
});
}
ui.input("derivatives").addEventListener("change", onFunctionsChanged);
for (const id of ["logitA", "logitB", "logitC", "temperature"]) ui.input(id).addEventListener("input", onSoftmaxChanged);
ui.select("activation").addEventListener("change", resetNetwork);
ui.select("units").addEventListener("change", resetNetwork);
ui.button("reset").addEventListener("click", resetNetwork);
ui.button("clearPrevious").addEventListener("click", () => {
previousLoss.clear();
lossLegend.sciChartLegend?.setRenderableSeriesArray([currentLossLine]);
});
ui.button("train").addEventListener("click", () => {
if (epoch < MAX_EPOCHS) running = !running;
showStatus();
});

onFunctionsChanged();
onSoftmaxChanged();
resetNetwork();
requestAnimationFrame(trainFrame);

Key points:

  • Each activation and its derivative is a FastLineRenderableSeries over an XyDataSeries of 801 points; the derivative uses the same colour with strokeDashArray. Hiding a series sets isVisible, and the legend is rebuilt to list only the functions on show.
  • The softmax is a FastColumnRenderableSeries on a NumericAxis with a TextLabelProvider for the class names, with dataLabels showing each probability above its column.
  • The network trains a few epochs per requestAnimationFrame and redraws its fit with clear() and appendRange(); the loss is appended point by point to a line series on a LogarithmicAxis, so early and late progress are both visible.
  • The training points are an XyScatterRenderableSeries with an EllipsePointMarker.

See it in the demo app: JavaScript line chart · React line chart · Angular line chart, and for a live-updating chart like the loss curve, JavaScript real-time chart performance · React real-time chart performance · Angular real-time chart performance.

Go deeper: SciChart.js line series documentation, the column series documentation for the softmax bars, the logarithmic axis documentation for the loss curve, and the line chart guide.

Frequently asked questions​

What is an activation function in a neural network?​

An activation function is the non-linear function applied to each unit's weighted sum of inputs before the result goes to the next layer. Without one, a neural network of any depth can only compute a linear function of its input, because stacked linear layers collapse into a single layer. ReLU, GELU, tanh and sigmoid are common choices for hidden layers, and sigmoid or softmax for the output.

Why is ReLU the most used activation function?​

ReLU, max(0, x), is cheap to compute and has a slope of exactly 1 for positive inputs, so it does not shrink the gradient as it passes back through many layers. That makes deep networks much easier to train than with sigmoid or tanh, which flatten out for large inputs. Its weakness is that a unit whose input is negative for every example stops learning, the dying ReLU problem.

What is the difference between sigmoid and softmax?​

Sigmoid maps one score to a probability between 0 and 1, and is used for a single yes/no output or for each label when several labels can be true at once. Softmax maps a vector of scores to probabilities that add up to 1, and is used when each example belongs to exactly one of several classes. With two classes they give the same result, since softmax of (z1, z2) equals the sigmoid of z1 − z2.

What does temperature do in softmax?​

Temperature divides every score before the softmax is applied. A temperature below 1 makes the distribution sharper, giving more of the probability to the top class, and as it approaches 0 softmax becomes a hard argmax. A temperature above 1 makes the distribution flatter, and very high temperatures give every class nearly the same probability. Language models use it to control how varied their sampled text is.

What is the vanishing gradient problem?​

The vanishing gradient problem is when the error signal gets smaller and smaller as backpropagation carries it from the output back to the early layers, so those layers learn very slowly or not at all. It happens with saturating activations: the sigmoid's derivative is at most 0.25, so ten sigmoid layers can shrink the gradient to about a millionth. ReLU-family activations, careful initialisation, normalisation layers and residual connections reduce it.

How do I plot an activation function in JavaScript?​

Sample the input range, for example 801 points from −5 to 5, compute the function and its derivative at each point in plain JavaScript, and draw each as a line series, with the derivative dashed. SciChart.js does this with FastLineRenderableSeries and XyDataSeries in plain JavaScript, React or Angular, and adds zoom, pan and a tooltip so you can read values near the corners and flat regions.

Sources​