Synthetic Data

Dive into Deep Learning · §2.2

Synthetic Regression Data: Ground-Truth Verification
known parameters · Gaussian generator · noise floor · statistical estimation error

Why Debug Machine Learning Code on Synthetic Data?

The Debugging Dilemma

  • Real-world ambiguity: When loss plateaus on real data, is the model misspecified, are the labels corrupted, or does the code contain a silent bug?
  • Controlled ground truth: Generating \mathbf{y} = \mathbf{X}\mathbf{w}^* + b^* + \boldsymbol{\epsilon} with \mathbf{w}^* = (2, -3.4)^\top, b^* = 4.2, and \sigma = 0.01 makes the linear model and squared loss statistically optimal by construction.
  • Quantitative pass/fail oracle: Any failure to hit the loss floor \frac{1}{2}\sigma^2 = 5 \times 10^{-5} or recover (\mathbf{w}^*, b^*) within \sim 3\sigma/\sqrt{n} \approx 10^{-3} convicts the code.

The Ground-Truth Data-Generating Process

Mathematical Specification

\mathbf{y} = \mathbf{X}\mathbf{w}^* + b^* + \boldsymbol{\epsilon}, \qquad X_{ij} \sim \mathcal{N}(0, 1), \quad \epsilon^{(i)} \sim \mathcal{N}(0, \sigma^2)

  • True parameters & high SNR: Weights \mathbf{w}^* = (2, -3.4)^\top, bias b^* = 4.2, and signal standard deviation \sqrt{2^2 + (-3.4)^2} \approx 3.94 (400\times larger than noise \sigma = 0.01).
  • Train/validation split: Drawing 2{,}000 i.i.d. examples provides 1{,}000 training examples for fitting and 1{,}000 validation examples for out-of-sample evaluation.

Implementing the Synthetic Generator

Vectorized Data Generation

def synthetic_data(w, b, noise, n):
    """n examples with standard normal features and labels Xw + b + noise."""
    X = d2l.randn(n, len(w))
    eps = d2l.randn(n, 1) * noise
    return X, d2l.matmul(X, d2l.reshape(w, (-1, 1))) + b + eps
  • Explicit column shape (-1, 1): Reshaping w to (d, 1) ensures matmul(X, w) produces an (n, 1) column matching eps of shape (n, 1), avoiding an (n, n) outer-sum broadcasting catastrophe.

Inspecting Generated Tensors and Realized Noise

Sanity-Checking the Data

We draw 2{,}000 examples and inspect the first training pair (\mathbf{x}^{(1)}, y^{(1)}) alongside its realized noise \epsilon^{(1)} = y^{(1)} - (\mathbf{w}^{*\top}\mathbf{x}^{(1)} + b^*):

w_star, b_star, noise = d2l.tensor([2, -3.4]), 4.2, 0.01
X, y = synthetic_data(w_star, b_star, noise, 2000)
x, label = X[0], y[0, 0]
eps = label - (d2l.reduce_sum(w_star * x) + b_star)
print(f'features: ({float(x[0]):.4f}, {float(x[1]):.4f})')
print(f'label: {float(label):.4f}, noise: {float(eps):.4f}')
features: (1.2794, 1.2895)
label: 2.3786, noise: 0.0042

Verify the arithmetic directly: 2 x_1^{(1)} - 3.4 x_2^{(1)} + 4.2 matches the observed label y^{(1)} up to the tiny Gaussian perturbation \epsilon^{(1)} of order \sigma = 0.01.

Why 2D Marginal Scatter Plots Look Like Thick Bands

Geometric Intuition

If \sigma = 0.01 is tiny, why does plotting y against x_1 and x_2 show thick vertical clouds several units wide rather than razor-thin lines?

  • Omitted-variable projection: In 3D space (x_1, x_2, y), all 1{,}000 points lie within \pm 0.03 of the tilted plane y = 2x_1 - 3.4x_2 + 4.2.
  • Unplotted feature variance: Projecting onto (x_2, y) folds each point’s unplotted coordinate 2x_1 \sim \mathcal{N}(0, 4) into the vertical spread (\textrm{std} = 2.0), while projecting onto (x_1, y) folds in -3.4x_2 (\textrm{std} = 3.4).

