↓ Luncat ka eusi utama
  1. Catetan Rékayasa & Artikel Téknis/

Linear Models & Anatomi Objective Functions — Tina MLE sareng MAP ka Cross-Entropy

Daptar eusi
Dasar Machine Learning - Artikel ieu mangrupikeun bagian tina hiji séri.
Bagian 2: Artikel ieu

1. Masalah Inti: Di Mana Loss Functions Salaku Asalna?
#

Dina Part 1, urang ngadetreujan Empirical Risk Minimization (ERM): milih hypothesis $h \in \mathcal{H}$ anu ngaminimalkeun rata-rata loss $\frac{1}{n}\sum_{i=1}^{n} L(h(x_i), y_i)$ dina dataset anu terbatas.

Dina pasah, urang nganggap loss function $L$ salaku anu parantos aya—ngasupkeun squared error $(y - \hat{y})^2$ tanpa naros naonkeun.

Dina praktek, anu barudak sering nganggap loss functions salaku menu heuristik rekayasa anu acak: “pake MSE pikeun regression, pake Cross-Entropy pikeun classification.” Heuristik eta jalan nepi ka anjeun ngadaptar noise non-standar, probabilities imbalanced, atawa model outputs custom—sareng peryogi ngarancang objective function tina prinsip dasar.

Loss functions teu acak. Unggal objective function standar dina machine learning—tina Mean Squared Error dina linear regression nepi ka Cross-Entropy dina Large Language Models modern—mangrupikeun kacindekan matematis langsung tina ngasumsikeun probability distribution husus pikeun data sareng nerapkeun Maximum Likelihood Estimation (MLE) atawa Information Theory.


2. Intuisi Konsep: Nyocokkeun Kurva vs. Modeling Kaos
#

Aya dua cara ningali linear model $\hat{y} = w^\top x$:

  1. The Geometric View: Anjeun ngabogaan awan titik dina spasi, sareng rek nagur hyperplane anu ngaminimalkeun jumlah jarak kuadrat vertikal ti titik ka plane. Ieu ngarasa intuitif, sanajan teu ngajelaskeun naonkeun urang ngakuadratkeun jarak alih-alih nyandak nilai absolut atawa pangkat opat.
  2. The Probabilistic View: Realita noisy. Sanajan hubungan salaku antara input $x$ sareng output $y$ sampurna linier, pangukuran karuksak ku perturbasi acak. Alih-alih mreditkeun hiji angka tetep, model anjeun ngaluarkeun probability distribution $P(y \mid x; w)$ dina sadaya hasil anu mungkin.

Dina tinjauan probabilistik, ngelatih model ngataroskeun hiji patarosan bersih:

Given the dataset we actually observed, which parameter vector $w$ makes these observations most probable?

Sakali anjeun ngumumkeun kumaha noise kalakuanna—Gaussian pikeun pangukuran kontinyu, Bernoulli pikeun kajadian biner, Categorical pikeun next-token prediction—rumus persis loss function anjeun kaluar sacara otomatis ngalangkungan aljabar.


3. Rumusan Matematis: Tina Probability ka Objective Functions
#

Maximum Likelihood Estimation (MLE)
#

Anu dirumuskeun ku Ronald Fisher (1922), Maximum Likelihood Estimation ngalanglang parameter $w$ anu ngamaksimalkeun probability (likelihood) ningali training dataset i.i.d. urang $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)$$

Ngalikeun rebuan atawa jutaan probability ngabalukarkeun numerical underflow (product ngaleungeun ka nol dina arithmetic floating-point). Sabab natural logarithm naek sacara monoton kilat, ngamaksimalkeun likelihood sacara matematis sami sareng ngamaksimalkeun log-likelihood—atawa sarua, ngaminimalkeun 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)$$

Ekspresi NLL ieu mangrupikeun cetak biru pikeun hampir sadaya loss functions dina supervised sareng self-supervised learning.


Derivasi 1: Naonkeun Linear Regression Make Mean Squared Error (MSE)
#

Anggap target urang $y$ dihasilkeun ku fungsi linier tina $x$ anu karuksak ku Gaussian noise zero-mean:

$$y_i = w^\top x_i + \epsilon_i, \qquad \epsilon_i \sim \mathcal{N}(0, \sigma^2)$$

Sarua, distribusi kondisional tina $y_i$ dina $x_i$ Gaussian anu puseur dina prediksi $\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)$$

