<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by w2sgarnav on Medium]]></title>
        <description><![CDATA[Stories by w2sgarnav on Medium]]></description>
        <link>https://medium.com/@w2sgarnav?source=rss-b28212064637------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FTDCeGN8dUQkgYrtsE8Z4g.jpeg</url>
            <title>Stories by w2sgarnav on Medium</title>
            <link>https://medium.com/@w2sgarnav?source=rss-b28212064637------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:51:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@w2sgarnav/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Regularization, Optimization, and When Linear Regression Breaks]]></title>
            <link>https://medium.com/@w2sgarnav/regularization-optimization-and-when-linear-regression-breaks-56e895399ca8?source=rss-b28212064637------2</link>
            <guid isPermaLink="false">https://medium.com/p/56e895399ca8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[w2sgarnav]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 14:47:14 GMT</pubDate>
            <atom:updated>2026-01-10T14:47:14.313Z</atom:updated>
            <content:encoded><![CDATA[<p><em>series on Linear and Logistic Regression</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*aKY3-14n3echY87M.png" /><figcaption>Bias–variance trade-off: increasing model complexity decreases bias but increases variance.</figcaption></figure><p>We saw the theory of OLS: the closed-form solution, the Gauss-Markov theorem, and exact inference under normality. But real data is messy. Features are correlated. Sometimes we have more variables than observations. And gradient descent sometimes beats matrix inversion.</p><p>This post is about what happens when the textbook assumptions fail, and what to do about it.</p><h3>When Does the Normal Equation Fail?</h3><p>The OLS solution <strong>β̂ = (XᵀX)⁻¹Xᵀy</strong> requires inverting <strong>XᵀX</strong>.</p><p>This fails or becomes unreliable when:</p><p>Problem :<br><strong>p &gt; n</strong> (more features than observations) <br><strong>Perfect multicollinearity<br>Near-multicollinearity</strong></p><p>What Happens :<br>XᵀX is singular — no unique solution <br>One predictor is exact linear combo of others <br>XᵀX is nearly singular — numerically unstable</p><p>Even when inversion is technically possible, <strong>ill-conditioning</strong> causes coefficient estimates to swing wildly with small data changes.</p><blockquote><strong><em>The symptom:</em></strong><em> Coefficients with huge standard errors, unexpected signs, or values that change dramatically when you add/remove a single observation.</em></blockquote><h3>Multicollinearity: A Deep Dive</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*QMNpH1r__26SFC70.png" /><figcaption><em>Highly correlated predictors contain overlapping information, leading to unstable coefficient estimates.</em></figcaption></figure><h3>What Is It?</h3><p><strong>Multicollinearity</strong> exists when predictor variables are highly correlated with each other — when one predictor can be (approximately) predicted from the others.</p><p><strong>Simple example:</strong> Including both “height in inches” and “height in centimeters” as predictors. They’re perfectly correlated, so you can’t tell which one is “really” driving the effect.</p><p><strong>Subtler example:</strong> In a housing model, square footage and number of bedrooms are correlated. Larger houses tend to have more bedrooms. The model struggles to separate their individual effects.</p><h3>Why Is It a Problem?</h3><p>Multicollinearity doesn’t bias your predictions — the model still predicts well overall. But it <strong>destroys interpretability</strong>:</p><ul><li>Standard errors explode</li><li>Coefficients become unstable</li><li>Signs may flip (you might get a negative coefficient for square footage!)</li><li>You can’t trust statements like “a 1-unit increase in X leads to…”</li></ul><h3>Detection: The Variance Inflation Factor (VIF)</h3><p>For each predictor xⱼ, calculate:</p><blockquote><strong><em>VIFⱼ = 1 / (1 — Rⱼ²)</em></strong></blockquote><p>where <strong>Rⱼ²</strong> is the R² from regressing xⱼ on all other predictors.</p><p><strong>Interpretation:</strong> VIF tells you how much the variance of β̂ⱼ is inflated due to multicollinearity:</p><blockquote><strong><em>Var(β̂ⱼ) = [σ² / ((n-1)·Var(xⱼ))] · VIFⱼ</em></strong></blockquote><p><strong>Rules of thumb:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*T6YZCVmb_2K6Qe6bgdmnRg.png" /></figure><h3>Detection: The Condition Number</h3><p>A more global measure:</p><blockquote><strong><em>κ(XᵀX) = λₘₐₓ / λₘᵢₙ</em></strong></blockquote><p>where λₘₐₓ and λₘᵢₙ are the largest and smallest eigenvalues of XᵀX.</p><p>Condition Number Interpretation &lt; 10 No serious problem 10–30 Moderate multicollinearity &gt; 30 Serious multicollinearity</p><h3>What to Do About Multicollinearity</h3><ol><li><strong>Remove redundant predictors</strong> — If two variables measure the same thing, drop one</li><li><strong>Combine predictors</strong> — Create an index or use PCA</li><li><strong>Get more data</strong> — Sometimes helps, sometimes doesn’t</li><li><strong>Use regularization</strong> — Ridge regression handles multicollinearity gracefully</li><li><strong>Accept it</strong> — If you only care about prediction, not interpretation</li></ol><h3>The Bias-Variance Trade-off</h3><p>Before diving into regularization, we need to understand a fundamental concept.</p><h3>Decomposition of Prediction Error</h3><p>For any estimator <strong>f̂(x)</strong>, the expected prediction error decomposes as:</p><blockquote><strong><em>E[(y — f̂(x))²] = Variance + Bias² + Irreducible Error</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*NIU9Gy2NdhKMiXl77UojeQ.png" /></figure><h3>The Trade-off</h3><ul><li><strong>High variance:</strong> Model is sensitive to training data — overfitting</li><li><strong>High bias:</strong> Model systematically misses the true relationship — underfitting</li></ul><p><strong>OLS is unbiased</strong> but can have <strong>high variance</strong> when:</p><ul><li>Features are correlated (multicollinearity)</li><li>p is large relative to n</li><li>Data is noisy</li></ul><h3>The Key Insight</h3><blockquote><strong><em>We can sometimes achieve lower total error by accepting some bias in exchange for a large reduction in variance.</em></strong></blockquote><p>This is the motivation for regularization.</p><h3>Regularization: The Big Picture</h3><p>Regularization adds a <strong>penalty term</strong> to the loss function that discourages large coefficients:</p><blockquote><strong><em>Regularized Loss = RSS + λ · (Penalty on β)</em></strong></blockquote><p>The penalty “shrinks” coefficients toward zero, which:</p><ul><li>Reduces variance (more stable estimates)</li><li>Introduces some bias (coefficients are systematically too small)</li><li>Often improves prediction on new data</li></ul><p>The <strong>regularization parameter λ</strong> controls the trade-off:</p><ul><li>λ = 0: Regular OLS</li><li>λ → ∞: All coefficients shrink to zero</li></ul><h3>Ridge Regression (L2 Regularization)</h3><h3>The Idea</h3><p><strong>Ridge regression</strong> adds the sum of squared coefficients as a penalty:</p><blockquote><strong><em>β̂ʳⁱᵈᵍᵉ = argmin { ‖y — Xβ‖² + λ‖β‖₂² }</em></strong></blockquote><p>where <strong>‖β‖₂² = Σⱼβⱼ²</strong> (excluding the intercept, typically).</p><h3>Closed-Form Solution</h3><p>Unlike Lasso, Ridge has a beautiful closed-form:</p><blockquote><strong><em>β̂ʳⁱᵈᵍᵉ = (XᵀX + λI)⁻¹Xᵀy</em></strong></blockquote><p><strong>Why this works:</strong> Adding λI to XᵀX ensures invertibility. Every eigenvalue of (XᵀX + λI) is at least λ &gt; 0, so it’s always invertible — even when p &gt; n!</p><h3>Properties of Ridge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*LuQJmWN7Mba_n5Vty7fyng.png" /></figure><h3>Geometric Interpretation</h3><p>The constraint <strong>‖β‖₂² ≤ t</strong> defines a <strong>sphere</strong> in parameter space. Ridge finds the RSS-minimizing point within (or on) this sphere.</p><h3>Bayesian Interpretation</h3><p>Ridge is equivalent to MAP estimation with a Gaussian prior:</p><blockquote><strong><em>βⱼ ~ N(0, τ²)</em></strong></blockquote><p>The prior says “coefficients are probably small” — and the data updates this belief.</p><h3>When to Use Ridge</h3><ul><li>Multicollinearity is present</li><li>You have many predictors relative to observations</li><li>You want to keep all predictors but shrink them</li><li>Prediction is the primary goal</li></ul><h3>Lasso Regression (L1 Regularization)</h3><h3>The Idea</h3><p><strong>Lasso</strong> (Least Absolute Shrinkage and Selection Operator) uses the sum of absolute values:</p><blockquote><strong><em>β̂ˡᵃˢˢᵒ = argmin { ‖y — Xβ‖² + λ‖β‖₁ }</em></strong></blockquote><p>where <strong>‖β‖₁ = Σⱼ|βⱼ|</strong>.</p><h3>The Magic: Automatic Feature Selection</h3><p><strong>Key difference from Ridge:</strong> Lasso produces <strong>sparse solutions</strong> — some coefficients become exactly zero.</p><p>This means Lasso performs <strong>automatic feature selection</strong>. It tells you which predictors matter and which don’t.</p><h3>Why Does L1 Induce Sparsity?</h3><p>Geometric intuition:</p><ul><li>The L1 constraint <strong>‖β‖₁ ≤ t</strong> defines a <strong>diamond</strong> (or hypercube) in parameter space</li><li>The corners of this diamond lie on the coordinate axes</li><li>Because RSS contours are elliptical, they typically first touch the diamond at a corner</li><li>At corners, some coordinates are exactly zero</li></ul><p>In contrast, the smooth L2 sphere has no corners, so solutions rarely land exactly on an axis.</p><h3>No Closed Form</h3><p>Unlike Ridge, Lasso has <strong>no closed-form solution</strong> because the L1 norm isn’t differentiable at zero. You need iterative algorithms like:</p><ul><li>Coordinate descent</li><li>LARS (Least Angle Regression)</li><li>Proximal gradient methods</li></ul><h3>Properties of Lasso</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*CDAMtFSG_Fi632DEwi4qag.png" /></figure><h3>When to Use Lasso</h3><ul><li>You suspect many predictors are irrelevant</li><li>You want interpretability (which variables matter?)</li><li>Feature selection is a goal</li><li>You’re willing to sacrifice some of correlated predictors</li></ul><h3>Elastic Net: Best of Both Worlds</h3><h3>The Idea</h3><p><strong>Elastic Net</strong> combines L1 and L2 penalties:</p><blockquote><strong><em>β̂ᴱᴺ = argmin { ‖y — Xβ‖² + λ₁‖β‖₁ + λ₂‖β‖₂² }</em></strong></blockquote><p>Or equivalently, with a mixing parameter α ∈ [0,1]:</p><blockquote><strong><em>Penalty = λ[α‖β‖₁ + (1-α)‖β‖₂²]</em></strong></blockquote><h3>Why Both?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*D-ByWCxFa8hqecxesERLRw.png" /></figure><h3>When to Use Elastic Net</h3><ul><li>You want feature selection AND have correlated predictors</li><li>Groups of correlated variables should be in or out together</li><li>p &gt;&gt; n situations</li></ul><h3>Choosing λ: Cross-Validation</h3><p>How do you pick the regularization strength?</p><h3>The Process</h3><ol><li>Split data into K folds (typically K = 5 or 10)</li><li>For each candidate λ:</li></ol><ul><li>For each fold k:</li><li>Train on all folds except k</li><li>Evaluate prediction error on fold k</li><li>Average the errors across folds</li></ul><p>then, Choose λ with lowest average error</p><h3>Practical Tips</h3><ul><li>Use a grid of λ values on a log scale</li><li>Most software does this automatically (e.g., cv.glmnet in R, RidgeCV/LassoCV in sklearn)</li><li>Consider the “1 SE rule”: choose largest λ within 1 standard error of the minimum (simpler model)</li></ul><h3>Optimization Methods</h3><h3>When to Use the Normal Equation</h3><p>The closed-form <strong>β̂ = (XᵀX)⁻¹Xᵀy</strong> has complexity:</p><ul><li>Matrix multiplication: O(np²)</li><li>Matrix inversion: O(p³)</li></ul><p><strong>Good when:</strong> p is small (say, &lt; 10,000)</p><p><strong>Bad when:</strong> p is large, or you’re doing regularization without a closed form (Lasso)</p><h3>Gradient Descent</h3><p>For large-scale problems, iterative methods win.</p><p>For MSE loss <strong>J(β) = (1/2n)‖y — Xβ‖²</strong>:</p><blockquote><strong><em>∇J = -(1/n)Xᵀ(y — Xβ)</em></strong></blockquote><p><strong>Update rule:</strong></p><blockquote><strong><em>β⁽ᵗ⁺¹⁾ = β⁽ᵗ⁾ — α∇J = β⁽ᵗ⁾ + (α/n)Xᵀ(y — Xβ⁽ᵗ⁾)</em></strong></blockquote><p>where <strong>α</strong> is the <strong>learning rate</strong>.</p><h3>Convergence Conditions</h3><p>Gradient descent converges if:</p><blockquote><strong><em>0 &lt; α &lt; 2/λₘₐₓ(XᵀX/n)</em></strong></blockquote><p><strong>Convergence rate:</strong></p><blockquote>‖β⁽ᵗ⁾ — β‖ ≤ (1 — λₘᵢₙ/λₘₐₓ)ᵗ · ‖β⁽⁰⁾ — β<em>‖**</em></blockquote><p><strong>Key insight:</strong> Convergence is slow when the condition number κ = λₘₐₓ/λₘᵢₙ is large — exactly when multicollinearity is present!</p><h3>Stochastic Gradient Descent (SGD)</h3><p>Instead of using all data, update with a single random observation:</p><blockquote><strong><em>β⁽ᵗ⁺¹⁾ = β⁽ᵗ⁾ + α(yᵢ — xᵢᵀβ⁽ᵗ⁾)xᵢ</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*pwdr9sY8hm9yc4qyAya5Ag.png" /></figure><h3>Mini-batch Gradient Descent</h3><p>A compromise — use a batch of b observations:</p><blockquote><strong><em>β⁽ᵗ⁺¹⁾ = β⁽ᵗ⁾ + (α/b) Σᵢ∈batch (yᵢ — xᵢᵀβ⁽ᵗ⁾)xᵢ</em></strong></blockquote><p><strong>Typical batch sizes:</strong> 32, 64, 128, 256</p><h3>Comparison Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*IYfR8f5osYE7WCHmIASs5A.png" /></figure><p>*With enough iterations</p><h3>Residual Diagnostics: Finding Problems</h3><p>Even with regularization, you should check your residuals.</p><h3>Standardized Residuals</h3><p>Raw residuals have different variances (high-leverage points have smaller residual variance). To compare fairly:</p><blockquote><strong><em>rᵢ = ε̂ᵢ / (s · √(1 — hᵢᵢ))</em></strong></blockquote><p><strong>Rule of thumb:</strong> |rᵢ| &gt; 2 or 3 deserves attention.</p><h3>Studentized Residuals (Leave-One-Out)</h3><blockquote><strong><em>tᵢ = ε̂ᵢ / (s₍ᵢ₎ · √(1 — hᵢᵢ))</em></strong></blockquote><p>where s₍ᵢ₎ is computed without observation i. More sensitive to outliers.</p><h3>Cook’s Distance</h3><p>Measures influence of observation i on <strong>all</strong> predictions:</p><blockquote><strong><em>Dᵢ = [rᵢ² / (p+1)] · [hᵢᵢ / (1 — hᵢᵢ)]</em></strong></blockquote><p><strong>Rules of thumb:</strong></p><ul><li>Dᵢ &gt; 1: Definitely investigate</li><li>Dᵢ &gt; 4/n: Worth a look</li></ul><h3>What the Plots Tell You</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*Wu2Vhlgknr57VWzczQvUhw.png" /></figure><h3>Extensions of Linear Regression</h3><h3>Polynomial Regression</h3><p>Transform features to capture curves:</p><blockquote><strong><em>y = β₀ + β₁x + β₂x² + β₃x³ + ε</em></strong></blockquote><p><strong>Still linear regression!</strong> It’s linear in β, just nonlinear in x.</p><p><strong>Warning:</strong> High-degree polynomials overfit easily. Use regularization or cross-validation.</p><h3>Interaction Terms</h3><p>Let the effect of one variable depend on another:</p><blockquote><strong><em>y = β₀ + β₁x₁ + β₂x₂ + β₃(x₁·x₂) + ε</em></strong></blockquote><p><strong>Interpretation:</strong> The effect of x₁ on y is now (β₁ + β₃x₂) — it depends on x₂!</p><p><strong>When to include interactions:</strong></p><ul><li>Theory suggests the effect should vary</li><li>You see it in exploratory plots</li><li>Be careful: interactions increase multicollinearity</li></ul><h3>Weighted Least Squares (WLS)</h3><p>When errors have unequal variance Var(εᵢ) = σ²/wᵢ:</p><blockquote><strong><em>β̂ᵂᴸˢ = argmin Σᵢ wᵢ(yᵢ — xᵢᵀβ)²</em></strong></blockquote><p>Down-weight observations with high variance.</p><h3>Generalized Least Squares (GLS)</h3><p>When Var(ε) = σ²Ω (non-spherical errors):</p><blockquote><strong><em>β̂ᴳᴸˢ = (XᵀΩ⁻¹X)⁻¹XᵀΩ⁻¹y</em></strong></blockquote><p>GLS is BLUE when you know the error structure.</p><h3>Practical Decision Guide</h3><h3>Which Method Should I Use?</h3><pre>Start with OLS<br>    │<br>    ├── Works well? → Done!<br>    │<br>    └── Problems?<br>            │<br>            ├── Multicollinearity? → Ridge<br>            │<br>            ├── Too many predictors? → Lasso or Elastic Net<br>            │<br>            ├── Want feature selection? → Lasso<br>            │<br>            ├── Correlated predictors + want sparsity? → Elastic Net<br>            │<br>            ├── Heteroscedasticity? → WLS or robust SE<br>            │<br>            └── Nonlinearity? → Polynomial terms or transformation</pre><h3>Regularization Cheat Sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*youkB9AohhZY9Oo-eCDIiw.png" /></figure><h3>Key Takeaways</h3><ol><li><strong>Multicollinearity</strong> doesn’t bias predictions but destroys interpretability. Detect with VIF &gt; 10 or condition number &gt; 30.</li><li><strong>Bias-variance trade-off</strong> is fundamental: OLS is unbiased but can have high variance. Regularization trades bias for lower variance.</li><li><strong>Ridge</strong> shrinks all coefficients toward zero. Use when you have multicollinearity or want to keep all predictors.</li><li><strong>Lasso</strong> sets some coefficients exactly to zero. Use for feature selection.</li><li><strong>Elastic Net</strong> combines both. Use when you want sparsity with correlated predictors.</li><li><strong>Gradient descent</strong> scales better than the normal equation for large p. SGD scales to massive datasets.</li><li><strong>Always check residuals</strong> — even with fancy methods, diagnostics matter.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56e895399ca8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[stuff on: Linear and Logistic Regression]]></title>
            <link>https://medium.com/@w2sgarnav/stuff-on-linear-and-logistic-regression-7594f0ede574?source=rss-b28212064637------2</link>
            <guid isPermaLink="false">https://medium.com/p/7594f0ede574</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[w2sgarnav]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 14:23:06 GMT</pubDate>
            <atom:updated>2026-01-10T14:23:06.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>maths and concepts</h3><h3>Linear Regression from First Principles: The Mathematical Foundations</h3><p><em>series on Linear and Logistic Regression</em></p><p>Linear regression is the “hello world” of machine learning, but dismissing it as basic would be a mistake. Behind its apparent simplicity lies elegant mathematics, deep geometric intuition, and powerful statistical theory. In this series, we’ll build up both regression techniques from scratch, covering the math you need to actually <em>understand</em> what’s happening — not just plug values into sklearn.</p><p>Let’s begin at the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*WGZGcwRBLvN2wP0h" /></figure><h3>The Regression Problem</h3><p>At its core, regression asks a simple question: given some input variables, can we predict a continuous output?</p><p>Formally, given a dataset <strong>D = {(xᵢ, yᵢ)}</strong> for i = 1 to n, where <strong>xᵢ ∈ ℝᵖ</strong> are feature vectors and <strong>yᵢ ∈ ℝ</strong> are continuous responses, we seek a function <strong>f: ℝᵖ → ℝ</strong> that approximates y well.</p><p>The fundamental assumption is that there exists some true relationship:</p><blockquote><strong><em>y = f(x) + ε</em></strong></blockquote><ul><li><strong>f(x) = E[Y | X = x]</strong> is the <em>regression function</em> (the conditional expectation)</li><li><strong>ε</strong> is random noise with <strong>E[ε] = 0</strong></li></ul><p>This decomposition captures something profound about real data: outcomes are determined partly by systematic, predictable factors (captured by f(x)) and partly by random variation (captured by ε). The error term represents measurement noise, inherent randomness, and the effects of variables we haven’t included.</p><p><strong>Key insight</strong>: No matter how sophisticated our model, some <em>irreducible error</em> will always remain. This is the price we pay for the complexity and randomness inherent in natural phenomena.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*rENka1yzDY5Jy5-m" /></figure><h3>Why Linear Models?</h3><p>Linear models assume that:</p><blockquote><strong><em>f(x) = β₀ + β₁x₁ + β₂x₂ + … + βₚxₚ = xᵀβ</em></strong></blockquote><p>Despite their apparent simplicity, linear models remain the first choice in practice for several compelling reasons:</p><h3>1. Interpretability</h3><p>Each coefficient <strong>βⱼ</strong> represents the change in <strong>E[Y]</strong> for a unit change in <strong>xⱼ</strong>, <em>holding other variables constant</em>. This “all else equal” interpretation is precisely what scientists and decision-makers seek.</p><p>In medicine: “If we increase the dosage by 10mg, how much will the patient’s blood pressure change, on average?”</p><p>Linear models answer this directly.</p><h3>2. Taylor Approximation</h3><p>Any smooth function can be locally approximated by a linear function via first-order Taylor expansion. If the true relationship is reasonably smooth and we’re operating in a limited region, a linear approximation may be quite accurate.</p><p>This is the mathematical justification for why linear models often work well in practice even when the true relationship is nonlinear.</p><h3>3. Computational Tractability</h3><p>Linear models admit closed-form solutions. The OLS estimator can be computed in <strong>O(np²)</strong> time, and gradient-based methods converge reliably because the loss function is convex.</p><h3>4. Statistical Optimality</h3><p>Under certain conditions, linear estimators have optimal properties — the Gauss-Markov theorem guarantees that among all linear unbiased estimators, OLS has minimum variance.</p><h3>5. Foundation for Everything Else</h3><p>Understanding linear regression deeply is essential because many advanced techniques — generalized linear models, mixed effects models, and even neural networks — build upon or generalize these concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*dmczFkWKzQ0VWCXe.jpeg" /></figure><h3>Model Specification</h3><p>The linear regression model specifies:</p><blockquote><strong><em>yᵢ = β₀ + β₁xᵢ₁ + β₂xᵢ₂ + … + βₚxᵢₚ + εᵢ</em></strong><em> for i = 1, …, n</em></blockquote><p>Or in matrix notation:</p><blockquote><strong><em>y = Xβ + ε</em></strong></blockquote><p>where:</p><ul><li><strong>y = (y₁, …, yₙ)ᵀ ∈ ℝⁿ</strong> is the response vector</li><li><strong>X ∈ ℝⁿˣ⁽ᵖ⁺¹⁾</strong> is the design matrix (including intercept column of 1s)</li><li><strong>β = (β₀, β₁, …, βₚ)ᵀ ∈ ℝᵖ⁺¹</strong> is the parameter vector</li><li><strong>ε = (ε₁, …, εₙ)ᵀ ∈ ℝⁿ</strong> is the error vector</li></ul><p>The matrix notation isn’t merely convenient — it reveals the deep linear algebraic structure of regression.</p><h3>The Design Matrix</h3><p>The design matrix <strong>X</strong> has this structure:</p><pre>| 1   x₁₁  x₁₂  ...  x₁ₚ |<br>    | 1   x₂₁  x₂₂  ...  x₂ₚ |<br>X = | .    .    .   .     .  |<br>    | .    .    .    .    .  |<br>    | 1   xₙ₁  xₙ₂  ...  xₙₚ |</pre><p>Each row is an observation, each column (after the first) is a feature. The first column of 1s ensures that <strong>β₀</strong> is added to every prediction — this is sometimes called the “bias” term in ML contexts.</p><p>The design matrix encodes all information about our predictors. Its properties — particularly its rank and the relationships among its columns — fundamentally determine what we can learn from the data.</p><h3>The Geometric Interpretation</h3><p>This is where things get beautiful.</p><p>The fitted values <strong>ŷ = Xβ̂</strong> lie in the <strong>column space</strong> of <strong>X</strong>, denoted <strong>C(X)</strong>. This is a (p+1)-dimensional subspace of <strong>ℝⁿ</strong> (assuming <strong>X</strong> has full column rank).</p><p>The least squares solution finds the point in <strong>C(X)</strong> <strong>closest to y</strong> in Euclidean distance.</p><p>Think of it this way:</p><ol><li>We live in an n-dimensional space (one dimension per observation)</li><li>The response vector <strong>y</strong> is a point in this space</li><li>The column space <strong>C(X)</strong> is a (p+1)-dimensional hyperplane</li><li>Among all points on this hyperplane, we seek the one closest to <strong>y</strong></li><li>Basic geometry tells us this closest point is found by <strong>dropping a perpendicular</strong> from <strong>y</strong> to the hyperplane</li></ol><p>This perpendicular is precisely the residual vector <strong>ε̂ = y — ŷ</strong>.</p><p>This geometric view immediately explains key properties:</p><ul><li>Residuals are orthogonal to fitted values</li><li>Residuals are orthogonal to each predictor column</li><li>Total variation in <strong>y</strong> decomposes into explained variation (along the hyperplane) and unexplained variation (perpendicular to it)</li></ul><h3>The Gauss-Markov Assumptions</h3><p>The validity of statistical inference depends critically on certain assumptions about the data-generating process.</p><h3>A1. Linearity in Parameters</h3><blockquote><strong><em>E[Y | X] = Xβ</em></strong></blockquote><p>Note: This doesn’t require linearity in the original variables — we can include <strong>x²</strong>, <strong>log(x)</strong>, or <strong>x₁·x₂</strong> as predictors, and the model remains linear in <strong>β</strong>.</p><h3>A2. Random Sampling / Exogeneity</h3><blockquote><strong><em>E[εᵢ | X] = 0</em></strong><em> for all i</em></blockquote><p>This is perhaps the most important assumption for causal interpretation. It requires that knowing the values of <strong>X</strong> tells us nothing about the expected value of <strong>ε</strong>.</p><p><strong>Violations occur when:</strong></p><ul><li>Omitted variables are correlated with included predictors</li><li>There is reverse causality</li><li>There is measurement error in predictors</li></ul><p>When this assumption fails, OLS estimates are <strong>biased and inconsistent</strong>.</p><h3>A3. No Perfect Multicollinearity</h3><blockquote><strong><em>rank(X) = p + 1 &lt; n</em></strong></blockquote><p>This technical requirement ensures <strong>XᵀX</strong> is invertible. Perfect multicollinearity occurs when one predictor is an exact linear combination of others.</p><h3>A4. Homoscedasticity</h3><blockquote><strong><em>Var(εᵢ | X) = σ²</em></strong><em> for all i</em></blockquote><p>The spread of errors around the regression line is constant regardless of predictor values.</p><p><strong>Violations (heteroscedasticity) are common</strong>: income variance typically increases with education level; stock return prediction errors increase during volatile periods.</p><p>Heteroscedasticity doesn’t bias coefficient estimates, but it invalidates the usual standard errors and confidence intervals.</p><h3>A5. No Autocorrelation</h3><blockquote><strong><em>Cov(εᵢ, εⱼ | X) = 0</em></strong><em> for all i ≠ j</em></blockquote><p>Errors are uncorrelated with each other. This is particularly relevant for time series data.</p><p><strong>Combining A4 and A5:</strong></p><blockquote><strong><em>Var(ε | X) = σ²Iₙ</em></strong></blockquote><p>This is called <strong>spherical errors</strong>.</p><h3>A6. Normality (for inference)</h3><blockquote><strong><em>ε | X ~ N(0, σ²Iₙ)</em></strong></blockquote><p>Under A1-A6, we have the <strong>Classical Normal Linear Regression Model</strong>:</p><blockquote><strong><em>y | X ~ N(Xβ, σ²Iₙ)</em></strong></blockquote><h3>OLS Estimation and the Gauss-Markov Theorem: Why Least Squares Works</h3><p><em>series on Linear and Logistic Regression</em></p><p>In Part 1, we set up the linear regression problem and discussed why linear models remain powerful despite their simplicity. Now we dive into the mathematics of estimation: how do we actually find the best-fitting line, and why is “least squares” the right criterion?</p><h3>The Least Squares Criterion</h3><p>The method of least squares, developed by Gauss and Legendre in the early 19th century, remains the most common approach to fitting linear models.</p><p>The intuition is straightforward: find the hyperplane that makes the smallest total “error” in predicting our responses.</p><p>But why <em>squared</em> errors? Several compelling reasons:</p><ol><li><strong>Mathematical tractability</strong>: Squared errors yield a smooth, differentiable objective with a unique global minimum (when <strong>X</strong> has full rank)</li><li><strong>Statistical optimality</strong>: Under normally distributed errors, minimizing squared errors is equivalent to maximum likelihood estimation</li><li><strong>Geometric interpretation</strong>: Minimizing squared errors corresponds to finding the orthogonal projection onto <strong>C(X)</strong></li><li><strong>Penalizing large errors</strong>: Squaring amplifies the penalty for large deviations</li></ol><h3>The Residual Sum of Squares</h3><p>The <strong>Residual Sum of Squares (RSS)</strong> is:</p><blockquote><strong><em>RSS(β) = Σᵢ(yᵢ — ŷᵢ)² = ‖y — Xβ‖² = (y — Xβ)ᵀ(y — Xβ)</em></strong></blockquote><p>The RSS is a <strong>quadratic function</strong> of <strong>β</strong> — it forms a paraboloid in parameter space. This convexity guarantees that any local minimum is the global minimum.</p><p>The OLS estimator minimizes the RSS:</p><blockquote><strong><em>β̂_OLS = argmin RSS(β)</em></strong></blockquote><h3>Derivation of the Normal Equations</h3><p>Let’s derive the OLS estimator through calculus — differentiating RSS with respect to <strong>β</strong> and setting the result to zero.</p><p><strong>Step 1: Expand the RSS</strong></p><pre>RSS(β) = (y - Xβ)ᵀ(y - Xβ)<br>       = yᵀy - yᵀXβ - βᵀXᵀy + βᵀXᵀXβ<br>       = yᵀy - 2βᵀXᵀy + βᵀXᵀXβ</pre><p>(Note: <strong>yᵀXβ</strong> is a scalar, so it equals its transpose <strong>βᵀXᵀy</strong>)</p><p><strong>Step 2: Take the gradient</strong></p><blockquote><strong><em>∂RSS/∂β = -2Xᵀy + 2XᵀXβ</em></strong></blockquote><p><strong>Step 3: Set to zero (first-order condition)</strong></p><blockquote><strong><em>XᵀXβ̂ = Xᵀy</em></strong></blockquote><p>These are the <strong>normal equations</strong>.</p><p><strong>Step 4: Solve</strong></p><p>If <strong>XᵀX</strong> is invertible:</p><blockquote><strong><em>β̂ = (XᵀX)⁻¹Xᵀy</em></strong></blockquote><p><strong>Step 5: Verify it’s a minimum</strong></p><p>The Hessian is <strong>∂²RSS/∂β∂βᵀ = 2XᵀX</strong>, which is positive semi-definite, confirming this is indeed a minimum.</p><h3>Understanding the Normal Equations</h3><p>The normal equations <strong>XᵀXβ̂ = Xᵀy</strong> have a beautiful interpretation:</p><p><strong>The residual vector (y — Xβ̂) must be orthogonal to every column of X.</strong></p><p>This orthogonality condition is both necessary and sufficient for optimality — it’s the geometric translation of “dropping a perpendicular.”</p><h3>The Hat Matrix</h3><p>The hat matrix provides deep geometric insight into regression mechanics.</p><p>The <strong>hat matrix</strong> (or projection matrix) is:</p><blockquote><strong><em>H = X(XᵀX)⁻¹Xᵀ</em></strong></blockquote><p>It “puts the hat on <strong>y</strong>“: <strong>ŷ = Hy</strong></p><p>The hat matrix linearly transforms observed responses into fitted values. Each fitted value <strong>ŷᵢ</strong> is a weighted average of all observed responses, with weights determined by row <strong>Hᵢ</strong>.</p><h3>Properties of the Hat Matrix</h3><ol><li><strong>Symmetric</strong>: <strong>Hᵀ = H</strong></li><li><strong>Idempotent</strong>: <strong>H² = H</strong></li><li><strong>Trace</strong>: <strong>tr(H) = p + 1</strong> (number of parameters)</li><li><strong>Eigenvalues</strong>: All eigenvalues are 0 or 1</li><li><strong>Range</strong>: <strong>R(H) = C(X)</strong></li></ol><p><strong>Proof of idempotency:</strong></p><pre>H² = X(XᵀX)⁻¹Xᵀ · X(XᵀX)⁻¹Xᵀ<br>   = X(XᵀX)⁻¹(XᵀX)(XᵀX)⁻¹Xᵀ<br>   = X(XᵀX)⁻¹Xᵀ <br>   = H</pre><p>The idempotency property confirms that <strong>H</strong> is a <strong>projection matrix</strong>. Applying the projection twice gives the same result as applying it once — once you’re on the subspace, you stay there.</p><h3>Leverage</h3><p>The diagonal element <strong>hᵢᵢ</strong> measures how much observation i influences its own fitted value — this is the <strong>leverage</strong> of observation i.</p><blockquote><strong><em>hᵢᵢ = xᵢᵀ(XᵀX)⁻¹xᵢ</em></strong></blockquote><p>Properties:</p><ul><li><strong>1/n ≤ hᵢᵢ ≤ 1</strong></li><li><strong>Σhᵢᵢ = p + 1</strong></li><li>Average leverage: <strong>h̄ = (p+1)/n</strong></li></ul><p><strong>High leverage points</strong> (hᵢᵢ &gt; 2h̄ or hᵢᵢ &gt; 3h̄) have unusual predictor values and disproportionately influence the fit.</p><h3>The Residual Maker Matrix</h3><p>Just as the hat matrix creates fitted values, the <strong>residual maker matrix</strong> creates residuals:</p><blockquote><strong><em>ε̂ = y — ŷ = y — Hy = (I — H)y = My</em></strong></blockquote><p>where <strong>M = I — H</strong> is the residual maker matrix.</p><p><strong>Properties:</strong></p><ul><li><strong>M</strong> is symmetric and idempotent</li><li><strong>MX = 0</strong> (residuals are orthogonal to predictors)</li><li><strong>tr(M) = n — p — 1</strong> (degrees of freedom for residuals)</li><li><strong>HM = MH = 0</strong></li></ul><h3>Orthogonality Conditions</h3><p>The OLS estimator satisfies:</p><blockquote><strong><em>Xᵀε̂ = Xᵀ(y — Xβ̂) = 0</em></strong></blockquote><p>This means:</p><ul><li><strong>Σε̂ᵢ = 0</strong> (residuals sum to zero)</li><li><strong>Σxᵢⱼε̂ᵢ = 0</strong> for each predictor j</li></ul><h3>Statistical Properties of OLS</h3><h3>Unbiasedness</h3><p><strong>Theorem</strong>: Under assumptions A1-A3, the OLS estimator is unbiased:</p><blockquote><strong><em>E[β̂ | X] = β</em></strong></blockquote><p><strong>Proof:</strong></p><pre>E[β̂ | X] = E[(XᵀX)⁻¹Xᵀy | X]<br>         = (XᵀX)⁻¹XᵀE[y | X]<br>         = (XᵀX)⁻¹XᵀXβ    (since E[y|X] = Xβ)<br>         = β  ∎</pre><h3>Variance-Covariance Matrix</h3><p>Knowing the estimator is unbiased tells us that <em>on average</em> we get the right answer. But how much will estimates vary from sample to sample?</p><p><strong>Theorem</strong>: Under assumptions A1-A5:</p><blockquote><strong><em>Var(β̂ | X) = σ²(XᵀX)⁻¹</em></strong></blockquote><p>This is profound. The variance depends on:</p><ul><li>The noise level <strong>σ²</strong> (more noise → more uncertainty)</li><li>The structure of predictors through <strong>(XᵀX)⁻¹</strong></li></ul><p>The matrix <strong>XᵀX</strong> is sometimes called the <strong>information matrix</strong> because it captures how much information the predictors provide about the parameters.</p><p><strong>Proof:</strong></p><pre>Var(β̂ | X) = Var((XᵀX)⁻¹Xᵀy | X)<br>           = (XᵀX)⁻¹Xᵀ Var(y | X) X(XᵀX)⁻¹<br>           = (XᵀX)⁻¹Xᵀ(σ²I)X(XᵀX)⁻¹<br>           = σ²(XᵀX)⁻¹  ∎</pre><h3>The Gauss-Markov Theorem</h3><p>This is one of the crown jewels of statistical theory — a powerful justification for using OLS.</p><p><strong>Theorem (Gauss-Markov)</strong>: Under assumptions A1-A5, the OLS estimator <strong>β̂</strong> is the <strong>Best Linear Unbiased Estimator (BLUE)</strong>. Among all linear unbiased estimators of <strong>β</strong>, OLS has the smallest variance.</p><p>Let’s unpack this:</p><ul><li><strong>Linear</strong>: The estimator is a linear function of <strong>y</strong></li><li><strong>Unbiased</strong>: <strong>E[β̂] = β</strong></li><li><strong>Best</strong>: Smallest variance among all estimators satisfying the above</li></ul><p><strong>Proof sketch:</strong></p><p>Let <strong>β̃ = Cy</strong> be any other linear unbiased estimator. Write <strong>C = (XᵀX)⁻¹Xᵀ + D</strong> for some matrix <strong>D</strong>.</p><p>For unbiasedness: <strong>E[β̃ | X] = CXβ = β</strong> requires <strong>CX = I</strong>, which means <strong>DX = 0</strong>.</p><p>The variance:</p><pre>Var(β̃ | X) = σ²CCᵀ = σ²(XᵀX)⁻¹ + σ²DDᵀ</pre><p>(Cross terms vanish because <strong>DX = 0</strong>)</p><p>Since <strong>DDᵀ</strong> is positive semi-definite:</p><blockquote><strong><em>Var(β̃ | X) ≥ Var(β̂ | X)</em></strong></blockquote><p>with equality iff <strong>D = 0</strong>. ∎</p><h3>Important Caveats</h3><p>The theorem does <strong>not</strong> say OLS is the best estimator overall:</p><ul><li>Biased estimators (like ridge regression) can achieve lower mean squared error by trading bias for variance reduction</li><li>Nonlinear estimators aren’t covered</li></ul><h3>Estimating σ²</h3><p>To conduct inference, we need to estimate <strong>σ²</strong>. We can’t simply compute the sample variance of residuals — residuals systematically underestimate true errors because the fitted line passes closer to observed points than the true line.</p><p><strong>Theorem</strong>: Under A1-A5, an unbiased estimator of σ² is:</p><blockquote><strong><em>σ̂² = s² = RSS/(n — p — 1) = ε̂ᵀε̂/(n — p — 1)</em></strong></blockquote><p>The denominator <strong>n — p — 1</strong> is the <strong>degrees of freedom for error</strong>. We divide by this (not n) because we’ve “used up” p+1 degrees of freedom estimating coefficients.</p><p><strong>Proof:</strong></p><p>We need to show <strong>E[ε̂ᵀε̂ | X] = (n — p — 1)σ²</strong>.</p><p>Note that <strong>ε̂ = My = M(Xβ + ε) = Mε</strong> (since <strong>MX = 0</strong>).</p><pre>E[ε̂ᵀε̂ | X] = E[εᵀMᵀMε | X] = E[εᵀMε | X]<br>            = E[tr(εᵀMε) | X] = E[tr(Mεεᵀ) | X]<br>            = tr(M·E[εεᵀ | X]) = tr(M·σ²I)<br>            = σ²·tr(M) = σ²(n - p - 1)  ∎</pre><h3>Distribution Theory and Inference</h3><p>Under the full Classical Normal Linear Model (A1-A6), we get exact distributional results.</p><h3>Distribution of OLS Estimator</h3><blockquote><strong><em>β̂ | X ~ N(β, σ²(XᵀX)⁻¹)</em></strong></blockquote><p>This follows because <strong>β̂</strong> is a linear transformation of normally distributed <strong>y</strong>.</p><h3>Testing Individual Coefficients</h3><p>To test <strong>H₀: βⱼ = βⱼ⁰</strong> vs <strong>H₁: βⱼ ≠ βⱼ⁰</strong>:</p><blockquote><strong><em>t = (β̂ⱼ — βⱼ⁰) / SE(β̂ⱼ) ~ t_{n-p-1}</em></strong></blockquote><p>where <strong>SE(β̂ⱼ) = s·√[(XᵀX)⁻¹]ⱼⱼ</strong></p><h3>Confidence Intervals</h3><p>A (1-α) confidence interval for βⱼ:</p><blockquote><strong><em>β̂ⱼ ± t_{α/2, n-p-1} · SE(β̂ⱼ)</em></strong></blockquote><h3>F-Test for Overall Significance</h3><p>To test <strong>H₀: β₁ = β₂ = … = βₚ = 0</strong>:</p><blockquote><strong><em>F = [(TSS — RSS)/p] / [RSS/(n-p-1)] ~ F_{p, n-p-1}</em></strong></blockquote><p>Equivalently:</p><blockquote><strong><em>F = [R²/p] / [(1-R²)/(n-p-1)]</em></strong></blockquote><h3>Model Evaluation: R² and Friends</h3><h3>Decomposition of Variance</h3><blockquote><strong><em>TSS = ESS + RSS</em></strong></blockquote><p>where:</p><ul><li><strong>TSS = Σ(yᵢ — ȳ)²</strong> — Total Sum of Squares</li><li><strong>ESS = Σ(ŷᵢ — ȳ)²</strong> — Explained Sum of Squares</li><li><strong>RSS = Σ(yᵢ — ŷᵢ)²</strong> — Residual Sum of Squares</li></ul><h3>Coefficient of Determination</h3><blockquote><strong><em>R² = 1 — RSS/TSS = ESS/TSS</em></strong></blockquote><p>Properties:</p><ul><li><strong>0 ≤ R² ≤ 1</strong></li><li><strong>R²</strong> equals the squared correlation between <strong>y</strong> and <strong>ŷ</strong></li><li>Adding variables <strong>never</strong> decreases R² (this is a problem!)</li></ul><h3>Adjusted R²</h3><p>To penalize model complexity:</p><blockquote><strong><em>R̄² = 1 — (1 — R²)·(n-1)/(n-p-1)</em></strong></blockquote><h3>Looking Ahead</h3><p>We’ve covered the core theory of OLS estimation. In the next post, we’ll explore:</p><ul><li><strong>Regularization</strong>: Ridge, Lasso, and Elastic Net — when OLS isn’t enough</li><li><strong>Optimization</strong>: Gradient descent and when the normal equation fails</li><li><strong>Multicollinearity</strong>: The bane of regression and how to detect it</li></ul><p>Then we’ll pivot to logistic regression, extending these ideas to classification.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7594f0ede574" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>