Marginal 2D scatter plots of a multivariate function always fold the variation of the unplotted features into the vertical scatter.

The Irreducible Loss Floor of the True Parameters

Theoretical Benchmark

\mathbb{E}\bigl[L(\mathbf{w}^*, b^*)\bigr] = \frac{1}{2}\,\mathbb{E}\bigl[(-\epsilon)^2\bigr] = \frac{\sigma^2}{2} = 5 \times 10^{-5}

  • Irreducible noise floor: Because future noise draws \epsilon \sim \mathcal{N}(0, \sigma^2) are independent of \mathbf{x}, no predictor can achieve an expected validation loss below \frac{1}{2}\sigma^2 = 5 \times 10^{-5}.
  • Finite-sample fluctuation: Over n' = 1{,}000 validation examples, the sample average of \frac{1}{2}\epsilon^2 fluctuates around 5 \times 10^{-5} with standard error \sigma^2/\sqrt{2n'} \approx 2.2 \times 10^{-6}.

Recovery I: Estimation Error Is Linear in the Noise

Statistical Recovery Analysis

\hat{\tilde{\mathbf{w}}} - \tilde{\mathbf{w}}^* = \bigl(\tilde{\mathbf{X}}^\top\tilde{\mathbf{X}}\bigr)^{-1}\tilde{\mathbf{X}}^\top\boldsymbol{\epsilon}

  • Signal cancellation: Substituting \mathbf{y} = \tilde{\mathbf{X}}\tilde{\mathbf{w}}^* + \boldsymbol{\epsilon} into the normal equations cancels the true parameter vector \tilde{\mathbf{w}}^*.
  • Unbiasedness & noiseless limit: Because \mathbb{E}[\boldsymbol{\epsilon}] = \mathbf{0}, \hat{\tilde{\mathbf{w}}} is unbiased (\mathbb{E}[\hat{\tilde{\mathbf{w}}}] = \tilde{\mathbf{w}}^*) and recovers \tilde{\mathbf{w}}^* to machine precision when \sigma = 0.

Recovery II: Isotropic Features Make X̃ᵀX̃ ≈ nI

Law of Large Numbers on the Gram Matrix

\frac{1}{n}\tilde{\mathbf{X}}^\top\tilde{\mathbf{X}} \approx \mathbf{I}_3 \quad\Longrightarrow\quad \hat{\tilde{\mathbf{w}}} - \tilde{\mathbf{w}}^* \approx \frac{1}{n}\tilde{\mathbf{X}}^\top\boldsymbol{\epsilon}

  • Diagonal concentration: Sample variances \frac{1}{n}\sum_{i=1}^n (x_j^{(i)})^2 concentrate tightly around \mathbb{E}[x_j^2] = 1.
  • Off-diagonal decoupling: Sample cross-products \frac{1}{n}\sum_{i=1}^n x_j^{(i)} x_k^{(i)} concentrate around \mathbb{E}[x_j x_k] = 0, decoupling the three parameter errors.

Recovery III: The σ/√n Standard Error Floor

The Statistical Limit

\operatorname{SE}(\hat{w}_j) = \operatorname{SE}(\hat{b}) \approx \frac{\sigma}{\sqrt{n}} = \frac{0.01}{\sqrt{1000}} \approx 3.16 \times 10^{-4}

  • Square-root sample scaling: Reducing estimation error by 10\times requires 100\times more training examples (n = 100{,}000), whereas reducing \sigma by 10\times shrinks error by 10\times immediately.
  • Exact covariance: \operatorname{Cov}(\hat{\tilde{\mathbf{w}}} \mid \tilde{\mathbf{X}}) = \sigma^2 (\tilde{\mathbf{X}}^\top\tilde{\mathbf{X}})^{-1} inflates when features are collinear.

Verifying the Least-Squares Reference Fit in Code

Gold-Standard Benchmark

We solve the normal equations on our n = 1{,}000 training examples with lstsq and compare actual parameter errors against \sigma / \sqrt{n} \approx 3 \times 10^{-4}:

