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.

  1. Derive beta_hat_new on the 2n-row table and state how the point estimates compare with beta_hat.
  2. 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 matrix Var(beta_hat_new) against Var(beta_hat).
  3. 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_new and X_new' y_new in terms of X'X and X'y via block matrices to relate beta_hat_new, fitted values, and the residual sum of squares to their n-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

  1. 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 n independent observations: - X is an n x k design matrix (a table with n rows of observations and k columns of predictors, usually including a column of 1s for the intercept). Assume X has full column rank k so (X'X) is invertible. - y is an n x 1 column vector of observed outcomes. - The true data-generating model is y = X * beta + e, where e is an n x 1 vector 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 variance sigma^2 and any two distinct rows have covariance 0).

    Cloning every record once stacks X on top of itself and y on top of itself into a 2n-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'X and X'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 X is a single column [1, 3]' (n = 2, k = 1): then X'X = 1^2 + 3^2 = 10, while X_new = [1, 3, 1, 3]' gives X_new' X_new = 1^2 + 3^2 + 1^2 + 3^2 = 20 = 2 * (X'X).

  2. Part 1: Why the estimated coefficients stay identical

    Now plug X_new' X_new = 2(X'X) and X_new' y_new = 2(X'y) into the OLS estimator beta_hat = (X'X)^-1 X'y. Recall that scaling an invertible matrix by a constant c scales its inverse by 1/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_hat
    

    The factor of 2 and the factor of 1/2 cancel out cleanly. That means beta_hat_new is numerically identical to beta_hat on every single dataset — not merely equal in expectation!

    Why does this happen intuitively? OLS chooses beta to minimize the Residual Sum of Squares (RSS), which is the sum of squared vertical distances between each observed y_i and its predicted value x_i' beta. When every point appears twice, every squared error (y_i - x_i' beta)^2 is 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 2 makes 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.

  3. 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_hat in two steps: 1. Estimate the error variance sigma^2 using s^2 = RSS / df, where df is the degrees of freedom (sample size minus number of estimated parameters k). 2. Compute Var_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 2n rows and k parameters, so it uses df_new = 2n - k alongside RSS_new = 2 * RSS and (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)^-1
    

    Compare Var_hat_new directly against the original Var_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, so Var_hat_new -> (1/2) Var_hat and SE_new / SE -> 1 / sqrt(2) = 0.707 (a 29.3% drop).

    Where does that factor of 1/2 come from? For large n, s_new^2 = 2 * RSS / (2n - k) is very close to s^2 = RSS / (n - k) (only slightly smaller in finite samples because k is 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.

  4. Part 2b: Why the true variance-covariance matrix is actually unchanged

    Now compare the true variance-covariance matrices Var(beta_hat | X) and Var(beta_hat_new | X) across repeated random draws of the dataset.

    Because beta_hat_new = beta_hat holds 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)^-1
    

    Copying 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)^-1 get the wrong answer? Because sigma^2 * (X'X)^-1 is only valid when Var(e | X) = sigma^2 * I. In the duplicated dataset, the stacked error vector is e_new = [e; e]. Row i and row n + i carry the exact same random shock e_i, so their correlation is 1 and their covariance is Cov(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)^-1
    

    The 4 from the perfectly correlated error pairs cancels (1/2) * (1/2) = 1/4, recovering the original sigma^2 * (X'X)^-1! Thus, the naive OLS covariance matrix underestimates the true variance by roughly a factor of 2 (in expectation, E[Var_hat_new | X] = [(n - k) / (2n - k)] * sigma^2 * (X'X)^-1).

  5. Part 3: Why p-values are misleading and how i.i.d. breaks

    A p-value for testing H_0: beta_j = 0 is the probability, assuming the true coefficient is 0 and 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 in e_new = [e; e] still has mean 0 and variance sigma^2. - Independent means knowing one row's error tells you nothing about another row's error (zero off-diagonal covariances in Var(e | X)). Duplicating every row severely violates independence: every row has an exact twin with correlation +1.0. The effective sample size is still n, while the software counts 2n.

    Because beta_hat_new = beta_hat while SE_new shrinks, 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 - k
    

    Both effects push p-values downward and manufacture false discoveries: - Suppose a noisy predictor has t_orig = 1.50 with n = 30, k = 2 (df = 28), giving a non-significant two-sided p = 0.145. Duplicating the table inflates t_new to 1.50 * sqrt(58 / 28) = 2.159 with df = 58, dropping the p-value to 0.035 — crossing the 0.05 significance threshold with zero new data! - Under a true null (beta_j = 0), a nominal 5% 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-n limit, |Z| > 1.96 / sqrt(2) = 1.386, which happens 16.6% of the time instead of 5% (and 17.5% at n = 30, 25.3% at n = 5). Likewise, nominal 95% confidence intervals cover the truth only about 83.4% of the time.

  6. 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] and y = [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.026
    

    Every ratio matches our algebra: beta_hat stays (1.1, 0.5), RSS doubles (2.7 -> 5.4), SE(slope) scales by 0.1837 / 0.3000 = 0.6124 = sqrt(3/8), and p(slope) plunges from 0.194 to 0.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 slope 0, 5,000 trials) confirms that the true spread of beta_hat_new stays at 0.226, while the duplicated SE under-reports 0.156 and 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.18
    

    How 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_i contributes 4 * x_i x_i' e_hat_i^2, and (2 X'X)^-1 cancels the 4 to recover the exact heteroskedasticity-robust (HC0) variance of the original n rows — though deduplicating first is still cleaner so finite-sample degrees-of-freedom adjustments use n, not 2n.

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) and X_new' y_new = 2(X'y), so beta_hat_new = (2 X'X)^-1 (2 X'y) = beta_hat on 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 by sqrt((n - k) / (2n - k)), which equals 0.612 at n = 5, k = 2 and approaches 1 / sqrt(2) ≈ 0.707 for large n.
  • True estimator variance is completely unchanged: Because beta_hat_new = beta_hat is 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)^-1 for correlated errors with covariance matrix Omega) using Omega = sigma^2 [[I_n, I_n], [I_n, I_n]] confirms that the 4 from perfectly correlated pairs cancels (1/2)^2.
  • Violation of independence (not homoscedasticity) breaks p-values: Homoscedasticity (equal error variance sigma^2 across 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. Because t_new = t_orig * sqrt((2n - k) / (n - k)) and degrees of freedom jump to 2n - k, a nominal 5% test rejects a true null about 16.6% of the time for large n (17.5% at n = 30, 25.3% at n = 5), and nominal 95% confidence intervals only achieve ~83.4% coverage.

Common mistakes

  • Claiming the point estimates become "more accurate" or "have lower true variance": beta_hat_new is the exact same number as beta_hat on every sample, so its true sampling distribution and true precision cannot improve.
  • Blaming s_new^2 for the 1 / sqrt(2) shrinkage: For large n, s_new^2 = 2 * RSS / (2n - k) is almost identical to s^2 = RSS / (n - k). The factor of 1/2 in the reported variance comes from (X_new' X_new)^-1 = (1/2)(X'X)^-1, compounded in small samples by 2n - k degrees of freedom.
  • Saying homoscedasticity is violated: Every row in e_new = [e; e] still has variance sigma^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 (from 0.212 to 0.150 on our 5-point example); you must either deduplicate or cluster standard errors on the original observation ID.
  • Thinking large n washes out the problem: Even at n = 1,000,000, SE_new / SE converges to 1 / sqrt(2) ≈ 0.707, t-statistics remain inflated by sqrt(2) ≈ 1.414, and the false-positive rate stays near 16.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 n genuinely new, independent draws, all 2n error terms are truly uncorrelated (Var(e_new | X_new) = sigma^2 I_2n), so the OLS variance formula sigma^2 (X_new' X_new)^-1 is now valid and the ~1 / sqrt(2) reduction in standard errors reflects real information gain (for example, from ~0.300 down to ~0.212). Unlike duplication, beta_hat_new will change slightly because the fresh y values 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_id or (user_id, timestamp)), count exact duplicate rows across (X, y) via df.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.0 if 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 by user_id or 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.481 in our 5-point example): because y_bar does not change when every y_i is repeated twice, the Total Sum of Squares (TSS) doubles alongside RSS (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 size N) is artificially inflated toward R^2 as N doubles from n to 2n (0.308 -> 0.416 in 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 from 0.194 to 0.026).

Follow-up questions

Similar questions

More Snapchat interview questions

All 94 Snapchat questions →