Materials · Machine Learning

Neural network formulas: a cheat sheet

Activation functions, loss functions and optimizers in one place. Each formula comes with its meaning, derivative, a worked numeric example, NumPy code, the one thing worth remembering, and its own page with a detailed breakdown and interactive 2D and 3D figures.

Javharbek Abdulatipov
18 formulas with a full breakdown7 activations9 loss functions2 optimizers

Activation functions

The neuron’s non-linearity: without it any deep network collapses into a single linear layer.

Sigmoidlogistic function

(0; 1)
$$\sigma(x)=\frac{1}{1+e^{-x}}$$
Full breakdown →
Details
Meaning

Squashes any number into the interval $(0,\,1)$, so the output reads as a probability. The curve is S-shaped and symmetric about the point $(0,\,0.5)$; its asymptotes are $y=0$ and $y=1$.

Derivative
$$\sigma'(x)=\sigma(x)\,\bigl(1-\sigma(x)\bigr)$$
Example

$\sigma(0)=0.5$, $\sigma(2)\approx0.881$, $\sigma(-2)\approx0.119$. The slope peaks at zero: $\sigma'(0)=0.25$, while $\sigma'(2)\approx0.105$.

In code
def sigmoid(x):
    return 0.5 * (1 + np.tanh(0.5 * x))  # = 1 / (1 + e^-x), no overflow

def sigmoid_grad(x):
    s = sigmoid(x)
    return s * (1 - s)
Remember: the derivative is expressed through the function itself, so backpropagation never recomputes the exponential. The downside: on the tails the slope is almost zero and the gradient vanishes.

Tanhhyperbolic tangent

(−1; 1)
$$\tanh(x)=\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}$$
Full breakdown →
Details
Meaning

The same S shape, but centred at zero with range $(-1,\,1)$. The function is odd: $\tanh(-x)=-\tanh(x)$.

Derivative
$$\tanh'(x)=1-\tanh^{2}(x)$$
Example

$\tanh(1)\approx0.762$, $\tanh'(0)=1$ — four times steeper than the sigmoid at zero, $\tanh'(1)\approx0.420$.

In code
def tanh_grad(x):
    t = np.tanh(x)
    return 1 - t ** 2
Connection: $\tanh(x)=2\sigma(2x)-1$. Outputs are zero-centred, so the next layer’s gradients are not all pushed one way — in hidden layers tanh trains better than the sigmoid.

ReLUrectified linear unit

max(0, x)
$$\operatorname{ReLU}(x)=\max(0,\,x)$$
Full breakdown →
Details
Meaning

Passes positive values unchanged and zeroes out negative ones. It is cheap, and to the right of zero the gradient does not vanish.

Derivative
$$\operatorname{ReLU}'(x)=\begin{cases}1, & x>0\\ 0, & x<0\end{cases}$$
Example

$\operatorname{ReLU}(-3)=0$, $\operatorname{ReLU}(2.5)=2.5$. At $x=0$ there is no derivative; libraries take $0$ by convention.

In code
def relu(x):
    return np.maximum(0, x)

def relu_grad(x):
    return (x > 0).astype(float)
Problem: the “dying ReLU”. If a neuron’s input is always negative, it outputs 0, the gradient is 0 too — and the neuron stops learning.

Leaky ReLU“leaky” ReLU

α ≈ 0.01
$$\operatorname{LReLU}(x)=\begin{cases}x, & x>0\\ \alpha x, & x\le 0\end{cases}=\max(\alpha x,\,x)\ \ (0<\alpha<1)$$
Full breakdown →
Details
Meaning

Like ReLU, but the negative part is not zeroed: it is multiplied by a small $\alpha$ (with $0<\alpha<1$). It cures the dying ReLU.

Derivative
$$\operatorname{LReLU}'(x)=\begin{cases}1, & x>0\\ \alpha, & x<0\end{cases}$$
Example

With $\alpha=0.01$: $\operatorname{LReLU}(-3)=-0.03$, $\operatorname{LReLU}(2)=2$.

In code
def leaky_relu(x, alpha=0.01):
    return np.where(x > 0, x, alpha * x)
Difference from ReLU: on the left the gradient is $\alpha$, not 0. A weak signal always flows, so the neuron does not die.

Softmax“soft argmax”

Σ = 1
$$\operatorname{softmax}(x)_i=s_i=\frac{e^{x_i}}{\sum_{j} e^{x_j}}$$
Full breakdown →
Details
Meaning

Turns a vector of logits (the network’s raw outputs) into a probability distribution: every $s_i\in(0,\,1)$ and they sum to 1. It sits at the end of a multi-class classifier.

Stability

In practice the maximum is subtracted from every logit: $\dfrac{e^{x_i-\max x}}{\sum_j e^{x_j-\max x}}$. The result is the same, with no exponential overflow.

