Ordinary Least Squares With Cloned Observations
Medium · Statistics & Math · Data Scientist · Technical Screen
Prompt
Consider a linear regression sample containing n mutually independent records (X, y), where the design matrix X has dimensions n x k (with full column rank k) and the response column vector y has dimensions n x 1. Under classical Ordinary Least Squares (OLS) conditions—including zero conditional mean and homoscedastic, uncorrelated disturbances—the fitted parameter vector is beta_hat = (X'X)^-1 X'y.
Suppose an upstream pipeline bug clones every record once, stacking the data into a 2n-row table (X_new, y_new) in which each original (x_i, y_i) pair appears twice.
- Derive
beta_hat_newon the2n-row table and state how the point estimates compare withbeta_hat. - Determine how the standard errors printed by an OLS routine change on the
2n-row table, and contrast both the software-reported covariance matrix and the true sampling covariance matrixVar(beta_hat_new)againstVar(beta_hat). - Explain why hypothesis-test p-values reported from the
2n-row regression are invalid, identifying which part of the independent and identically distributed (i.i.d.) disturbance condition fails.
Scope & Expectations
- Write
X_new' X_newandX_new' y_newin terms ofX'XandX'yvia block matrices to relatebeta_hat_new, fitted values, and the residual sum of squares to theirn-row counterparts. - Distinguish the naive covariance estimate reported by standard regression packages (accounting for residual degrees of freedom) from the true sampling variance induced by perfectly correlated error pairs.
- Tie the failure of error independence—while noting whether homoscedasticity still holds—to inflated t-statistics, altered degrees of freedom, and elevated Type I error rates.
Step-by-step walkthrough
Represent the duplicated dataset as stacked matrices
Before computing any regression formulas, write down what the original dataset and the duplicated dataset look like as matrices.
In the original dataset, we have
nindependent observations: -Xis ann x kdesign matrix (a table withnrows of observations andkcolumns of predictors, usually including a column of1s for the intercept). AssumeXhas full column rankkso(X'X)is invertible. -yis ann x 1column vector of observed outcomes. - The true data-generating model isy = X * beta + e, whereeis ann x 1vector of unobserved random errors with mean zero (E[e | X] = 0) and homoscedastic, uncorrelated variance (Var(e | X) = sigma^2 * I_n, meaning every error has variancesigma^2and any two distinct rows have covariance0).Cloning every record once stacks
Xon top of itself andyon top of itself into a2n-row table:Original (n rows): Duplicated (2n rows): X = [ row 1 ] X_new = [ X ] (shape: 2n x k) [ ... ] [ X ] [ row n ] y_new = [ y ] (shape: 2n x 1) y = [ y_1 ... y_n ]' [ y ]Every Ordinary Least Squares (OLS) quantity is built from two matrix cross-products:
X'XandX'y. Using block-matrix multiplication (where[X; X]' = [X' X']), each dot product simply sums every original row twice:X_new' X_new = [ X' X' ] [ X ] = X'X + X'X = 2 * (X'X) [ X ] X_new' y_new = [ X' X' ] [ y ] = X'y + X'y = 2 * (X'y) [ y ]To see why with tiny numbers, suppose
Xis a single column[1, 3]'(n = 2, k = 1): thenX'X = 1^2 + 3^2 = 10, whileX_new = [1, 3, 1, 3]'givesX_new' X_new = 1^2 + 3^2 + 1^2 + 3^2 = 20 = 2 * (X'X).Part 1: Why the estimated coefficients stay identical
Now plug
X_new' X_new = 2(X'X)andX_new' y_new = 2(X'y)into the OLS estimatorbeta_hat = (X'X)^-1 X'y. Recall that scaling an invertible matrix by a constantcscales its inverse by1/c, so(2 * X'X)^-1 = (1/2) * (X'X)^-1:beta_hat_new = (X_new' X_new)^-1 (X_new' y_new) = (2 * X'X)^-1 * (2 * X'y) = (1/2) * (X'X)^-1 * 2 * (X'y) = (X'X)^-1 X'y = beta_hatThe factor of
2and the factor of1/2cancel out cleanly. That meansbeta_hat_newis numerically identical tobeta_haton every single dataset — not merely equal in expectation!Why does this happen intuitively? OLS chooses
betato minimize the Residual Sum of Squares (RSS), which is the sum of squared vertical distances between each observedy_iand its predicted valuex_i' beta. When every point appears twice, every squared error(y_i - x_i' beta)^2is counted twice:Objective_new(beta) = sum over 2n rows of (y_i - x_i' beta)^2 = 2 * sum over n rows of (y_i - x_i' beta)^2 = 2 * Objective_orig(beta)Multiplying an entire U-shaped curve by
2makes it twice as steep, which never moves the horizontal position of its lowest point. Consequently: - Fitted values repeat twice:y_hat_new = X_new * beta_hat_new = [y_hat; y_hat]. - Residuals (observed minus predicted) repeat twice:e_hat_new = y_new - y_hat_new = [e_hat; e_hat]. - The residual sum of squares doubles:RSS_new = e_hat_new' e_hat_new = 2 * RSS.Part 2a: How the estimated standard errors reported by OLS shrink
To answer how standard errors change, we must separate what standard OLS software reports from the true sampling variability of the estimator. Let us compute the software-reported values first.
Standard regression software assumes all rows are independent and estimates the variance-covariance matrix of
beta_hatin two steps: 1. Estimate the error variancesigma^2usings^2 = RSS / df, wheredfis the degrees of freedom (sample size minus number of estimated parametersk). 2. ComputeVar_hat(beta_hat) = s^2 * (X'X)^-1, and take the square roots of its diagonal entries as the standard errors (SE).On the duplicated dataset, the software sees
2nrows andkparameters, so it usesdf_new = 2n - kalongsideRSS_new = 2 * RSSand(X_new' X_new)^-1 = (1/2)(X'X)^-1:s_new^2 = RSS_new / (2n - k) = (2 * RSS) / (2n - k) Var_hat_new = s_new^2 * (X_new' X_new)^-1 = [ (2 * RSS) / (2n - k) ] * [ (1/2) * (X'X)^-1 ] = [ RSS / (2n - k) ] * (X'X)^-1Compare
Var_hat_newdirectly against the originalVar_hat = [RSS / (n - k)] * (X'X)^-1:Var_hat_new = [ (n - k) / (2n - k) ] * Var_hat SE_new(beta_hat_j) = sqrt( (n - k) / (2n - k) ) * SE(beta_hat_j)Notice how much the estimated standard errors shrink: - Small sample (
n = 5, k = 2):SE_new / SE = sqrt(3 / 8) = 0.612(a 38.8% drop). - Moderate sample (n = 30, k = 2):SE_new / SE = sqrt(28 / 58) = 0.695(a 30.5% drop). - Large-sample limit (n -> infinity):(n - k) / (2n - k) -> 1/2, soVar_hat_new -> (1/2) Var_hatandSE_new / SE -> 1 / sqrt(2) = 0.707(a 29.3% drop).Where does that factor of
1/2come from? For largen,s_new^2 = 2 * RSS / (2n - k)is very close tos^2 = RSS / (n - k)(only slightly smaller in finite samples becausekis subtracted once instead of twice). The main culprit is(X_new' X_new)^-1 = (1/2)(X'X)^-1: the naive formula thinks we observed twice as much predictor spread and information.Part 2b: Why the true variance-covariance matrix is actually unchanged
Now compare the true variance-covariance matrices
Var(beta_hat | X)andVar(beta_hat_new | X)across repeated random draws of the dataset.Because
beta_hat_new = beta_hatholds identically for every possible draw of(X, y), the two estimators are the exact same random vector. Two identical random vectors must have the exact same variance-covariance matrix:Var(beta_hat_new | X) = Var(beta_hat | X) = sigma^2 * (X'X)^-1Copying rows in a spreadsheet cannot create new real-world information or reduce true estimation uncertainty.
Why did the textbook formula
sigma^2 * (X_new' X_new)^-1 = (1/2) sigma^2 (X'X)^-1get the wrong answer? Becausesigma^2 * (X'X)^-1is only valid whenVar(e | X) = sigma^2 * I. In the duplicated dataset, the stacked error vector ise_new = [e; e]. Rowiand rown + icarry the exact same random shocke_i, so their correlation is1and their covariance isCov(e_i, e_i) = sigma^2:Var(e_new | X) = Omega = [ E[ee'] E[ee'] ] = sigma^2 * [ I_n I_n ] [ E[ee'] E[ee'] ] [ I_n I_n ]When errors have general covariance
Omega, the true variance of OLS is given by the sandwich formula(X_new' X_new)^-1 (X_new' Omega X_new) (X_new' X_new)^-1. Compute the middle ("meat") matrix first:X_new' Omega X_new = sigma^2 * [ X' X' ] [ I_n I_n ] [ X ] [ I_n I_n ] [ X ] = sigma^2 * [ X' X' ] [ 2X ] [ 2X ] = 4 * sigma^2 * (X'X)Now multiply by the outer ("bread") inverses
(X_new' X_new)^-1 = (1/2)(X'X)^-1:Var(beta_hat_new | X) = [ (1/2)(X'X)^-1 ] * [ 4 * sigma^2 * (X'X) ] * [ (1/2)(X'X)^-1 ] = sigma^2 * (X'X)^-1The
4from the perfectly correlated error pairs cancels(1/2) * (1/2) = 1/4, recovering the originalsigma^2 * (X'X)^-1! Thus, the naive OLS covariance matrix underestimates the true variance by roughly a factor of2(in expectation,E[Var_hat_new | X] = [(n - k) / (2n - k)] * sigma^2 * (X'X)^-1).Part 3: Why p-values are misleading and how i.i.d. breaks
A p-value for testing
H_0: beta_j = 0is the probability, assuming the true coefficient is0and all model assumptions hold, of seeing a t-statistic at least as extreme as|t| = |beta_hat_j| / SE(beta_hat_j).Classical OLS inference relies on i.i.d. (independent and identically distributed) errors: - Identically distributed / homoscedastic means every error term comes from the same distribution with the same variance
sigma^2. Duplicating every row does not violate homoscedasticity: every row ine_new = [e; e]still has mean0and variancesigma^2. - Independent means knowing one row's error tells you nothing about another row's error (zero off-diagonal covariances inVar(e | X)). Duplicating every row severely violates independence: every row has an exact twin with correlation+1.0. The effective sample size is stilln, while the software counts2n.Because
beta_hat_new = beta_hatwhileSE_newshrinks, the t-statistic inflates and is judged against a looser t-distribution with more degrees of freedom:t_new = beta_hat_j / SE_new = t_orig * sqrt( (2n - k) / (n - k) ) (about 1.414 * t_orig) df_new = 2n - k instead of n - kBoth effects push p-values downward and manufacture false discoveries: - Suppose a noisy predictor has
t_orig = 1.50withn = 30, k = 2(df = 28), giving a non-significant two-sidedp = 0.145. Duplicating the table inflatest_newto1.50 * sqrt(58 / 28) = 2.159withdf = 58, dropping the p-value to0.035— crossing the0.05significance threshold with zero new data! - Under a true null (beta_j = 0), a nominal5%test rejects whenever|t_new| > t_crit(2n - k), which is equivalent to|t_orig| > t_crit(2n - k) * sqrt((n - k) / (2n - k)). In the large-nlimit,|Z| > 1.96 / sqrt(2) = 1.386, which happens 16.6% of the time instead of 5% (and 17.5% atn = 30, 25.3% atn = 5). Likewise, nominal95%confidence intervals cover the truth only about 83.4% of the time.Worked numeric example, simulation, and practical remedies
Let us verify every formula on a 5-point dataset with an intercept (
n = 5, k = 2):x = [1, 2, 3, 4, 5]andy = [1, 3, 2, 4, 3].Dataset N df RSS s^2 beta_hat SE(slope) t(slope) p(slope) ------------------------------------------------------------------------------- Original 5 3 2.7 0.900 (1.1, 0.5) 0.300 1.667 0.194 Duplicated 10 8 5.4 0.675 (1.1, 0.5) 0.184 2.722 0.026Every ratio matches our algebra:
beta_hatstays(1.1, 0.5),RSSdoubles (2.7 -> 5.4),SE(slope)scales by0.1837 / 0.3000 = 0.6124 = sqrt(3/8), andp(slope)plunges from0.194to0.026.import numpy as np def fit_ols(X, y): """Return OLS coefficients, naive i.i.d. standard errors, and residuals.""" n, k = X.shape xtx_inv = np.linalg.inv(X.T @ X) beta_hat = xtx_inv @ (X.T @ y) residuals = y - X @ beta_hat s2 = (residuals @ residuals) / (n - k) se = np.sqrt(np.diag(s2 * xtx_inv)) return beta_hat, se, residuals x = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) y = np.array([1.0, 3.0, 2.0, 4.0, 3.0]) X = np.column_stack([np.ones(5), x]) X_dup = np.vstack([X, X]) y_dup = np.concatenate([y, y]) beta_orig, se_orig, resid_orig = fit_ols(X, y) beta_dup, se_dup, resid_dup = fit_ols(X_dup, y_dup) print(np.round(beta_orig, 3), np.round(se_orig, 3)) # [1.1 0.5] [0.995 0.3 ] print(np.round(beta_dup, 3), np.round(se_dup, 3)) # [1.1 0.5] [0.609 0.184]A quick Monte Carlo simulation (
n = 30, k = 2, true slope0,5,000trials) confirms that the true spread ofbeta_hat_newstays at0.226, while the duplicated SE under-reports0.156and inflates the false-positive rate from~5%to~18%:rng = np.random.default_rng(0) n = 30 X_sim = np.column_stack([np.ones(n), rng.normal(size=n)]) X_sim_dup = np.vstack([X_sim, X_sim]) t_crit_28 = 2.048 # two-sided 5% critical value for df = 28 t_crit_58 = 2.002 # two-sided 5% critical value for df = 58 slopes = [] reported_ses = [] reject_orig = 0 reject_dup = 0 trials = 5000 for _ in range(trials): y_sim = 1.0 + rng.normal(size=n) # true slope is 0 b0, se0, _ = fit_ols(X_sim, y_sim) bd, sed, _ = fit_ols(X_sim_dup, np.concatenate([y_sim, y_sim])) slopes.append(bd[1]) reported_ses.append(sed[1]) reject_orig += abs(b0[1] / se0[1]) > t_crit_28 reject_dup += abs(bd[1] / sed[1]) > t_crit_58 print("True SD of slope:", round(float(np.std(slopes)), 3)) # ~0.226 print("Mean reported SE (duplicated):", round(float(np.mean(reported_ses)), 3)) # ~0.156 print("False-positive rate:", reject_orig / trials, "->", reject_dup / trials) # ~0.05 -> ~0.18How to fix this in practice: - Deduplicate accidental copies first: In analytics pipelines (for example, an accidental many-to-many SQL join fan-out or double-logged app events), drop exact duplicate records on the primary event/unit key before running OLS. - Cluster standard errors for genuine repeated measurements: If multiple rows belong to the same user or cluster (correlated within unit rather than accidental clones), group by unit ID and compute cluster-robust (sandwich) standard errors (or fit a mixed-effects model). Note that if you cluster exact copies by original row ID without small-sample adjustments, each cluster score
2 * x_i * e_hat_icontributes4 * x_i x_i' e_hat_i^2, and(2 X'X)^-1cancels the4to recover the exact heteroskedasticity-robust (HC0) variance of the originalnrows — though deduplicating first is still cleaner so finite-sample degrees-of-freedom adjustments usen, not2n.
Intuition & how it works
Imagine polling 100 voters to estimate what fraction supports a ballot measure, and finding 54 "yes" votes (54%). Before running your statistical analysis, someone accidentally photocopies every ballot and feeds the 200-sheet stack into a spreadsheet. Your estimated support is still exactly 54% (108 / 200), because every "yes" and every "no" was doubled equally. However, the spreadsheet has no idea half the sheets are photocopies: it assumes 200 independent voters answered, reports a margin of error roughly 1 / sqrt(2) ≈ 0.707 times as wide, and prints an artificially tiny p-value — even though the photocopier added zero real-world evidence.
Naive Ordinary Least Squares (OLS — fitting a linear model by minimizing the sum of squared vertical prediction errors) falls into this exact trap when every observation in (X, y) is duplicated. Algebraically, stacking [X; X] and [y; y] multiplies both X'X and X'y by 2, and those 2s cancel in beta_hat_new = (2 X'X)^-1 (2 X'y) = beta_hat, leaving the coefficients unchanged. Yet the standard OLS variance formula s^2 (X'X)^-1 assumes every row's random error is independent, so doubling X'X cuts (X_new' X_new)^-1 in half while inflating the degrees of freedom (sample size minus number of parameters) from n - k to 2n - k.
On a tiny 5-point dataset x = [1, 2, 3, 4, 5], y = [1, 3, 2, 4, 3] with an intercept (n = 5, k = 2), OLS fits intercept 1.1 and slope 0.5 with residual sum of squares RSS = 2.7, slope standard error 0.300, t = 1.667 (df = 3), and two-sided p = 0.194 (not statistically significant). After duplicating all 5 rows (2n = 10, df = 8), OLS fits the exact same (1.1, 0.5), RSS doubles to 5.4, the reported slope standard error drops by sqrt(3/8) = 0.612 to 0.184, t jumps to 2.722, and p drops to 0.026 — creating a false "significant" result out of thin air.
Key points
- Estimated coefficients are numerically identical:
X_new' X_new = 2(X'X)andX_new' y_new = 2(X'y), sobeta_hat_new = (2 X'X)^-1 (2 X'y) = beta_haton every dataset. Fitted values and residuals repeat twice, and the Residual Sum of Squares (RSS) doubles (RSS_new = 2 * RSS). - Software-reported covariance and standard errors shrink: Standard OLS reports
Var_hat_new = s_new^2 (X_new' X_new)^-1 = [2 * RSS / (2n - k)] * (1/2)(X'X)^-1 = [(n - k) / (2n - k)] * Var_hat. Estimated standard errors shrink bysqrt((n - k) / (2n - k)), which equals0.612atn = 5, k = 2and approaches1 / sqrt(2) ≈ 0.707for largen. - True estimator variance is completely unchanged: Because
beta_hat_new = beta_hatis the exact same random vector,Var(beta_hat_new | X) = Var(beta_hat | X) = sigma^2 (X'X)^-1. Evaluating the sandwich variance formula (the general OLS variance formula(X'X)^-1 X' Omega X (X'X)^-1for correlated errors with covariance matrixOmega) usingOmega = sigma^2 [[I_n, I_n], [I_n, I_n]]confirms that the4from perfectly correlated pairs cancels(1/2)^2. - Violation of independence (not homoscedasticity) breaks p-values: Homoscedasticity (equal error variance
sigma^2across rows) still holds, and errors remain identically distributed, so only the independence part of i.i.d. fails: each row has a clone with correlation+1. Becauset_new = t_orig * sqrt((2n - k) / (n - k))and degrees of freedom jump to2n - k, a nominal5%test rejects a true null about16.6%of the time for largen(17.5%atn = 30,25.3%atn = 5), and nominal95%confidence intervals only achieve~83.4%coverage.
Common mistakes
- Claiming the point estimates become "more accurate" or "have lower true variance":
beta_hat_newis the exact same number asbeta_haton every sample, so its true sampling distribution and true precision cannot improve. - Blaming
s_new^2for the1 / sqrt(2)shrinkage: For largen,s_new^2 = 2 * RSS / (2n - k)is almost identical tos^2 = RSS / (n - k). The factor of1/2in the reported variance comes from(X_new' X_new)^-1 = (1/2)(X'X)^-1, compounded in small samples by2n - kdegrees of freedom. - Saying homoscedasticity is violated: Every row in
e_new = [e; e]still has variancesigma^2. What fails is zero covariance between distinct rows (Cov(e_i, e_{n+i}) = sigma^2 != 0). - Trying to fix duplicated data with heteroskedasticity-robust (White / HC) standard errors: Heteroskedasticity-robust standard errors allow each row to have a different error variance while still assuming distinct rows are independent. On duplicated rows, HC0 standard errors still shrink by the exact
1 / sqrt(2)factor (from0.212to0.150on our 5-point example); you must either deduplicate or cluster standard errors on the original observation ID. - Thinking large
nwashes out the problem: Even atn = 1,000,000,SE_new / SEconverges to1 / sqrt(2) ≈ 0.707, t-statistics remain inflated bysqrt(2) ≈ 1.414, and the false-positive rate stays near16.6%.
Follow-up questions
-
How do the standard errors behave if you collect n genuinely fresh, independent samples from the same population instead of cloning the existing rows? With
ngenuinely new, independent draws, all2nerror terms are truly uncorrelated (Var(e_new | X_new) = sigma^2 I_2n), so the OLS variance formulasigma^2 (X_new' X_new)^-1is now valid and the~1 / sqrt(2)reduction in standard errors reflects real information gain (for example, from~0.300down to~0.212). Unlike duplication,beta_hat_newwill change slightly because the freshyvalues contain independent random noise that averages down estimation error, and both t-tests and p-values will have proper Type I error rates (5%) and confidence interval coverage (95%). -
What data-hygiene checks or regression diagnostics help uncover accidental row duplication before or during modeling? Before modeling, check primary-key uniqueness (
event_idor(user_id, timestamp)), count exact duplicate rows across(X, y)viadf.duplicated().sum(), and compare row counts before and after every SQL/DataFrame join to catch many-to-many join fan-out. Inside regression diagnostics, inspect whether fitted values and residuals occur in identical pairs (note that a Durbin-Watson test — which checks lag-1 correlation between adjacent rows — only flags duplicates if copies sit right next to each other, and looks completely normal around~2.0if the table is stacked as[X; X]). Fix logging/join duplicates by deduplicating (drop_duplicates); if multiple rows are genuine repeated measurements of the same user over time, keep the rows and use cluster-robust standard errors byuser_idor a mixed-effects model. -
What happens to ordinary R-squared, adjusted R-squared, and the overall F-test when every row is repeated? Ordinary R-squared (
R^2 = 1 - RSS / TSS, the fraction of total outcome variance explained by the model) stays completely unchanged (0.481in our 5-point example): becausey_bardoes not change when everyy_iis repeated twice, the Total Sum of Squares (TSS) doubles alongsideRSS(2 * RSS / (2 * TSS) = RSS / TSS). However, Adjusted R-squared (1 - (1 - R^2)(N - 1) / (N - k), which penalizes extra parameters based on sample sizeN) is artificially inflated towardR^2asNdoubles fromnto2n(0.308 -> 0.416in the example), and the overall model F-statistic ([R^2 / (k - 1)] / [(1 - R^2) / (N - k)]) scales up by(2n - k) / (n - k)(2.78 -> 7.41, dropping its p-value from0.194to0.026).
Follow-up questions
- How do the standard errors behave if you collect n genuinely fresh, independent samples from the same population instead of cloning the existing rows?
- What data-hygiene checks or regression diagnostics help uncover accidental row duplication before or during modeling?
- What happens to ordinary R-squared, adjusted R-squared, and the overall F-test when every row is repeated?
Similar questions
- Auditing Assumption Failures in OLS Regression
- Optimal Center Selection Under L1 and L2 Objectives: Median vs. Mean
- Adapting a Production Beta-Binomial Model to Concept Drift
- Mean Front-to-Rear Camera Transitions per Session
- Verify Binary Tree Completeness
- Contrasting Batch and Layer Normalization
More Snapchat interview questions
- Generalization, Regularization, and Transformer Self-Attention Medium
- Hierarchy Tree Rendering and Two-Hop Reporting Pairs Hard
- Mean Front-to-Rear Camera Transitions per Session Medium Pro
- Contrasting Batch and Layer Normalization Hard Pro
- Banner CTR and Session Engagement Analytics Medium Pro
- Count Enclosed Land Islands Medium Pro
- Daily Users Starting With App Launch Medium Pro
- API-Polled News Feed Aggregator Hard Pro
- Time-Series Metrics Monitoring and Alerting Platform Medium Pro
- Vertical Short-Video Feed Vending Backend Medium Pro