Ayeuna substitusikeun density ieu ka 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$$

Ngaleungitkeun konstanta positip sareng faktor skala anu teu mindahkeun lokasi minimum ngahasilkeun:

$$\hat{w}_{\text{MLE}} = \arg\min_{w} \frac{1}{n} \sum_{i=1}^{n} (y_i - w^\top x_i)^2$$

Kapentingan utama: Ngaminimalkeun MSE teu ngan kagunaan geometri—eta MLE persis dina asumsi i.i.d. Gaussian noise. Upami data anjeun ngandung outlier heavy-tailed (langkung dibaguskeun ku Laplace distribution $P(\epsilon) \propto \exp(-\vert{}\epsilon\vert{}/b)$), ngaliwatan derivasi persis anu sami ngahasilkeun Mean Absolute Error (MAE / $L_1$ loss) alih-alih MSE.


Derivasi 2: Naonkeun Logistic Regression Make Binary Cross-Entropy (BCE)
#

Ayeuna pertimbangkeun binary classification dimana $y_i \in \{0, 1\}$. Make fungsi linier menta $w^\top x_i$ langsung gagal sabab outputna nyebar $(-\infty, +\infty)$, ngalanggar wates probability $[0, 1]$, sareng kasalahan sacara terang teu Gaussian.

Nuturkeun David Cox (1958), urang modeling log-odds (logit) salaku fungsi linier tina input:

$$\log \left( \frac{p_i}{1 - p_i} \right) = w^\top x_i$$

Ngarengsekeun pikeun $p_i = P(y_i = 1 \mid x_i; w)$ ngahasilkeun logistic sigmoid function:

$$\hat{p}_i = \sigma(w^\top x_i) = \frac{1}{1 + e^{-w^\top x_i}}$$

Sabab $y_i \in \{0, 1\}$, distribusi alami pikeun hiji kajadian biner tunggal mangrupikeun Bernoulli distribution:

$$P(y_i \mid x_i; w) = \hat{p}_i^{y_i} (1 - \hat{p}_i)^{1 - y_i}$$

Sandi Negative Log-Likelihood dibagi rata-rata dina $n$ sampel:

$$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]$$

Ieu Binary Cross-Entropy (BCE) (oge disebut Log Loss).

Naonkeun Teu Ngan Make MSE kana Sigmoid Output?
#

Upami anjeun nyocokkeun $\hat{p}_i = \sigma(w^\top x_i)$ ka squared error $(y_i - \hat{p}_i)^2$, dua patologi muncul:

  1. Non-convexity: MSE ngagabung sareng sigmoid ngahasilkeun non-convex loss surface sareng plateau datar, ngalakukeun optimization gampang kanjebak. BCE, balikna, konveks sampurna (strictly convex) dina $w$.
  2. Vanishing Gradients on Confident Mistakes: Biar $z_i = w^\top x_i$, catet $\frac{d\hat{p}_i}{dz_i} = \hat{p}_i(1 - \hat{p}_i)$. Tingali gradient dua loss ieu dina $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$

Dina BCE, turunan sigmoid kaluar bersih. Upami label salaku $y_i = 1$ sareng model yakin mreditkeun $\hat{p}_i = 0.0001$, MSE ngahasilkeun gradient nol sareng kira-kira teu ngapdetkeun weights—sambing BCE ngahasilkeun signal kasalahan kuat, bersih anu proporsional ka $(\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.


Tinjauan Information-Theoretic: Cross-Entropy & KL Divergence
#

Naonkeun Bernoulli/Categorical NLL husus dingaranan Cross-Entropy? Jawabanana ti Claude Shannon’s Information Theory (1948) sareng Solomon Kullback & Richard Leibler (1951).

Biar $P$ mangrupikeun distribusi label empirical salaku sareng $Q_w$ mangrupikeun distribusi probability anu dipreditkeun model urang. Kullback-Leibler (KL) Divergence ngukur sabaraha inpormasi tambahan (dina nats atawa bits) anu boros nalika encoding sampel tina $P$ make distribusi aproksimasi $Q_w$:

$$D_{\text{KL}}(P \Vert{} Q_w) = \sum_{y} P(y) \log \frac{P(y)}{Q_w(y)}$$

Ngabagi logarithm nga-dekomposisi KL Divergence jadi dua istilah:

$$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)}$$

