<?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 Saurabh Agarwal on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Agarwal on Medium]]></description>
        <link>https://medium.com/@som54654?source=rss-6a91ebe98117------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mtX9RHbL7pV0VaYi</url>
            <title>Stories by Saurabh Agarwal on Medium</title>
            <link>https://medium.com/@som54654?source=rss-6a91ebe98117------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:27:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@som54654/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[Linear Regression: Everything You Need to Know — And Why]]></title>
            <link>https://medium.com/@som54654/linear-regression-everything-you-need-to-know-and-why-4ca30eff3955?source=rss-6a91ebe98117------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ca30eff3955</guid>
            <dc:creator><![CDATA[Saurabh Agarwal]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 20:37:43 GMT</pubDate>
            <atom:updated>2026-03-16T20:44:43.674Z</atom:updated>
            <content:encoded><![CDATA[<p>Most explanations of linear regression hand you a formula, list the assumptions in bullet points, and call it done. You walk away able to recite the conditions but with no idea what actually breaks when you violate them, why the loss function is squared and not something else, or what the math is actually doing. This is the article that answers those questions.</p><p>Every assumption comes with what breaks when you violate it — and why, precisely. Every equation is grounded in geometry or probability, not dropped from the sky. Every question a careful reader would naturally ask is addressed in the flow, because those questions are the ones that lead to real understanding.</p><p>What is covered: what linear regression is, why it still matters in a world of neural networks and LLMs, the assumptions and the full reasoning behind each one, how the optimization works and why squared errors are the right choice, and a deep dive into multicollinearity — one of the most misunderstood topics in applied regression.</p><p>Linear regression fits a line — or more generally, a hyperplane — that describes the relationship between one or more input variables and an output variable. The mathematical form is:</p><pre>y = β₀ + β₁x₁ + β₂x₂ + ... + βₚxₚ + ε</pre><ul><li><strong>y</strong> — the outcome you are trying to explain or predict (the dependent variable)</li><li><strong>x₁, x₂, …, xₚ</strong> — the inputs used to explain it (the independent variables)</li><li><strong>β₀</strong> — the intercept: the expected value of y when all inputs are zero</li><li><strong>β₁, …, βₚ</strong> — the slopes: how much y changes per unit change in each input, holding everything else constant</li><li><strong>ε</strong> — the error term: everything about y that the inputs do not explain</li></ul><p>In matrix notation, the same model is written compactly as:</p><pre>y = Xβ + ε</pre><p>Where <strong>X</strong> is the n×(p+1) design matrix — a leading column of ones for the intercept, followed by the predictor columns. <strong>β</strong> is the (p+1)×1 coefficient vector. <strong>y</strong> is the n×1 response vector.</p><blockquote>“Linear” Means Linear in the Parameters — <strong>NOT</strong> in the Inputs</blockquote><p>This distinction matters and most introductions skip it.</p><p>The model is called linear because the coefficients β enter linearly — not because the relationship between x and y must be a straight line. You can include x², log(x), or x₁·x₂ as inputs and it is still linear regression, because β still enters as a simple multiplier.</p><p>What makes a model <em>nonlinear</em> is when the coefficients themselves appear inside exponents or products:</p><pre>Linear: y = β₀ + β₁x + β₂x² ← β enters as multiplier, <br>x² is just a feature Nonlinear: y = β₀ · exp(β₁x) ← β₁ is inside the exponent</pre><p>Any transformation of x you can compute <em>before</em> fitting is fair game. The linearity constraint is entirely on how β enters the equation. This matters practically: if you suspect y grows with the square of x, include x² as a predictor. You do not need a different model — you need a different feature.</p><p>Before going further, clear up a misconception that causes confusion throughout this subject.</p><blockquote>“Independent variables are called ‘independent’ not because they are statistically independent of each other — they often are not — but because in experimental thinking, we vary them independently to observe their effect on the outcome.”</blockquote><p>The name comes from experimental design philosophy, not from any statistical independence guarantee. In fact, one of the core problems in regression — multicollinearity — is precisely the situation where the inputs are correlated with each other. Calling them “independent” is a naming convention from the history of experimental science. Treat it as such and nothing more.</p><p>Fair question. Gradient-boosted trees outperform it on most tabular benchmarks. Neural networks model complexity that no line could capture. So why does a method from 1805 remain worth learning deeply?</p><p>Three reasons — and none of them is “because it is easy.”</p><p>The coefficient β₁ tells you the <strong>expected change in y for a one-unit increase in x₁, holding all other variables constant</strong>. This is the <em>ceteris paribus</em> interpretation — isolating the marginal effect of one variable while everything else stays fixed.</p><p>No other widely used model provides this directly. A gradient-boosted tree may predict well, but it cannot tell you cleanly how much a one-year increase in education changes expected salary, holding experience and industry constant. A neural network learns a high-dimensional nonlinear function with no interpretable summary per variable. Linear regression gives you a number with a direction, a magnitude, and a formal measure of uncertainty around it.</p><p>One clarification worth making now: the coefficient tells you the <strong>marginal effect</strong> — not how much of the variance in y a variable explains. Explaining variance is R²’s job. A variable can have a large coefficient and a small R² (big effect, noisy relationship) or a small coefficient and a large R² (tight relationship, small scale). The coefficient and R² are answering different questions. Conflating them is a common mistake.</p><p>The intercept β₀ is the expected value of y when all predictors are zero. Whether that is meaningful depends entirely on context.</p><p><strong>When it is not meaningful:</strong> A model predicting house prices from square footage. The intercept is the expected price of a house with zero square footage. Mathematically defined, practically absurd. It serves as a mathematical anchor that ensures the line fits correctly across the range of real data — but has no direct interpretation worth reporting.</p><p><strong>When it is meaningful:</strong> A model predicting exam scores where x is hours studied. The intercept is the expected score for a student who studied zero hours — the baseline score from prior knowledge alone. Interpretable and useful.</p><p><strong>When it is the whole point:</strong> In an A/B test with a binary variable (0 = control, 1 = treatment), the intercept is the expected outcome in the control group. The coefficient on the treatment variable is the average treatment effect — the lift. Both are directly interpretable and are the quantities of interest.</p><p>The rule: always ask whether x = 0 lies within or near the range of your data before interpreting the intercept. If it does not, β₀ is extrapolation.</p><p>One of the most underused applications of linear regression in industry is measuring the effect of a treatment or intervention. Include a binary indicator variable (0 = control, 1 = treatment) in a regression and the coefficient on that indicator is the <strong>average treatment effect</strong> — the lift. The t-statistic on that coefficient gives you the statistical significance of the effect.</p><p>This is regression applied as a hypothesis test. It is used constantly in A/B testing, policy evaluation, and campaign measurement. The regression framework allows you to control for other variables simultaneously — something a simple comparison of means cannot do. By including pre-treatment covariates, you reduce residual variance and increase the precision of the treatment effect estimate.</p><p>Here is where most treatments fail. They list the assumptions without explaining what each one protects against. If you do not know what breaks and why, you cannot diagnose problems or choose the right fix.</p><p>The relationship between y and x must be linear in the parameters. This is the most fundamental assumption and the one most often left implicit.</p><p>If the true relationship is exponential and you fit a line, the predictions will be systematically wrong across the range of x. The line will underpredict in some regions and overpredict in others in a consistent, patterned way. No amount of data, careful estimation, or tuning repairs a misspecified functional form.</p><p><strong>How to check:</strong> Plot residuals against each predictor and against fitted values. If the relationship is linear, residuals should scatter randomly around zero with no pattern. A curved pattern — residuals positive at low x, negative in the middle, positive again at high x — is the signature of a missing nonlinear term.</p><p><strong>The fix:</strong> Include the appropriate transformation of x. If residuals show a quadratic curve, add x². If residuals suggest diminishing returns, try log(x).</p><p>Each observation must carry independent information. The errors must be uncorrelated: knowing the error for observation i should tell you nothing about the error for observation j.</p><p><strong>What breaks — the full derivation:</strong></p><p>The OLS variance formula is:</p><pre>Var(β̂) = σ²(XᵀX)⁻¹</pre><p>To see where this comes from, recall:</p><pre>β̂ = β + (XᵀX)⁻¹Xᵀε</pre><p>β is a fixed constant. Variance of a constant plus a random quantity equals the variance of the random quantity alone. Using the rule Var(Az) = A·Var(z)·Aᵀ for constant matrix A = (XᵀX)⁻¹Xᵀ:</p><pre>Var(β̂) = (XᵀX)⁻¹Xᵀ · E[εεᵀ] · X(XᵀX)⁻¹</pre><p>Under the assumption that errors are uncorrelated with constant variance, E[εεᵀ] = σ²I — a diagonal matrix with σ² on the diagonal and zeros everywhere else. This simplifies to:</p><pre>Var(β̂) = σ²(XᵀX)⁻¹</pre><p>When errors are autocorrelated, E[εεᵀ] = σ²Ω where Ω has non-zero off-diagonal entries — correlations between errors. The true variance of β̂ becomes:</p><pre>True Var(β̂) = σ²(XᵀX)⁻¹XᵀΩX(XᵀX)⁻¹</pre><p>OLS reports σ²(XᵀX)⁻¹, ignoring Ω entirely. With positive autocorrelation — consecutive errors tend to share the same sign — the true variance is larger than what OLS reports.</p><p><strong>The effective sample size intuition:</strong></p><p>Suppose you collect 100 daily temperature readings to estimate a trend. If today is hot, tomorrow is probably also hot. Your 100 observations do not carry 100 independent pieces of information — they might carry the effective information of 20 independent observations, because consecutive readings are telling you the same story. The OLS formula assumes n = 100 independent observations. It produces a falsely small variance, falsely small standard errors, inflated t-statistics, and declared significance where there is none.</p><p><strong>An important and precise distinction:</strong> autocorrelation does not cause bias. The OLS point estimate β̂ is still correct on average — E[β̂] = β — as long as E[ε|X] = 0 holds. What is destroyed is the uncertainty quantification: the standard errors, confidence intervals, and p-values. The value of the estimate survives. The inference around it does not.</p><p>The variance of the errors must be the same across all observations. Formally: Var(εᵢ) = σ² for all i.</p><p><strong>Two distinct mechanisms cause non-constant variance:</strong></p><p>The first and most common: variance scales with the level of x. Consider income and discretionary spending. Low-income households have constrained, predictable spending — little room for variation. High-income households have wildly variable spending. As income rises, the spread of errors fans out. On a residual plot, this produces the classic cone or fan shape: tight residuals at low fitted values, wide residuals at high fitted values.</p><p>The second: some observations are inherently noisier due to measurement conditions or data collection methodology. The noisiness is systematic — tied to something observable — not purely random scatter.</p><p><strong>What breaks — and exactly why:</strong></p><p>The standard error formula σ²(XᵀX)⁻¹ uses a single σ² for all observations. If different observations have different variances σᵢ², the true variance of β̂ is:</p><pre>True Var(β̂) = (XᵀX)⁻¹Xᵀ · diag(σ₁², σ₂², ..., σₙ²) · X(XᵀX)⁻¹</pre><p>OLS plugs in a single estimated σ² and reports σ²(XᵀX)⁻¹. This is wrong. The computed standard errors do not reflect reality. All hypothesis tests and confidence intervals built on those standard errors are unreliable.</p><p>Additionally, OLS is inefficient under heteroscedasticity. A noisy observation with high variance carries little reliable information about the true line — it should have less influence on the estimated coefficients. Equal weighting ignores this structure.</p><p><strong>Critical point:</strong> heteroscedasticity does not bias the coefficients. As long as E[ε|X] = 0 holds, β̂ is still correct on average. The damage is entirely to the standard errors and everything that depends on them.</p><p><strong>How to detect it:</strong></p><p><em>Visually:</em> Plot residuals against fitted values. A fan shape — residuals spreading out as fitted values increase — is the signature of heteroscedasticity.</p><p><em>Formally:</em> The Breusch-Pagan test regresses the squared residuals eᵢ² on the predictors and tests whether any predictor significantly explains the variation in squared residuals. A significant result confirms heteroscedasticity.</p><p><strong>Three fixes, in order of complexity:Fix 1 — Robust Standard Errors (the first thing to try):</strong></p><p>The simplest and most common fix in practice. You keep the OLS coefficients exactly as they are — they are still unbiased — and replace the standard error formula with one that is valid under heteroscedasticity.</p><p>The true variance under heteroscedasticity requires knowing σᵢ² for each observation. You do not know them, but you can estimate each with the squared residual eᵢ²:</p><pre>Robust Var(β̂) = (XᵀX)⁻¹Xᵀ · diag(e₁², e₂², ..., eₙ²) · X(XᵀX)⁻¹</pre><p>This is called the <strong>sandwich estimator</strong> — (XᵀX)⁻¹ on the outside, the meat diag(eᵢ²) in the middle — or White’s heteroscedasticity-consistent (HC) standard errors. The coefficients do not change. Only the standard errors are corrected. This gives valid t-tests and confidence intervals without requiring you to model the variance structure explicitly.</p><p><strong>Fix 2 — Log Transformation of y:</strong></p><p>When variance grows proportionally with the level of y — exactly the fan shape — a log transformation of the response often stabilizes the variance completely.</p><p>If the true relationship is multiplicative:</p><pre>y = exp(β₀ + β₁x₁ + ... + βₚxₚ + ε) where ε ~ N(0, σ²)</pre><p>Taking logarithms:</p><pre>log(y) = β₀ + β₁x₁ + ... + βₚxₚ + ε</pre><p>Now log(y) follows the standard linear model with constant error variance. The fan shape disappears because a percentage change in y translates to an additive change in log(y) — stabilizing multiplicative variance.</p><p>The interpretation of coefficients changes: β₁ is now the expected change in log(y) per unit increase in x₁, which approximately equals the <strong>percentage change in y</strong>. A coefficient of 0.05 means a one-unit increase in x₁ is associated with approximately a 5% increase in y. This interpretation is often more natural for quantities like income, price, or count data.</p><p><strong>Fix 3 — Weighted Least Squares (WLS):</strong></p><p>When you have a model for how variance changes — from theory or from a diagnostic regression of eᵢ² on predictors — assign each observation a weight wᵢ = 1/σᵢ²:</p><pre>L(β) = Σᵢ wᵢ(yᵢ − xᵢᵀβ)²</pre><p>This downweights noisy observations and upweights precise ones. WLS recovers the BLUE property (Best Linear Unbiased Estimator) that OLS loses under heteroscedasticity.</p><p>The common misstatement: “the data must be normally distributed.” The correct statement: <strong>the errors must be normally distributed</strong>. Not x. Not y unconditionally. The errors.</p><p>Formally: εᵢ ~ N(0, σ²).</p><p><strong>Why these are the same thing stated differently:</strong></p><p>If εᵢ ~ N(0, σ²) and yᵢ = xᵢᵀβ + εᵢ, then for a specific observed xᵢ, the term xᵢᵀβ is a fixed number. Adding a fixed number to a normal random variable shifts its mean but does not change the shape:</p><pre>yᵢ | xᵢ ~ N(xᵢᵀβ, σ²)</pre><p>“Errors are normally distributed with mean 0” and “y given X is normally distributed with mean Xβ” are the same statement from two different angles. The distribution of x is irrelevant.</p><p><strong>Why this assumption is needed:</strong></p><p>It is required for exact t-tests and F-tests in finite samples. If ε is normal, β̂ is normal:</p><pre>β̂ ~ N(β, σ²(XᵀX)⁻¹)</pre><p>The t-statistic β̂ⱼ/SE(β̂ⱼ) follows a t-distribution with n−p−1 degrees of freedom exactly. This is what gives you correct p-values and confidence intervals in small samples.</p><p><strong>What happens with non-normal errors:</strong></p><p>The coefficients β̂ are still unbiased. Normality of errors is not required for E[β̂] = β. What breaks is the exact distributional claim about β̂.</p><p>For large samples, the Central Limit Theorem rescues you. β̂ is a linear combination of many observations. By the CLT, such combinations converge to normality regardless of the distribution of individual terms — even if εᵢ is skewed or heavy-tailed. This is what “asymptotically normal” means: converging to normality as n → ∞. In practice, with n in the hundreds or thousands, the approximation is usually adequate.</p><p>In small samples with non-normal errors, use <strong>bootstrap confidence intervals</strong>: resample your data with replacement many times, refit the model on each resample, and build confidence intervals from the empirical distribution of β̂ across resamples. No distributional assumption required. Bootstrap CIs can be asymmetric — which is more honest when the sampling distribution is skewed.</p><p>No predictor can be a perfect linear combination of other predictors. This is the minimum requirement for OLS to have a unique solution at all. The practical concern — no near-perfect multicollinearity — is stronger and more important. It deserves its own section.</p><p>Multicollinearity is the condition where predictors in the model are correlated with each other. State the most important practical point clearly upfront:</p><blockquote><strong><em>Multicollinearity is not a problem unless you want to interpret the individual coefficients.</em></strong></blockquote><p>If the goal is prediction — getting accurate ŷ — multicollinearity among predictors does not harm predictive performance. The model R² is unaffected. The fitted values ŷ are still valid. The moment you want to isolate the effect of one variable holding others constant, multicollinearity becomes a serious problem. Know which goal you have before diagnosing or treating it.</p><p>The coefficient β₁ is defined as: the expected change in y for a one-unit increase in x₁, <strong>holding all other variables constant</strong>. That “holding constant” clause is the entire basis of the interpretation.</p><p>If x₁ and x₂ are highly correlated, holding x₂ constant while varying x₁ is a scenario that essentially never occurs in your data. The model is being asked to estimate an effect it has never directly observed. It cannot do so reliably.</p><p>An intuitive first thought: the explanatory power is “split” between correlated variables. The problem is more severe than that.</p><p>Consider x₁ and x₂ that are nearly perfectly correlated. The model could assign all credit to x₁ (β₁ = 5, β₂ = 0), all to x₂ (β₁ = 0, β₂ = 5), or any combination (β₁ = 3, β₂ = 2) — all produce nearly identical fitted values and nearly identical SSE. There is no unique answer. The coefficients are <strong>indeterminate</strong>.</p><p>“Split” implies one specific answer exists. The problem is there is no unique answer at all.</p><p>This indeterminacy drives the variance up. Because many β values fit the data nearly equally well, different samples will settle on different values. Across repeated samples, β̂ swings wildly. That instability is high variance — the direct mechanism linking multicollinearity to unreliable coefficients.</p><p><strong>On R² and individual contributions:</strong> the total model R² is valid and unaffected by multicollinearity. What breaks is the attribution of explanatory power to individual predictors. When predictors share information, the total credit cannot be cleanly allocated. The total is correct; the individual shares are ambiguous. This is why a significant F-test combined with all non-significant t-tests is the classic fingerprint of multicollinearity.</p><p><strong>Structural multicollinearity</strong> is an artifact of model construction, not a property of the underlying data. Including x and x² creates correlation by design — large x means large x². Including interaction terms x₁·x₂ creates correlation with the main effects. The data itself may be clean; the model formulation introduced the problem. This type can often be reduced by centering.</p><p><strong>Data multicollinearity</strong> is present in the raw data regardless of model design. Income and education are correlated in the world. Height and weight are correlated. No model redesign removes this — the correlation is in the data generating process. Requires a different remedy.</p><p>VIF for predictor j measures exactly how much the variance of β̂_j is inflated by its correlation with the other predictors.</p><p><strong>How VIF is computed:</strong></p><p>Step 1: Regress xⱼ on all other predictors. Get R²_j — how well the other predictors explain xⱼ.</p><p>Step 2: VIF_j = 1 / (1 − R²_j)</p><p><strong>Interpretation:</strong></p><ul><li>R²_j = 0 → VIF = 1. No inflation. Ideal.</li><li>R²_j = 0.5 → VIF = 2. Moderate — usually acceptable.</li><li>R²_j = 0.9 → VIF = 10. 90% of xⱼ explained by others. Borderline problematic.</li><li>R²_j = 0.99 → VIF = 100. Near-perfect multicollinearity.</li></ul><p><strong>Why 10 is the conventional threshold:</strong> VIF = 10 corresponds to R²_j = 0.9. At this level, the standard error of β̂_j is √10 ≈ 3.16 times larger than it would be if xⱼ were uncorrelated with everything else. That is the conventional point where the inflation is considered harmful enough to act on. A rule of thumb, not a theorem.</p><p><strong>The direct connection between VIF and variance:</strong></p><p>From the Frisch-Waugh-Lovell theorem:</p><pre>Var(β̂_j) = σ² / [Sⱼⱼ · (1 − R²_j)] = (σ²/Sⱼⱼ) × VIF_j</pre><p>Where Sⱼⱼ = Σᵢ(xᵢⱼ − x̄ⱼ)² is the total variation in predictor j. The denominator Sⱼⱼ(1 − R²_j) is the residual variation in xⱼ that is orthogonal to all other predictors — the only variation OLS can use to estimate β̂_j. Multicollinearity eats into this signal. VIF measures exactly how much.</p><p>If VIF_j = 10, the variance is exactly 10× what it would be in the orthogonal world. Standard error is √10 ≈ 3.16× larger. That is the definition.</p><p>As n grows, Sⱼⱼ grows — you are summing more terms. The denominator in Var(β̂_j) grows. Variance shrinks. A large dataset can produce precise coefficient estimates even under high VIF.</p><blockquote><strong><em>Multicollinearity is more of a small-sample problem than a large-sample problem</em></strong><em> — in terms of estimation precision.</em></blockquote><p>But interpretability does not recover with scale. Even with a precisely estimated coefficient, β̂_j still represents “the effect of xⱼ holding all other correlated variables constant” — a counterfactual that may never occur in your data. Coefficients also remain sensitive to model specification: adding or removing a correlated variable can swing the remaining coefficients substantially, regardless of n.</p><p><strong>The nuanced summary:</strong> high VIF with small n is a double problem — imprecise estimates and uninterpretable coefficients. High VIF with large n: estimation precision recovers; interpretability remains a genuine concern. VIF is not a death sentence with large n, but it is always an interpretability warning.</p><p>When two predictors are perfectly correlated — say x₂ = 2x₁ — the design matrix X has linearly dependent columns. The matrix XᵀX is <strong>singular</strong>: its determinant is zero and its inverse does not exist. OLS has no unique solution.</p><p><strong>Concrete example:</strong> Let x₁ = [1, 2, 3] and x₂ = [2, 4, 6]:</p><pre>X = | 1 1 2 | | 1 2 4 | | 1 3 6 |</pre><p>Column 3 is exactly 2× column 2. XᵀX inherits this dependency. Determinant = 0. No inverse. Infinitely many β vectors produce identical fitted values.</p><p>With near-perfect multicollinearity, XᵀX is technically invertible but numerically unstable — its determinant is close to zero, its inverse has enormous values, and tiny changes in the data cause large swings in β̂. This is an <strong>ill-conditioned</strong> matrix.</p><p><strong>1. Centering — for structural multicollinearity only</strong></p><p>Subtract the mean from each variable before constructing derived terms. Centering reduces correlation between odd and even powers: (x − x̄) and (x − x̄)² are far less correlated than x and x², because the centered term alternates sign while the squared term is always non-negative.</p><p><em>Why centering does NOT help with same-parity pairs:</em> (x − x̄)² and (x − x̄)⁴ remain correlated regardless of centering — one is a monotone function of the other. And centering does nothing for data multicollinearity — if income and education are correlated in the world, centering their means changes nothing.</p><p><strong>2. Remove the multicollinear variable</strong></p><p>If two variables carry redundant information, keeping both destabilizes the coefficients without adding meaningful independent signal. Remove the one less central to your question.</p><p><strong>3. Principal Component Analysis (PCA)</strong></p><p>PCA rotates the original variables into a set of orthogonal components — uncorrelated linear combinations ordered by how much variance in X they explain. Regressing on these components eliminates multicollinearity by construction.</p><p>The cost: interpretability. A principal component is a weighted combination of all original variables. Its coefficient cannot be interpreted as “the effect of x₁ holding x₂ constant.” PCA is appropriate when prediction is the primary goal and per-variable interpretation is secondary.</p><p>For each observation, the error is:</p><pre>eᵢ = yᵢ − ŷᵢ = yᵢ − (β₀ + β₁xᵢ₁ + ... + βₚxᵢₚ)</pre><p>Picture each data point connected to the fitted line by a vertical string. Each string exerts an upward or downward pull proportional to the error. The best-fit line is the position where these pulls are collectively minimized.</p><p><strong>Vertical, not perpendicular.</strong> OLS minimizes distance in the y direction — not the shortest perpendicular distance from each point to the line. Minimizing perpendicular distance is a different method called <strong>Total Least Squares (TLS)</strong>, used when the predictors themselves are measured with error. In OLS, x is treated as fixed and error-free. All uncertainty is attributed to y. The perpendicular distance forms a right triangle with the line — OLS uses only the vertical leg. TLS uses the full hypotenuse.</p><p>The loss function OLS minimizes:</p><pre>L(β) = Σᵢ eᵢ² = Σᵢ (yᵢ − xᵢᵀβ)²</pre><p>The notation xᵢᵀβ is the inner product of observation i’s feature vector (with a leading 1 for the intercept) and the coefficient vector: xᵢᵀβ = β₀ + β₁xᵢ₁ + … + βₚxᵢₚ. The intercept is absorbed into vector notation via the leading 1 in xᵢ.</p><p><strong>Odd powers fail on symmetry.</strong> A residual of +e contributes +e³ to cubic loss; a residual of −e contributes −e³. They cancel. Large errors of opposite signs offset each other to zero loss — not what you want. Even powers guarantee this does not happen: positive and negative residuals of the same magnitude are penalized identically.</p><p><strong>Among even powers, squaring uniquely gives a linear closed-form solution.</strong></p><p>Taking the gradient of Σeᵢ² with respect to β:</p><pre>∂L/∂β = −2Xᵀ(y − Xβ)</pre><p>Setting to zero:</p><pre>XᵀXβ = Xᵀy ← the Normal Equations: linear in β β̂ = (XᵀX)⁻¹Xᵀy ← exact closed-form solution</pre><p>Solvable in one algebraic step. The gradient of Σeᵢ⁴ gives a cubic equation in β — no closed form, iterative methods only. Squaring is the unique even power where the gradient is linear in β.</p><p><strong>Squaring is the direct consequence of assuming Gaussian errors — the probabilistic justification.</strong></p><p>Assume εᵢ ~ N(0, σ²). The log-likelihood of the full dataset is:</p><pre>ℓ(β, σ²) = −(n/2)log(2πσ²) − (1/2σ²) · Σᵢ(yᵢ − xᵢᵀβ)²</pre><p>The first term does not involve β. Maximizing ℓ over β means minimizing Σᵢ(yᵢ − xᵢᵀβ)² — exactly OLS. The squaring in the loss function comes directly from the e^(−x²/2) shape of the Gaussian probability density.</p><p>This gives OLS a dual justification: geometrically motivated by Legendre in 1805 (minimize squared distances) and probabilistically by Gauss in 1809 (maximize likelihood under normal errors). Both arrive at identical estimates. Squared errors are the geometric expression of the Gaussian error model.</p><p><strong>The outlier tradeoff:</strong> squaring penalizes large errors disproportionately. A residual of 10 contributes 100 to the loss; a residual of 1 contributes 1. This makes OLS sensitive to outliers. Absolute loss (LAD regression) is more robust — but has no closed form and corresponds to MLE under a Laplace error distribution, not Gaussian.</p><p><strong>L1 — Absolute loss (LAD regression)</strong> Sign-symmetric: Yes | Closed form: No — requires iterative methods | MLE error model: Laplace | Outlier sensitivity: Low — robust</p><p><strong>L2 — Squared loss (OLS)</strong> Sign-symmetric: Yes | Closed form: Yes — normal equations | MLE error model: Gaussian | Outlier sensitivity: Medium</p><p><strong>L4 — Fourth power loss</strong> Sign-symmetric: Yes | Closed form: No — requires iterative methods | MLE error model: None standard | Outlier sensitivity: High</p><p>When you ask “how confident should we be in a prediction of $500K next month?”, there are two fundamentally different intervals you can report — and choosing the wrong one dramatically understates the true uncertainty.</p><p><strong>Confidence Interval for the mean prediction:</strong></p><p>“What is the uncertainty about the <em>average</em> outcome for observations with these characteristics?”</p><pre>ŷ* ± t · s · √(x*ᵀ(XᵀX)⁻¹x*)</pre><p>This captures only <strong>parameter uncertainty</strong> — uncertainty in β̂ due to estimating it from finite data. As n → ∞, this interval collapses to a point because β̂ converges to β.</p><p><strong>Prediction Interval for a new individual observation:</strong></p><p>“Where will <em>this specific future observation</em> actually fall?”</p><pre>ŷ* ± t · s · √(1 + x*ᵀ(XᵀX)⁻¹x*)</pre><p>The extra <strong>1</strong> inside the square root represents the irreducible residual variance of the new observation — ε* ~ N(0, σ²). Even if you knew β perfectly, any individual outcome would still scatter around the true mean by ε*. This noise never disappears no matter how much data you collect.</p><p><strong>t</strong> is the critical value from the t-distribution with n−p−1 degrees of freedom at your chosen confidence level — approximately 1.96 for 95% confidence with large n. This is not the same as the p-value. The t-critical value is a threshold from the distribution; the p-value is the probability of observing a test statistic as extreme as yours under the null hypothesis.</p><p><strong>s</strong> is the standard error of the regression: s = √(SSE/(n−p−1)), in the same units as y.</p><p>The PI is always wider than the CI because it captures two sources of uncertainty: parameter uncertainty (shared with CI) plus irreducible observation noise (unique to PI).</p><p><strong>Concrete intuition:</strong> Even if you know perfectly that average December sales is $500K, any specific December will differ because of factors unique to that month — a competitor ran a flash sale, unusual weather, a news event shifted spending patterns. That scatter is σ². Reporting a CI to a stakeholder asking about one specific month dramatically understates the real uncertainty.</p><ul><li>Linear regression is linear in the parameters, not necessarily in the inputs. Any transformation of x is permitted.</li><li>“Independent variables” are named for their experimental role, not for statistical independence from each other.</li><li>The coefficient β̂_j measures the marginal effect: expected change in y per unit change in xⱼ, holding all other variables constant. R² measures explained variance. These are different questions.</li><li>The intercept is interpretable only when x = 0 is meaningful within or near the range of the data.</li><li>Autocorrelation and heteroscedasticity do not bias the point estimates — they corrupt the standard errors and invalidate all inference built on them.</li><li>The first fix for heteroscedasticity is robust (White’s HC) standard errors. The second is log transformation of y when variance scales with the level of y. The third is WLS when the variance structure is estimable.</li><li>Normality of errors is required for exact finite-sample inference. For large n, the CLT delivers approximate normality without requiring the assumption.</li><li>Multicollinearity does not harm prediction but destroys the interpretability of individual coefficients. It is more of a small-sample problem for estimation precision, but interpretability does not recover with scale.</li><li>VIF directly measures variance inflation: VIF = 10 means variance is 10× worse, standard error is √10 ≈ 3.16× larger than ideal.</li><li>Significant F-test combined with all non-significant t-tests is the classic fingerprint of multicollinearity.</li><li>OLS minimizes vertical distance. TLS minimizes perpendicular distance and applies when x is measured with error.</li><li>Squared loss is the unique even power that gives a linear closed-form solution and is simultaneously MLE under Gaussian errors.</li><li>A confidence interval covers uncertainty about the mean prediction. A prediction interval covers uncertainty about a specific future observation. Always use a prediction interval when the question is about one future outcome.</li></ul><p>The next post covers causal inference applications of linear regression: when correlation becomes causation, what omitted variable bias does to your coefficients, what endogeneity is and how to detect it, and identification strategies including instrumental variables and regression discontinuity design. It also covers the full inference machinery — t-tests, F-tests, confidence intervals, and model evaluation metrics including adjusted R², AIC, and BIC.</p><p><em>Originally published at </em><a href="https://gist.github.com/som028/3131dc61cb41dd888b18411e63f21b76"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ca30eff3955" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>