Basic Math Used for Loss Functions

July 1, 2025

Math for Training

Entropy

The mathematical definition of entropy for a discrete probability distribution p(x)p(x) is

H(p)=−∑xp(x)log⁡p(x)H(p) = -\sum_{x} p(x) \log p(x)

Equivalently,

H(X)=Ex∼p[−log⁡p(x)]H(X) = \mathbb{E}_{x \sim p}\left[-\log p(x)\right]

For probabilities p1,…,pnp_1, \dots, p_n:

H(p)=−∑i=1npilog⁡piH(p) = -\sum_{i=1}^{n} p_i \log p_i

The log base determines the unit:

  • log⁡2→\log_2 \rightarrow bits
  • ln⁡→\ln \rightarrow nats

Example: for a fair coin,

p=[0.5, 0.5]p = [0.5,\, 0.5] H(p)=−(0.5log⁡20.5+0.5log⁡20.5)=1 bitH(p) = -\left(0.5 \log_2 0.5 + 0.5 \log_2 0.5\right) = 1 \text{ bit}

Intuition: entropy measures the average uncertainty / information content of a random variable. Higher entropy means the distribution is more uncertain or spread out.

Cross Entropy

H(p,q)=−∑xp(x)log⁡q(x)H(p, q) = -\sum_{x} p(x) \log q(x)

For classification with CC classes:

H(p,q)=−∑i=1Cpilog⁡qiH(p, q) = -\sum_{i=1}^{C} p_i \log q_i

KL divergence

DKL(p∥q)=∑xp(x)log⁡p(x)q(x)D_{\mathrm{KL}}(p \| q) = \sum_{x} p(x) \log \frac{p(x)}{q(x)}

Equivalently,

DKL(p∥q)=Ex∼p[log⁡p(x)−log⁡q(x)]D_{\mathrm{KL}}(p \| q) = \mathbb{E}_{x \sim p}\left[\log p(x) - \log q(x)\right]

For discrete probabilities pi,qip_i, q_i:

DKL(p∥q)=∑ipilog⁡piqiD_{\mathrm{KL}}(p \| q) = \sum_{i} p_i \log \frac{p_i}{q_i}

It connects directly to entropy and cross-entropy:

DKL(p∥q)=H(p,q)−H(p)D_{\mathrm{KL}}(p \| q) = H(p, q) - H(p)

Softmax

σ:Rn→(0,1)n\sigma : \mathbb{R}^n \rightarrow (0, 1)^n

defined by

σ(z)i=ezi∑j=1nezj,i=1,…,n\sigma(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^{n} e^{z_j}}, \qquad i = 1, \dots, n

where

z=(z1,…,zn)∈Rn.\mathbf{z} = (z_1, \dots, z_n) \in \mathbb{R}^n .