1. The Core Problem: Where Do Loss Functions Actually Come From? #
In Part 1, we established Empirical Risk Minimization (ERM): choose a hypothesis $h \in \mathcal{H}$ that minimizes the average loss $\frac{1}{n}\sum_{i=1}^{n} L(h(x_i), y_i)$ over a finite dataset.
At that point, we treated the loss function $L$ as a given—plugging in squared error $(y - \hat{y})^2$ without asking why.
In practice, beginners often treat loss functions as an arbitrary menu of engineering heuristics: “use MSE for regression, use Cross-Entropy for classification.” That heuristic works until you face non-standard noise, imbalanced probabilities, or custom model outputs—and need to design an objective function from first principles.
Loss functions are not arbitrary. Every standard objective function in machine learning—from Mean Squared Error in linear regression to Cross-Entropy in modern Large Language Models—is the direct mathematical consequence of assuming a specific probability distribution for the data and applying Maximum Likelihood Estimation (MLE) or Information Theory.
2. Conceptual Intuition: Fitting Curves vs. Modeling Uncertainty #
There are two ways to view a linear model $\hat{y} = w^\top x$:
- The Geometric View: You have a cloud of points in space, and you want to draw a hyperplane that minimizes the sum of vertical squared distances from the points to the plane. This feels intuitive, yet it does not explain why we square the distances instead of taking absolute values or fourth powers.
- The Probabilistic View: Reality is noisy. Even if the true relationship between input $x$ and output $y$ is perfectly linear, measurements are corrupted by random perturbations. Instead of predicting a single rigid number, your model outputs a probability distribution $P(y \mid x; w)$ over plausible outcomes.
Under the probabilistic view, training a model asks a single clean question:
Given the dataset we actually observed, which parameter vector $w$ makes these observations most probable?
Once you declare how the noise behaves—Gaussian for continuous sensor measurements, Bernoulli for binary events, Categorical for next-token prediction—the exact formula of your loss function falls out automatically through algebra.
3. Mathematical Formulation: From Probability to Objective Functions #
Maximum Likelihood Estimation (MLE) #
Formalized by Ronald Fisher (1922), Maximum Likelihood Estimation searches for parameters $w$ that maximize the probability (likelihood) of observing our i.i.d. training dataset $S = \{(x_1, y_1), \dots, (x_n, y_n)\}$:
$$\hat{w}_{\text{MLE}} = \arg\max_{w} \prod_{i=1}^{n} P(y_i \mid x_i; w)$$Multiplying thousands or millions of probabilities causes numerical underflow (the product collapses to zero in floating-point arithmetic). Because the natural logarithm is strictly monotonically increasing, maximizing the likelihood is mathematically identical to maximizing the log-likelihood—or equivalently, minimizing the Negative Log-Likelihood (NLL):
$$\hat{w}_{\text{MLE}} = \arg\min_{w} \left( -\sum_{i=1}^{n} \log P(y_i \mid x_i; w) \right)$$This NLL expression is the blueprint for almost all loss functions in supervised and self-supervised learning.
Derivation 1: Why Linear Regression Uses Mean Squared Error (MSE) #
Suppose our target $y$ is generated by a linear function of $x$ corrupted by zero-mean Gaussian noise:
$$y_i = w^\top x_i + \epsilon_i, \qquad \epsilon_i \sim \mathcal{N}(0, \sigma^2)$$Equivalently, the conditional distribution of $y_i$ given $x_i$ is Gaussian centered at the prediction $\hat{y}_i = w^\top x_i$:
$$P(y_i \mid x_i; w, \sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left( -\frac{(y_i - w^\top x_i)^2}{2\sigma^2} \right)$$Now substitute this density into the Negative Log-Likelihood:
$$\text{NLL}(w) = -\sum_{i=1}^{n} \left[ -\frac{1}{2}\log(2\pi\sigma^2) - \frac{(y_i - w^\top x_i)^2}{2\sigma^2} \right]$$$$\text{NLL}(w) = \underbrace{\frac{n}{2}\log(2\pi\sigma^2)}_{\text{constant w.r.t. } w} + \frac{1}{2\sigma^2} \sum_{i=1}^{n} (y_i - w^\top x_i)^2$$Dropping positive constants and scaling factors that do not shift the location of the minimum yields:
$$\hat{w}_{\text{MLE}} = \arg\min_{w} \frac{1}{n} \sum_{i=1}^{n} (y_i - w^\top x_i)^2$$Key takeaway: Minimizing MSE is not just a geometric convenience—it is exact MLE under the assumption of i.i.d. Gaussian noise. If your data contains heavy-tailed outliers (better modeled by a Laplace distribution $P(\epsilon) \propto \exp(-\vert{}\epsilon\vert{}/b)$), repeating this exact derivation produces Mean Absolute Error (MAE / $L_1$ loss) instead of MSE.
Derivation 2: Why Logistic Regression Uses Binary Cross-Entropy (BCE) #
Now consider binary classification where $y_i \in \{0, 1\}$. Using a raw linear function $w^\top x_i$ fails immediately because its output spans $(-\infty, +\infty)$, violating probability bounds $[0, 1]$, and errors are clearly not Gaussian.
Following David Cox (1958), we model the log-odds (logit) as a linear function of the input:
$$\log \left( \frac{p_i}{1 - p_i} \right) = w^\top x_i$$Solving for $p_i = P(y_i = 1 \mid x_i; w)$ gives the logistic sigmoid function:
$$\hat{p}_i = \sigma(w^\top x_i) = \frac{1}{1 + e^{-w^\top x_i}}$$Since $y_i \in \{0, 1\}$, the natural distribution for a single binary outcome is the Bernoulli distribution:
$$P(y_i \mid x_i; w) = \hat{p}_i^{y_i} (1 - \hat{p}_i)^{1 - y_i}$$Take the Negative Log-Likelihood averaged across $n$ samples:
$$J_{\text{BCE}}(w) = -\frac{1}{n} \sum_{i=1}^{n} \Big[ y_i \log(\hat{p}_i) + (1 - y_i) \log(1 - \hat{p}_i) \Big]$$This is Binary Cross-Entropy (BCE) (also called Log Loss).
Why Not Just Apply MSE to the Sigmoid Output? #
If you plugged $\hat{p}_i = \sigma(w^\top x_i)$ into squared error $(y_i - \hat{p}_i)^2$, two pathologies emerge:
- Non-convexity: MSE composed with a sigmoid creates a non-convex loss surface with flat plateaus, making optimization trap-prone. BCE, by contrast, is strictly convex in $w$.
- Vanishing Gradients on Confident Mistakes: Let $z_i = w^\top x_i$, noting that $\frac{d\hat{p}_i}{dz_i} = \hat{p}_i(1 - \hat{p}_i)$. Look at the gradient of both losses with respect to $z_i$:
- MSE gradient: $2(\hat{p}_i - y_i) \cdot \underbrace{\hat{p}_i(1 - \hat{p}_i)}_{\to 0 \text{ when saturated}}$
- BCE gradient: $-\left(\frac{y_i}{\hat{p}_i} - \frac{1 - y_i}{1 - \hat{p}_i}\right) \cdot \hat{p}_i(1 - \hat{p}_i) = \hat{p}_i - y_i$
In BCE, the sigmoid derivative cancels out cleanly. If the true label is $y_i = 1$ and the model confidently predicts $\hat{p}_i = 0.0001$, MSE produces a near-zero gradient and barely updates the weights—while BCE produces a strong, clean error signal proportional to $(\hat{p}_i - y_i)$.
Connection to LLMs: Extending this exact derivation from 2 classes (Bernoulli + Sigmoid) to $K$ mutually exclusive classes (Categorical distribution + Softmax) produces Categorical Cross-Entropy—the exact objective function used to pre-train modern Large Language Models across vocabularies of 50,000 to 200,000 tokens.
The Information-Theoretic View: Cross-Entropy & KL Divergence #
Why is Bernoulli/Categorical NLL specifically named Cross-Entropy? The answer comes from Claude Shannon’s Information Theory (1948) and Solomon Kullback & Richard Leibler (1951).
Let $P$ be the true empirical label distribution and $Q_w$ be our model’s predicted probability distribution. The Kullback-Leibler (KL) Divergence measures how much extra information (in nats or bits) is wasted when encoding samples from $P$ using the approximate distribution $Q_w$:
$$D_{\text{KL}}(P \Vert{} Q_w) = \sum_{y} P(y) \log \frac{P(y)}{Q_w(y)}$$Splitting the logarithm decomposes KL Divergence into two terms:
$$D_{\text{KL}}(P \Vert{} Q_w) = \underbrace{-\sum_{y} P(y) \log Q_w(y)}_{\text{Cross-Entropy } H(P, Q_w)} - \underbrace{\left( -\sum_{y} P(y) \log P(y) \right)}_{\text{Shannon Entropy } H(P)}$$Because the entropy of the true data $H(P)$ does not depend on the model parameters $w$, minimizing KL Divergence with respect to $w$ is mathematically equivalent to minimizing Cross-Entropy—which is identical to maximizing Likelihood:
$$\arg\min_{w} D_{\text{KL}}(P_{\text{data}} \Vert{} Q_w) \equiv \arg\min_{w} H(P_{\text{data}}, Q_w) \equiv \arg\max_{w} \sum_{i=1}^{n} \log Q_w(y_i \mid x_i)$$This equivalence unifies statistics and information theory: fitting a model via Maximum Likelihood is equivalent to pulling the model’s probability distribution as close as possible to the data-generating distribution in KL divergence.
From MLE to MAP: Regularization as a Bayesian Prior #
Pure MLE trusts the training data completely. As we saw in Part 1, with finite noisy samples, pure MLE can drive weights $w$ to extreme magnitudes to memorize noise.
To incorporate prior beliefs about reasonable parameter values, we apply Bayes’ Theorem and perform Maximum A Posteriori (MAP) estimation (Bishop, 2006):
$$\hat{w}_{\text{MAP}} = \arg\max_{w} P(w \mid S) = \arg\max_{w} \frac{P(S \mid w) P(w)}{P(S)}$$Since $P(S)$ is independent of $w$, taking the negative logarithm gives:
$$\hat{w}_{\text{MAP}} = \arg\min_{w} \Big[ \underbrace{-\log P(S \mid w)}_{\text{Data Loss (NLL)}} \underbrace{-\log P(w)}_{\text{Regularization Penalty}} \Big]$$Assume a zero-mean isotropic Gaussian prior on the weights, $w \sim \mathcal{N}(0, \tau^2 I)$, expressing the belief that smaller weights are more plausible before seeing any data:
$$-\log P(w) = \frac{1}{2\tau^2} \Vert{}w\Vert{}_2^2 + \text{const}$$Combining this with our Gaussian linear regression likelihood (noise variance $\sigma^2$) and multiplying by $2\sigma^2$ produces Ridge Regression ($L_2$-regularized MSE):
$$\hat{w}_{\text{MAP}} = \arg\min_{w} \left( \sum_{i=1}^{n} (y_i - w^\top x_i)^2 + \lambda \Vert{}w\Vert{}_2^2 \right), \qquad \text{where } \lambda = \frac{\sigma^2}{\tau^2}$$Notice the physical meaning of $\lambda = \sigma^2 / \tau^2$: the noisier your measurements ($\sigma^2$) or the stronger your prior constraint ($\tau^2$ small), the larger the regularization penalty $\lambda$ should be. Replacing the Gaussian prior with a Laplace prior $P(w) \propto \exp(-\Vert{}w\Vert{}_1 / b)$ produces Lasso Regression ($L_1$ regularization)—a topic we will dissect geometrically in Part 4.

Figure 2. Left: for a confidently wrong prediction, the MSE gradient vanishes while the cross-entropy gradient stays large. Right: a Gaussian prior pulls the MAP estimate toward zero relative to the MLE peak.
4. Analytical vs. Iterative Solutions: The Normal Equation and Its Limits #
Once an objective function is defined, how do we find the vector $w$ that minimizes it?
The Closed-Form Solution (Normal Equation) #
For Ordinary Least Squares (OLS), stack the inputs into a design matrix $X \in \mathbb{R}^{n \times d}$ and targets into $y \in \mathbb{R}^n$. The objective is a quadratic form:
$$J(w) = \frac{1}{2} \Vert{}Xw - y\Vert{}_2^2 = \frac{1}{2} \left( w^\top X^\top X w - 2 y^\top X w + y^\top y \right)$$Taking the vector gradient and setting it to zero:
$$\nabla_w J(w) = X^\top X w - X^\top y = 0 \implies \hat{w}_{\text{OLS}} = (X^\top X)^{-1} X^\top y$$For MAP (Ridge), the penalty term adds $\lambda I$ to the diagonal, guaranteeing invertibility even when features are collinear:
$$\hat{w}_{\text{Ridge}} = (X^\top X + \lambda I)^{-1} X^\top y$$Why Closed-Form Solutions Break Down #
Despite the elegance of solving for $\hat{w}$ in a single line of linear algebra, analytical solutions fail in three critical real-world regimes:
| Criterion | Analytical Solution (Normal Equation) | Iterative Optimization (Gradient-Based) |
|---|---|---|
| Time Complexity | $O(n d^2 + d^3)$ — cubic in feature count $d$ | $O(k \cdot n d)$ or $O(k \cdot b d)$ per mini-batch $b$ |
| Memory Footprint | Must materialize $d \times d$ matrix $X^\top X$ | Streams data in small mini-batches; scales to billions of rows |
| Non-Linear Links (e.g., Logistic Regression) | Impossible — $\nabla_w J_{\text{BCE}}(w) = \frac{1}{n}X^\top(\sigma(Xw) - y) = 0$ is transcendental with no algebraic closed form | Works directly via first-order or second-order updates |
| Collinear Features ($X^\top X$ singular) | Unstable without pseudoinverse (SVD) or $L_2$ ridge term | Converges smoothly toward minimum-norm solution |
Even for a model as simple as Logistic Regression, setting the gradient to zero yields a nonlinear transcendental equation in $w$ that cannot be inverted algebraically. Iterative numerical optimization is no longer optional—it is mandatory.
5. Minimal Implementation: Exact MAP Linear Regression & Logistic MLE in NumPy #
Below is a minimal from-scratch implementation demonstrating two key results from this article:
- Solving OLS (MLE) and Ridge (MAP) analytically using
np.linalg.solve(which uses LU/Cholesky factorization and is far more numerically stable than explicitly computingnp.linalg.inv). - Solving Logistic Regression (BCE MLE) iteratively and verifying directly how BCE gradients remain strong on confident mistakes where sigmoid-MSE gradients vanish.
import numpy as np
rng = np.random.default_rng(7)
# =====================================================================
# PART A: Analytical Linear Regression — MLE (OLS) vs. MAP (Ridge)
# =====================================================================
n_samples = 80
x_raw = rng.uniform(-2.0, 2.0, size=(n_samples, 1))
# Create a nearly collinear second feature to stress-test OLS vs. MAP
x_collinear = x_raw + rng.normal(0.0, 1e-3, size=(n_samples, 1))
X_reg = np.hstack([np.ones((n_samples, 1)), x_raw, x_collinear])
true_w = np.array([1.5, 2.0, 0.0]) # Bias=1.5, true slope=2.0
y_reg = X_reg @ true_w + rng.normal(0.0, 0.5, size=n_samples)
# Exact MLE (OLS): solve (X^T X) w = X^T y
w_mle = np.linalg.solve(X_reg.T @ X_reg, X_reg.T @ y_reg)
# Exact MAP (Ridge): Gaussian prior penalty on weights (excluding bias)
lam = 1.0
I_reg = np.eye(X_reg.shape[1])
I_reg[0, 0] = 0.0 # Do not penalize the intercept term
w_map = np.linalg.solve(X_reg.T @ X_reg + lam * I_reg, X_reg.T @ y_reg)
print("True weights: ", np.round(true_w, 3))
print("MLE (OLS) weights:", np.round(w_mle, 3), "<- explodes under collinearity")
print("MAP (Ridge) w: ", np.round(w_map, 3), "<- stabilized by Gaussian prior\n")
# =====================================================================
# PART B: Logistic Regression via Iterative BCE Minimization
# =====================================================================
def sigmoid(z: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-np.clip(z, -500, 500)))
def bce_loss(y: np.ndarray, p: np.ndarray) -> float:
eps = 1e-12
p = np.clip(p, eps, 1.0 - eps)
return float(-np.mean(y * np.log(p) + (1.0 - y) * np.log(1.0 - p)))
# Synthetic binary dataset
X_clf = rng.normal(0.0, 1.0, size=(200, 2))
X_clf_b = np.hstack([np.ones((200, 1)), X_clf])
logits_true = -0.3 + 2.2 * X_clf[:, 0] - 1.5 * X_clf[:, 1]
y_clf = (rng.uniform(size=200) < sigmoid(logits_true)).astype(float)
# Iterative gradient descent on Negative Log-Likelihood (BCE)
w_log = np.zeros(X_clf_b.shape[1])
lr = 0.5
for step in range(300):
p_hat = sigmoid(X_clf_b @ w_log)
grad = (X_clf_b.T @ (p_hat - y_clf)) / len(y_clf)
w_log -= lr * grad
print(f"Logistic MLE final BCE: {bce_loss(y_clf, sigmoid(X_clf_b @ w_log)):.4f}")
print("Recovered log-odds weights:", np.round(w_log, 3), "(True: [-0.3, 2.2, -1.5])\n")
# =====================================================================
# PART C: Confident Mistake Check — Why BCE Beats Sigmoid-MSE
# =====================================================================
y_true = 1.0
z_wrong = -6.0 # Model is strongly confident the class is 0 (wrong!)
p_wrong = float(sigmoid(np.array([z_wrong]))[0])
grad_bce_z = p_wrong - y_true
grad_mse_z = 2.0 * (p_wrong - y_true) * p_wrong * (1.0 - p_wrong)
print(f"At confident mistake (y=1, p_hat={p_wrong:.5f}):")
print(f" |d(BCE)/dz| = {abs(grad_bce_z):.5f} (strong corrective signal)")
print(f" |d(MSE)/dz| = {abs(grad_mse_z):.5f} (nearly vanished gradient)")Interpreting the Behavior #
Three concrete theoretical predictions show up immediately in the console output:
- Collinearity & MAP Stabilization: Because
x_rawandx_collinearare nearly identical, $X^\top X$ is poorly conditioned. Pure MLE (OLS) assigns wildly opposing weights (e.g.,+50and-48) to fit minor noise fluctuations. Adding the Gaussian prior ($\lambda = 1.0$) shrinks and splits the weight cleanly across the two correlated features (~1.0and~1.0). - Exact Recovery via Iterative NLL: Without any closed-form equation, minimizing Binary Cross-Entropy recovers the true underlying log-odds parameters cleanly.
- The Vanishing Gradient Contrast: When the model predicts $\hat{p} \approx 0.00247$ for a sample whose true label is $y = 1$, BCE delivers a gradient magnitude of
0.9975, immediately pushing the model out of its mistake. Sigmoid-MSE delivers a gradient of just0.0049—over 200× weaker—causing learning to stall right when correction is needed most.
6. Limitations & Bridge to Part 3 #
We now have a principled framework for turning probabilistic assumptions into exact objective functions (MSE, MAE, Cross-Entropy, and MAP penalties). Yet our NumPy experiment above relied on a naive fixed-step loop (w_log -= lr * grad) over a smooth, convex 3-parameter bowl.
What happens when the dataset has 10 million rows instead of 200, when the loss surface is filled with narrow ravines, saddle points, and non-convex valleys, and when a single learning rate either crawls too slowly or diverges violently?
In Part 3: Mathematical Optimization — From SGD and AdamW to Learning Rate Schedules, we will dissect the geometry of loss landscapes and trace how iterative optimizers evolved from Robbins & Monro’s Stochastic Approximation (1951) and Polyak Momentum (1964) all the way to Adam and AdamW—the exact optimization engine powering modern deep learning and LLMs.
References #
- Fisher, R. A. (1922). “On the Mathematical Foundations of Theoretical Statistics.” Philosophical Transactions of the Royal Society of London. Series A, 222, 309–368. (Formal foundation of Maximum Likelihood Estimation).
- Shannon, C. E. (1948). “A Mathematical Theory of Communication.” Bell System Technical Journal, 27(3), 379–423. (Entropy and information-theoretic foundations).
- Kullback, S., & Leibler, R. A. (1951). “On Information and Sufficiency.” The Annals of Mathematical Statistics, 22(1), 79–86. (Original formulation of KL Divergence).
- Cox, D. R. (1958). “The Regression Analysis of Binary Sequences.” Journal of the Royal Statistical Society: Series B (Methodological), 20(2), 215–242. (Foundation of Logistic Regression).
- Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. (Chapters 3 & 4: Probabilistic perspectives on Linear Models, MLE, and MAP).