Derivative
$$\frac{\partial s_i}{\partial x_j}=\begin{cases}s_i(1-s_i), & i=j\\ -\,s_i s_j, & i\ne j\end{cases}$$
Example

Logits $(2,\,1,\,0)$ give probabilities $\approx(0.665,\,0.245,\,0.090)$.

In code
def softmax(x):
    e = np.exp(x - x.max())
    return e / e.sum()
Remember: the diagonal $s_i(1-s_i)$ is exactly the derivative of the sigmoid. For two classes softmax is the sigmoid of the logit difference.

Losses — regression

We predict a number. The loss function says how far the prediction $\hat{y}$ is from the answer $y$.

MAEmean absolute error

|·|
$$\mathrm{MAE}=\frac{1}{n}\sum_{i=1}^{n}\bigl|y_i-\hat{y}_i\bigr|$$
Full breakdown →
Details
Meaning

The average absolute error. It is in the same units as the target and is the easiest to interpret. It is more robust to outliers than MSE.

Derivative
$$\frac{\partial\,\mathrm{MAE}}{\partial\hat{y}_i}=-\frac{1}{n}\operatorname{sign}\bigl(y_i-\hat{y}_i\bigr)$$
Example

Running example: $y=(3,\,5,\,8)$, $\hat{y}=(2.5,\,5,\,10)$, errors $y-\hat{y}=(0.5,\,0,\,-2)$. $\mathrm{MAE}=(0.5+0+2)/3\approx0.833$.

In code
mae = np.mean(np.abs(y - y_hat))
The absolute value keeps errors of opposite sign from cancelling out; $|x|=\sqrt{x^2}$. The gradient has the same size for an error of 0.1 and for an error of 100.

MSEmean squared error

(·)²
$$\mathrm{MSE}=\frac{1}{n}\sum_{i=1}^{n}\bigl(y_i-\hat{y}_i\bigr)^2$$
Full breakdown →
Details
Meaning

The average squared error. Squaring punishes large misses hard. Its units are the target’s units squared.

Derivative
$$\frac{\partial\,\mathrm{MSE}}{\partial\hat{y}_i}=-\frac{2}{n}\bigl(y_i-\hat{y}_i\bigr)$$
Example

Running example: $y=(3,\,5,\,8)$, $\hat{y}=(2.5,\,5,\,10)$, errors $y-\hat{y}=(0.5,\,0,\,-2)$. $\mathrm{MSE}=(0.25+0+4)/3\approx1.417$: the single error of $-2$ makes up 94% of the sum.

In code
mse = np.mean((y - y_hat) ** 2)
The gradient is proportional to the error: the bigger the miss, the harder the model is pulled towards it. That is why MSE is more sensitive to outliers than MAE — one anomalous object contributes a huge share.

RMSEroot mean squared error

√MSE
$$\mathrm{RMSE}=\sqrt{\frac{1}{n}\sum_{i=1}^{n}\bigl(y_i-\hat{y}_i\bigr)^2}$$
Full breakdown →
Details
Meaning

The square root of MSE brings the error back to the target’s units. It is as readable as MAE but still punishes large errors more.

Example

Running example: $y=(3,\,5,\,8)$, $\hat{y}=(2.5,\,5,\,10)$, errors $y-\hat{y}=(0.5,\,0,\,-2)$. $\mathrm{RMSE}=\sqrt{1.417}\approx1.190$ versus $\mathrm{MAE}\approx0.833$.

In code
rmse = np.sqrt(np.mean((y - y_hat) ** 2))
Always $\mathrm{RMSE}\ge\mathrm{MAE}$, with equality only when all errors have the same magnitude. The wider the gap, the more uneven the error magnitudes: it is an outlier indicator.

MAPEmean absolute percentage error

%
$$\mathrm{MAPE}=\frac{100\%}{n}\sum_{i=1}^{n}\left|\frac{y_i-\hat{y}_i}{y_i}\right|$$
Full breakdown →
Details
Meaning

The error as a percentage of the actual value: “on average the model is off by MAPE %”. Useful when the relative error matters more than the absolute one.

Example

Running example: $y=(3,\,5,\,8)$, $\hat{y}=(2.5,\,5,\,10)$, errors $y-\hat{y}=(0.5,\,0,\,-2)$. $\mathrm{MAPE}=\frac{100\%}{3}\bigl(\tfrac{0.5}{3}+0+\tfrac{2}{8}\bigr)\approx13.9\%$.

In code
mape = 100 * np.mean(np.abs((y - y_hat) / y))
⚠ Undefined at $y_i=0$ and explodes near zero. Asymmetric: an under-forecast of a positive value costs at most 100%, an over-forecast can cost any amount. The “symmetric” variant is sMAPE, but it is symmetric only in ratios, not in units.

