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.

Activation curves, a softmax over three scores and a one-hidden-layer network fitted in the browser (sample data). Try the interactive version.
- 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 . The activation function turns into the unit's output , which the next layer uses as an input.
The weighted sum is linear, and a linear function of a linear function is still linear. Take two one-input layers, followed by . Substituting gives : one straight line, so the second layer added nothing. The same holds for matrices of any size, since .
Put a ReLU between the layers and the result is , a line with a bend at . 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 at every unit it passes through, so a derivative near 0 stops learning and a derivative of 1 passes the signal on untouched.
| Function | Formula | Output range | Derivative | Typical use |
|---|---|---|---|---|
| Sigmoid (logistic) | 0 to 1 | , at most 0.25 | Binary output layer; gates in LSTM and GRU cells | |
| Tanh | −1 to 1 | , at most 1 | Recurrent hidden state; small networks | |
| ReLU | 0 to ∞ | 0 for , 1 for | Default for hidden layers in feed-forward and convolutional networks | |
| Leaky ReLU | if , else () | −∞ to ∞ | 1 or | Hidden layers, when units are dying |
| ELU | if , else | to ∞ | 1 or | Hidden layers; smoother than ReLU at 0 |
| GELU | , with the normal CDF | about −0.17 to ∞ | Transformer feed-forward layers (BERT, GPT) | |
| Swish / SiLU | , SiLU when | about −0.28 to ∞ | for | Image and language models; gated forms such as SwiGLU |
| Softplus | 0 to ∞ | A smooth ReLU; outputs that must be positive, such as a standard deviation | ||
| Softmax | over a vector | each 0 to 1, summing to 1 | 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: , and . Tanh has the same S shape stretched to −1 to 1; in fact . 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 , and tanh's is 0.0099 at . 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 for negative inputs, and PReLU learns during training. ELU (Clevert, Unterthiner and Hochreiter, 2015) curves smoothly down to , 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: . Large positive inputs pass through, large negative ones are switched off, and inputs near zero are scaled down smoothly. A common fast form is . BERT and OpenAI's GPT models use GELU.
Swish, , 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 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 ) and −0.28 (Swish, at ), so their gradient is never zero everywhere on the left the way ReLU's is.
Softplus
Softplus, , is a smooth version of ReLU: it approaches 0 on the left and 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.
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 . Ignoring the weights, ten sigmoid layers scale the gradient by at most , 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:
Here is the temperature, normally 1. Every 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:
| Class | Logit | Probability, | |||
|---|---|---|---|---|---|
| Cat | 2.0 | 7.389 | 70.5% | 87.9% | 54.7% |
| Dog | 1.0 | 2.718 | 25.9% | 11.9% | 33.1% |
| Bird | −1.0 | 0.368 | 3.5% | 0.2% | 12.2% |
| Sum | 10.475 | 100% | 100% | 100% |
At each probability is divided by 10.475: cat 7.389 / 10.475 = 0.705. A gap of one logit between cat and dog becomes a ratio of 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 approaches 0, softmax becomes the argmax. Above 1 it flattens the distribution; as 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: . 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
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 , 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.
| Property | Sigmoid | Tanh | ReLU | Leaky ReLU / ELU | GELU / Swish |
|---|---|---|---|---|---|
| Zero-centred output | No | Yes | No | Leaky ReLU: no; ELU: closer to zero | No, but closer than ReLU |
| Saturates (flat gradient) | Both ends | Both ends | Left half only (gradient 0) | Leaky ReLU: no; ELU: left side, towards | Left side, slowly |
| Can units die? | No | No | Yes | No | Rarely |
| Smooth at 0 | Yes | Yes | No (a corner) | Leaky: no; ELU: yes when | Yes |
| Cost to compute | An exponential | An exponential | A comparison | A comparison (+ exp for ELU) | An erf or exponential |
Choose by where the function sits in the network:
| Layer or task | Usual choice | Alternatives | Why |
|---|---|---|---|
| Hidden layers, feed-forward or convolutional | ReLU | Leaky ReLU, ELU, GELU, SiLU | Cheap, and no saturation for positive inputs |
| Transformer feed-forward layers | GELU | SiLU, gated forms such as SwiGLU | Smooth; used by BERT and GPT |
| Recurrent cells (LSTM, GRU) | Tanh for the state, sigmoid for the gates | Bounded state keeps the recurrence stable; gates need 0 to 1 | |
| Output, binary classification | Sigmoid | The probability of the positive class | |
| Output, one class out of many | Softmax | Probabilities that sum to 1 | |
| Output, several labels at once | Sigmoid per class | Each label is its own yes/no | |
| Output, regression | None (linear) | Softplus for positive targets | The 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 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 units | Loss after 1,000 epochs | After 5,000 epochs | Dead units at the end |
|---|---|---|---|
| Tanh, 8 | 0.0037 | 0.0021 | |
| Sigmoid, 8 | 0.0157 | 0.0022 | |
| GELU, 8 | 0.0116 | 0.0025 | |
| ReLU, 8 | 0.067 | 0.055 | 2 of 8 |
| Leaky ReLU (), 8 | 0.066 | 0.055 | |
| ReLU, 32 | 0.0049 | 0.0040 | 10 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.
- JavaScript
- React
- Angular
// 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);
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
NumberRange,
FastLineRenderableSeries,
XyDataSeries,
LegendModifier,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// Each activation function with its derivative
const sigmoid = (x: number) => 1 / (1 + Math.exp(-x));
const activations = [
{ name: "Sigmoid", colour: "#50C7E0", f: sigmoid, df: (x: number) => sigmoid(x) * (1 - sigmoid(x)) },
{ name: "Tanh", colour: "#F48420", f: Math.tanh, df: (x: number) => 1 - Math.tanh(x) ** 2 },
{ name: "ReLU", colour: "#3BD16F", f: (x: number) => Math.max(0, x), df: (x: number) => (x > 0 ? 1 : 0) }
];
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Input x", visibleRange: new NumberRange(-5, 5) }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "f(x)", visibleRange: new NumberRange(-1.25, 2.5) }));
const xValues = getYourInputRange(); // e.g. 801 points from -5 to 5
for (const a of activations) {
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: xValues.map(a.f), dataSeriesName: a.name }),
stroke: a.colour,
strokeThickness: 2.5
}),
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: xValues.map(a.df), dataSeriesName: `${a.name} derivative` }),
stroke: a.colour,
strokeDashArray: [6, 4] // dashed: the derivative
})
);
}
sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true }),
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
export const ActivationFunctionChart = () => (
<SciChartReact initChart={initChart} style={{ width: "100%", height: 450 }} />
);
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
NumberRange,
FastLineRenderableSeries,
XyDataSeries,
LegendModifier,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// Each activation function with its derivative
const sigmoid = (x: number) => 1 / (1 + Math.exp(-x));
const activations = [
{ name: "Sigmoid", colour: "#50C7E0", f: sigmoid, df: (x: number) => sigmoid(x) * (1 - sigmoid(x)) },
{ name: "Tanh", colour: "#F48420", f: Math.tanh, df: (x: number) => 1 - Math.tanh(x) ** 2 },
{ name: "ReLU", colour: "#3BD16F", f: (x: number) => Math.max(0, x), df: (x: number) => (x > 0 ? 1 : 0) }
];
@Component({
selector: "app-activation-function-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 450px"></scichart-angular>`
})
export class ActivationFunctionChartComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Input x", visibleRange: new NumberRange(-5, 5) }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "f(x)", visibleRange: new NumberRange(-1.25, 2.5) }));
const xValues = getYourInputRange(); // e.g. 801 points from -5 to 5
for (const a of activations) {
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: xValues.map(a.f), dataSeriesName: a.name }),
stroke: a.colour,
strokeThickness: 2.5
}),
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: xValues.map(a.df), dataSeriesName: `${a.name} derivative` }),
stroke: a.colour,
strokeDashArray: [6, 4] // dashed: the derivative
})
);
}
sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true }),
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
}
Key points:
- Each activation and its derivative is a
FastLineRenderableSeriesover anXyDataSeriesof 801 points; the derivative uses the same colour withstrokeDashArray. Hiding a series setsisVisible, and the legend is rebuilt to list only the functions on show. - The softmax is a
FastColumnRenderableSerieson aNumericAxiswith aTextLabelProviderfor the class names, withdataLabelsshowing each probability above its column. - The network trains a few epochs per
requestAnimationFrameand redraws its fit withclear()andappendRange(); the loss is appended point by point to a line series on aLogarithmicAxis, so early and late progress are both visible. - The training points are an
XyScatterRenderableSerieswith anEllipsePointMarker.
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
- Goodfellow, I., Bengio, Y. and Courville, A. (2016), Deep Learning, MIT Press. Chapter 6: hidden units, output units, softmax and the cross-entropy gradient.
- Nair, V. and Hinton, G. E. (2010), Rectified linear units improve restricted Boltzmann machines. Proceedings of the 27th International Conference on Machine Learning, 807–814.
- Glorot, X., Bordes, A. and Bengio, Y. (2011), Deep sparse rectifier neural networks. Proceedings of AISTATS, PMLR 15, 315–323.
- Glorot, X. and Bengio, Y. (2010), Understanding the difficulty of training deep feedforward neural networks. Proceedings of AISTATS, PMLR 9, 249–256.
- Bengio, Y., Simard, P. and Frasconi, P. (1994), Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2), 157–166.
- Hendrycks, D. and Gimpel, K. (2016), Gaussian error linear units (GELUs). arXiv:1606.08415.
- Ramachandran, P., Zoph, B. and Le, Q. V. (2017), Searching for activation functions. arXiv:1710.05941.
- Clevert, D.-A., Unterthiner, T. and Hochreiter, S. (2015), Fast and accurate deep network learning by exponential linear units (ELUs). arXiv:1511.07289.
- Maas, A. L., Hannun, A. Y. and Ng, A. Y. (2013), Rectifier nonlinearities improve neural network acoustic models. ICML Workshop on Deep Learning for Audio, Speech and Language Processing.
- He, K., Zhang, X., Ren, S. and Sun, J. (2015), Delving deep into rectifiers. arXiv:1502.01852. He initialisation and PReLU.
- Lu, L., Shin, Y., Su, Y. and Karniadakis, G. E. (2019), Dying ReLU and initialization: theory and numerical examples. arXiv:1903.06733.
- Leshno, M., Lin, V. Y., Pinkus, A. and Schocken, S. (1993), Multilayer feedforward networks with a nonpolynomial activation function can approximate any function. Neural Networks, 6(6), 861–867.
- Hinton, G., Vinyals, O. and Dean, J. (2015), Distilling the knowledge in a neural network. arXiv:1503.02531. Softmax temperature.
- Devlin, J., Chang, M.-W., Lee, K. and Toutanova, K. (2019), BERT: pre-training of deep bidirectional transformers for language understanding. arXiv:1810.04805. GELU in BERT.
- Radford, A., Narasimhan, K., Salimans, T. and Sutskever, I. (2018), Improving language understanding by generative pre-training. OpenAI. GELU in GPT.
- Shazeer, N. (2020), GLU variants improve transformer. arXiv:2002.05202.
- Guo, C., Pleiss, G., Sun, Y. and Weinberger, K. Q. (2017), On calibration of modern neural networks. arXiv:1706.04599.