Sabab entropy data salaku $H(P)$ teu gumantung kana parameter model $w$, ngaminimalkeun KL Divergence dina $w$ sacara matematis sarua sareng ngaminimalkeun Cross-Entropy—anu sami sareng ngamaksimalkeun 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)$$

Ekivalensi ieu ngahijikeun statistik sareng information theory: nga-fit model ngalangkungan Maximum Likelihood sarua sareng nyedhakkeun distribusi probability model saluyu pangandelanna ka data-generating distribution dina KL divergence.


Tina MLE ka MAP: Regularization salaku Bayesian Prior
#

MLE murni percaya data latihan sampurna. Salaku anu urang tingali dina Part 1, sareng sampel noisy anu terbatas, MLE murni bisa ngahasilkeun weights $w$ anu ekstrem pikeun ngahapal noise.

Pikeun ngalebetkeun keyakinan prior kana nilai parameter anu ngarek, urang nerapkeun Bayes’ Theorem sareng ngalakukeun 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)}$$

Sabab $P(S)$ teu gumantung kana $w$, nyandak negative logarithm ngahasilkeun:

$$\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]$$

Asumsikeun Gaussian prior zero-mean isotropic dina weights, $w \sim \mathcal{N}(0, \tau^2 I)$, anu nyatakeun keyakinan weights leutik langkung mungkin sateuacan ningali data:

$$-\log P(w) = \frac{1}{2\tau^2} \Vert{}w\Vert{}_2^2 + \text{const}$$

Ngahijikeun ieu sareng Gaussian linear regression likelihood urang (noise variance $\sigma^2$) sareng ngalikeun $2\sigma^2$ ngahasilkeun 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}$$

Catet harti fisika tina $\lambda = \sigma^2 / \tau^2$: salila pangukuran anjeun noisier ($\sigma^2$) atawa salila prior constraint anjeun kuat ($\tau^2$ leutik), regularization penalty $\lambda$ kedah langkung ageung. Ngaganti Gaussian prior sareng Laplace prior $P(w) \propto \exp(-\Vert{}w\Vert{}_1 / b)$ ngahasilkeun Lasso Regression ($L_1$ regularization)—topik anu bakal urang bedah sacara geometri dina Part 4.


Cross-entropy vs. MSE gradients and MLE vs. MAP posterior

Figure 2. Kenca: pikeun prediksi anu salah kalayan yakin, MSE gradient leungit sambing cross-entropy gradient tetep ageung. Katuhu: Gaussian prior nyarungkeun estimasi MAP ka nol dibandingkeun sareng pucuk MLE.

4. Solusi Analitis vs. Iteratif: Normal Equation sareng Watesna
#

Sakali objective function dihartikeun, kumaha urang mendakan vector $w$ anu ngaminimalkeun eta?

Solusi Closed-Form (Normal Equation)
#

Pikeun Ordinary Least Squares (OLS), susun inputs jadi design matrix $X \in \mathbb{R}^{n \times d}$ sareng targets jadi $y \in \mathbb{R}^n$. Objective-na 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)$$

Nyandak vector gradient sareng nyetel ka nol:

$$\nabla_w J(w) = X^\top X w - X^\top y = 0 \implies \hat{w}_{\text{OLS}} = (X^\top X)^{-1} X^\top y$$

Pikeun MAP (Ridge), penalty term nambahan $\lambda I$ ka diagonal, ngijingkeun invertibility sanajan features collinear:

$$\hat{w}_{\text{Ridge}} = (X^\top X + \lambda I)^{-1} X^\top y$$

Naonkeun Solusi Closed-Form Bisa Runtuh
#

Sanajan elegan ngarengsekeun $\hat{w}$ dina hiji baris linear algebra, solusi analitis gagal dina tilu regime dunya nyata anu kritis:

Kriteria Analytical Solution (Normal Equation) Iterative Optimization (Gradient-Based)
Time Complexity $O(n d^2 + d^3)$ — kubik dina jumlah feature $d$ $O(k \cdot n d)$ atawa $O(k \cdot b d)$ per mini-batch $b$
Memory Footprint Kedah materialize $d \times d$ matrix $X^\top X$ Streams data dina mini-batches leutik; scales ka miliaran baris
Non-Linear Links (e.g., Logistic Regression) Impossible — $\nabla_w J_{\text{BCE}}(w) = \frac{1}{n}X^\top(\sigma(Xw) - y) = 0$ transcendental tanpa bentuk closed-form aljabar Jalan langsung ngalangkungan update first-order atawa second-order
Collinear Features ($X^\top X$ singular) Katingal teu stabil tanpa pseudoinverse (SVD) atawa istilah ridge $L_2$ Converges kalayan mulus ka minimum-norm solution