Hubera hybrid of MSE and MAE

threshold δ
$$L_\delta(r)=\begin{cases}\tfrac{1}{2}r^2, & |r|\le\delta\\[1mm] \delta\bigl(|r|-\tfrac{1}{2}\delta\bigr), & |r|>\delta\end{cases}\qquad r=y-\hat{y}$$
Full breakdown →
Details
Meaning

Quadratic near zero like MSE (fine tuning), linear for large errors like MAE (not afraid of outliers). Both branches and their derivatives meet at $|r|=\delta$.

Derivative
$$\frac{\partial L_\delta}{\partial\hat{y}}=\begin{cases}-r, & |r|\le\delta\\ -\delta\operatorname{sign}(r), & |r|>\delta\end{cases}$$
Example

Running example: $y=(3,\,5,\,8)$, $\hat{y}=(2.5,\,5,\,10)$, errors $y-\hat{y}=(0.5,\,0,\,-2)$. With $\delta=1$: losses $0.125$, $0$ and $1\cdot(2-0.5)=1.5$; the mean is $\approx0.542$.

In code
def huber(y, y_hat, delta=1.0):
    r = np.abs(y - y_hat)
    return np.mean(np.where(r <= delta, 0.5 * r ** 2,
                            delta * (r - 0.5 * delta)))
On outliers the gradient is bounded by $\delta$ in magnitude and does not explode. A good fit, for example, for property prices with anomalies. $\delta\downarrow$ — closer to MAE, $\delta\uparrow$ — closer to MSE.

Losses — classification

We predict a class. The model outputs probabilities, and the loss punishes a low probability of the correct answer. The logarithm is natural.

BCEbinary cross-entropy

+ sigmoid
$$\mathrm{BCE}=-\frac{1}{n}\sum_{i=1}^{n}\Bigl[y_i\log\hat{y}_i+(1-y_i)\log\bigl(1-\hat{y}_i\bigr)\Bigr]$$
Full breakdown →
Details
Meaning

For two classes. The label $y\in\{0,1\}$ acts as a switch: of the two terms only one survives, $-\log$ of the probability of the correct answer.

Derivative with respect to the logit
$$\hat{y}=\sigma(z):\qquad \frac{\partial\,\mathrm{BCE}_i}{\partial z_i}=\hat{y}_i-y_i$$
Example

The correct answer is $y=1$. Confident and right, $\hat{y}=0.9$: the loss is $-\ln0.9\approx0.105$. Confident and wrong, $\hat{y}=0.1$: $-\ln0.1\approx2.303$ — 22 times more.

In code
p = np.clip(y_hat, 1e-7, 1 - 1e-7)
bce = -np.mean(y * np.log(p)
               + (1 - y) * np.log(1 - p))
It punishes a confident mistake hardest: as $\hat{y}\to0$ for $y=1$ the loss goes to infinity. Sigmoid + BCE gives the clean gradient “prediction − truth”.

Categorical CEcategorical cross-entropy

+ softmax
$$\mathrm{CE}=-\sum_{k=1}^{K} y_k\log\hat{y}_k$$
Full breakdown →
Details
Meaning

For $K$ classes; $y$ is a one-hot vector (a one in the position of the correct class). Only one term survives — $-\log$ of the probability of the correct class.

Gradient of softmax + CE
$$\hat{y}=\operatorname{softmax}(x):\qquad \frac{\partial\,\mathrm{CE}}{\partial x_k}=s_k-y_k$$
Example

Logits $(2,\,1,\,0)$, the correct class is the first. $s\approx(0.665,\,0.245,\,0.090)$, $\mathrm{CE}=-\ln0.665\approx0.408$, gradient $s-y\approx(-0.335,\,0.245,\,0.090)$: the correct logit is pulled up and the others down.

In code
def cross_entropy(logits, k):
    z = logits - logits.max()
    return np.log(np.exp(z).sum()) - z[k]
The key payoff: the whole softmax Jacobian together with the logarithm collapses into $s_k-y_k$. This pair sits at the end of most classifiers and language models (LLMs), where the classes are vocabulary tokens.

Optimizer

How to move the weights $\theta$ along the loss gradient $g_t$ so that the loss goes down.

Adamadaptive moment estimation

momentum + adaptive
$$\theta_t=\theta_{t-1}-\eta\,\frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}$$
Full breakdown →
Details
Step 1 · first moment (momentum)
$$m_t=\beta_1 m_{t-1}+(1-\beta_1)\,g_t$$
Step 2 · second moment (scale)
$$v_t=\beta_2 v_{t-1}+(1-\beta_2)\,g_t^2$$
Step 3 · bias correction
$$\hat{m}_t=\frac{m_t}{1-\beta_1^{\,t}}\qquad \hat{v}_t=\frac{v_t}{1-\beta_2^{\,t}}$$
Default hyperparameters