n = 1000                                          # The training examples
X1 = torch.cat((X[:n], torch.ones(n, 1)), 1)      # A column of ones for b
w_hat = torch.linalg.lstsq(X1, y[:n]).solution[:, 0]
e_w = d2l.numpy(w_hat[:2] - w_star)
print(f'error in w: ({e_w[0]:.1e}, {e_w[1]:.1e})')
print(f'error in b: {float(w_hat[2] - b_star):.1e}')
print(f'standard error: {noise / n ** 0.5:.1e}')
error in w: (3.3e-04, 5.7e-04)
error in b: 1.1e-04
standard error: 3.2e-04
  • Pass/fail tolerance: Any converged iterative optimizer in this chapter must land within \sim 10^{-3} (\approx 3\text{ SE}) of (\mathbf{w}^*, b^*).

Concept Check: Loss Floors, Sample Size & Collinearity

Check Your Understanding

Predict the quantitative effect of each modification to our synthetic benchmark:

  1. Sample size vs. noise: What is the standard error of \hat{w}_1 when (a) n = 100, \sigma = 0.01, and (b) n = 1{,}000, \sigma = 0.1?
  2. Misspecified quadratic term: Suppose the true labels are generated by y = 2x_1 - 3.4x_2 + 4.2 + 0.5x_1^2 + \epsilon with x_1, x_2 \sim \mathcal{N}(0, 1), and we fit the linear model \hat{y} = w_1 x_1 + w_2 x_2 + b. Which parameter absorbs the unmodeled 0.5x_1^2 term as n \to \infty?
  3. Correlated features: If x_2 = 0.99 x_1 + \sqrt{1 - 0.99^2}\,z, why do individual weight errors |\hat{w}_j - w_j^*| blow up by \sim 7\times while predictions \hat{\mathbf{w}}^\top\mathbf{x} on new test points from the same distribution remain accurate?

Answers:

    1. \sigma / \sqrt{n} = 0.01 / \sqrt{100} = 10^{-3}; (b) 0.1 / \sqrt{1000} \approx 3.16 \times 10^{-3}.
  1. Because \mathbb{E}[x_1^2] = 1 and \mathbb{E}[x_1 \cdot x_1^2] = \mathbb{E}[x_1^3] = 0, the quadratic term 0.5x_1^2 is orthogonal to x_1 and x_2 but shifts the mean label by +0.5, so \hat{b} \to 4.2 + 0.5 = 4.7 while \hat{\mathbf{w}} \to (2, -3.4)^\top.
  2. When x_1 \approx x_2, the difference direction x_1 - x_2 has tiny variance (1 - \rho = 0.01), inflating \operatorname{Var}(\hat{w}_1 - \hat{w}_2), but new test points from the same distribution also have x_1 \approx x_2 and only probe the well-determined sum \hat{w}_1 + \hat{w}_2.

Summary & Key Takeaways

Summary

Benchmark Quantity Formula / Definition Value on Running Example Diagnostic Role in Later Sections
Data Generator \mathbf{y} = \mathbf{X}\mathbf{w}^* + b^* + \boldsymbol{\epsilon} \mathbf{w}^* = (2, -3.4)^\top, b^* = 4.2, \sigma = 0.01 Ground-truth linear testbed (n = 1{,}000 train, 1{,}000 val)
Irreducible Loss Floor \mathbb{E}[L(\mathbf{w}^*, b^*)] = \frac{1}{2}\sigma^2 5 \times 10^{-5} (or \sigma^2 = 10^{-4} without \frac{1}{2}) Target plateau for training and validation loss curves
Estimation Error \hat{\tilde{\mathbf{w}}} - \tilde{\mathbf{w}}^* = (\tilde{\mathbf{X}}^\top\tilde{\mathbf{X}})^{-1}\tilde{\mathbf{X}}^\top\boldsymbol{\epsilon} Exact zero when \sigma = 0 Separates statistical noise floor from optimization error
Parameter Standard Error \operatorname{SE}(\hat{w}_j) \approx \sigma / \sqrt{n} 0.01 / \sqrt{1000} \approx 3.2 \times 10^{-4} Sets 3\text{ SE} \approx 10^{-3} pass/fail tolerance for recovered weights