Sanajan pikeun model sapertos basajan Logistic Regression, nyetel gradient ka nol ngahasilkeun persamaan transcendental nonlinier dina $w$ anu teu bisa di-invert sacara aljabar. Optimization numerik iteratif teu ngan opsional—eta wajib.


5. Implementasi Minimal: Exact MAP Linear Regression & Logistic MLE dina NumPy
#

Di handap ieu implementasi ti nol anu minimal anu ngajelaskeun dua hasil konci tina artikel ieu:

  1. Ngarengsekeun OLS (MLE) sareng Ridge (MAP) sacara analitis make np.linalg.solve (anu make LU/Cholesky factorization sareng langkung numerically stable tibatan ngitung np.linalg.inv sacara eksplisit).
  2. Ngarengsekeun Logistic Regression (BCE MLE) sacara iteratif sareng ngaverifikasi langsung kumaha BCE gradients tetep kuat dina kasalahan anu yakin dimana sigmoid-MSE gradients leungit.
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)")

Ngajelaskeun Kiarana
#

Tilu prediksi teoretis konkret katon langsung dina console output:

  1. Collinearity & MAP Stabilization: Sabab x_raw sareng x_collinear hampir sami, $X^\top X$ kondisi-na goreng. MLE murni (OLS) nembongkeun weights anu lepat ejah (e.g., +50 sareng -48) pikeun nyocokkeun fluktuasi noise leutik. Nambahan Gaussian prior ($\lambda = 1.0$) nyumputkeun sareng misahkeun weight kalayan bersih dina dua feature anu pakait (~1.0 sareng ~1.0).
  2. Exact Recovery via Iterative NLL: Tanpa persamaan closed-form, ngaminimalkeun Binary Cross-Entropy ngawangun deui parameter log-odds salaku kalayan bersih.
  3. The Vanishing Gradient Contrast: Lamun model mreditkeun $\hat{p} \approx 0.00247$ pikeun sampel anu label salakuna $y = 1$, BCE nyadiakeun gradient magnitude 0.9975, langsung nyorong model kaluar tina kasalahan. Sigmoid-MSE nyadiakeun gradient 0.0049—leuwih 200× lemah—ngabalukarkeun sinaon berhenti dimana koreksi pangperluan pisan.

6. Wates & Jembatan ka Part 3
#

Ayeuna urang ngabogaan rengking anu mibanda dasar pikeun ngarobah asumsi probabilistik jadi objective functions persis (MSE, MAE, Cross-Entropy, sareng MAP penalties). Tapi eksperimen NumPy di luhur ngandelan loop langkah tetep anu naif (w_log -= lr * grad) dina smooth, convex 3-parameter bowl.

Naon anu kajadian lamun dataset mibanda 10 miliun baris alih-alih 200, lamun loss surface kadieu sareng narrow ravines, saddle points, sareng non-convex valleys, sareng lamun hiji learning rate tunggal boh lila pisan atanapi diverges kalayan kencang?

Dina Part 3: Mathematical Optimization — From SGD and AdamW to Learning Rate Schedules, urang bakal mbedah geometri loss landscapes sareng ngalacak kumaha iterative optimizers berevolusi tina Robbins & Monro’s Stochastic Approximation (1951) sareng Polyak Momentum (1964) nepi ka Adam sareng AdamW—engine optimization persis anu ngadorong modern deep learning sareng LLMs.


Rujukan
#

  1. 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).
  2. Shannon, C. E. (1948). “A Mathematical Theory of Communication.” Bell System Technical Journal, 27(3), 379–423. (Entropy and information-theoretic foundations).
  3. Kullback, S., & Leibler, R. A. (1951). “On Information and Sufficiency.” The Annals of Mathematical Statistics, 22(1), 79–86. (Original formulation of KL Divergence).
  4. 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).
  5. Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. (Chapters 3 & 4: Probabilistic perspectives on Linear Models, MLE, and MAP).
Dasar Machine Learning - Artikel ieu mangrupikeun bagian tina hiji séri.
Bagian 2: Artikel ieu