$\eta=0.001$ (learning rate), $\beta_1=0.9$, $\beta_2=0.999$, $\epsilon=10^{-8}$. All operations are element-wise: every weight has its own $m$ and $v$.

Example

First step, $g_1=0.5$, $m_0=v_0=0$: $m_1=0.05$, $v_1=0.00025$. Without correction the step would be $3.16$ times too large: $0.05/\sqrt{0.00025}\approx3.16$, because $v$ is understated more than $m$; with it $\hat{m}_1=0.5$, $\hat{v}_1=0.25$, and $\hat{m}_1/\sqrt{\hat{v}_1}=1$. On the first step the weight moves by exactly $\eta$, whatever the scale of the gradient.

In code
m = b1 * m + (1 - b1) * g
v = b2 * v + (1 - b2) * g ** 2
m_hat = m / (1 - b1 ** t)
v_hat = v / (1 - b2 ** t)
theta -= lr * m_hat / (np.sqrt(v_hat) + eps)
The numerator $\hat{m}_t$ says where to go: inertia smooths out gradient noise. The denominator $\sqrt{\hat{v}_t}$ sets how big each weight’s step is. AdamW is the same Adam with weight decay decoupled from the gradient; modern LLMs are trained with it.

The next level

Activations of modern transformers, the predecessors of Adam, metric learning and imbalanced classes — in the order of study.

SiLU / Swishthe activation of Qwen and LLaMA

x·σ(x)
$$\operatorname{SiLU}(x)=x\cdot\sigma(x)$$
Full breakdown →
Details
Example

$\operatorname{SiLU}(1)\approx0.731$, $\operatorname{SiLU}(-1)\approx-0.269$: unlike ReLU, small negative values get through.

A smooth activation: behaves like ReLU away from zero, but with no kink. Inside SwiGLU blocks it is used in Qwen, LLaMA and other modern LLMs.

GELUBERT, GPT

x·Φ(x)
$$\operatorname{GELU}(x)=x\cdot\Phi(x)$$
Full breakdown →
Details
Example

$\operatorname{GELU}(1)\approx0.841$, $\operatorname{GELU}(-1)\approx-0.159$.

$\Phi(x)$ is the cumulative distribution function of the standard normal: the input is scaled by the probability that it is “above the noise”. The standard activation in BERT, GPT-2 and GPT-3.

SGD → Momentum → RMSPropthe groundwork for Adam

momentum
$$\theta_t=\theta_{t-1}-\eta\,g_t$$
Full breakdown →
Details
Momentum
$$u_t=\beta u_{t-1}+g_t,\qquad \theta_t=\theta_{t-1}-\eta\,u_t$$
RMSProp
$$v_t=\beta v_{t-1}+(1-\beta)\,g_t^2,\qquad \theta_t=\theta_{t-1}-\eta\,\frac{g_t}{\sqrt{v_t}+\epsilon}$$
Adam’s predecessors: Momentum adds inertia, RMSProp a per-weight step scale. Work through them in order and Adam becomes obvious.

Triplet Lossre-identification (Re-ID)

margin m
$$L=\max\bigl(0,\;d(a,p)-d(a,n)+m\bigr)$$
Full breakdown →
Details
Example

Margin $m=0.2$. $d(a,p)=0.4$, $d(a,n)=1.1$: $L=0$, the triplet is already separated. $d(a,p)=0.9$, $d(a,n)=1.0$: $L=0.1$ — the “other” is too close.

Metric learning: the anchor $a$ must be closer to its “own” $p$ than to the “other” $n$ by at least the margin $m$. Exactly the mathematics behind re-identifying people across cameras.

Focal Lossimbalanced classes

γ ≈ 2
$$\mathrm{FL}=-(1-p_t)^{\gamma}\log p_t$$
Full breakdown →
Details
Example

$p_t$ is the probability of the correct class. With $\gamma=2$ an easy example with $p_t=0.9$ weighs 100 times less than in CE ($0.001$ versus $0.105$), while a hard one with $p_t=0.3$ only about 2 times less ($0.590$ versus $1.204$).

Cross-entropy with a factor $(1-p_t)^\gamma$: it damps the easy examples and focuses training on the hard ones. Used in object detection, where background vastly outnumbers people and faces.

Backprop and regularizationtopics, not formulas

mechanisms

How the gradient flows back through every layer · L1/L2 · Dropout · BatchNorm / LayerNorm

Details
The next step is not another formula but assembly: understanding backpropagation as the process in which all the formulas above work together.

Route: SiLU and GELU (to close out the activations of modern transformers) → SGD, Momentum, RMSProp (the foundation under Adam) → Triplet Loss (Re-ID) → and then mechanisms rather than formulas: backpropagation and attention inside a transformer.

← All materials