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 + eps2.2 Synthetic Data
Real-world datasets are messy, and worse yet, they never come with an answer key: when you train a new algorithm on real housing records and get a weight vector \(\hat{\mathbf{w}}\), you have no way of knowing the true data-generating parameters \(\mathbf{w}^*\) or the irreducible noise floor. Before unleashing an implementation on real data, a seasoned researcher first tests it on synthetic data generated from a known ground-truth model.
On a synthetic dataset, we control the feature distribution, the true weights \(\mathbf{w}^*\) and bias \(b^*\), the sample size \(n\), and the noise level \(\sigma\). That gives us two direct checks on our code: we can test whether the learned parameters \((\hat{\mathbf{w}}, \hat{b})\) approach \((\mathbf{w}^*, b^*)\), and we can compare the final loss against the theoretical noise floor \(\frac{1}{2}\sigma^2\). In this section, we build the synthetic dataset that we use throughout the next three sections, inspect its scatter plots, and compute the least-squares fit as a reference benchmark.
2.2.1 Generating the Data
To keep visualization effortless while exercising multi-feature matrix algebra, we generate \(n = 1{,}000\) training examples with \(d = 2\) features. We draw the design matrix \(\mathbf{X} \in \mathbb{R}^{1000 \times 2}\) with independent standard normal entries \(X_{ij} \sim \mathcal{N}(0, 1)\), and generate the labels from the linear model
\[\mathbf{y} = \mathbf{X} \mathbf{w}^* + b^* + \boldsymbol{\epsilon}, \tag{2.2.1}\]
using ground-truth parameters
\[\mathbf{w}^* = (2,\, -3.4)^\top, \qquad b^* = 4.2, \tag{2.2.2}\]
and additive Gaussian noise \(\epsilon^{(i)} \sim \mathcal{N}(0, \sigma^2)\) with standard deviation \(\sigma = 0.01\). Notice that the signal \((\mathbf{X}\mathbf{w}^* + b^*)\) varies on a scale of several units, whereas the noise \(\sigma = 0.01\) is hundreds of times smaller—so any healthy optimizer should recover \(\mathbf{w}^*\) and \(b^*\) to within a few thousandths.
Because JAX uses explicit functional pseudorandom keys (Section 1.1), our data generator takes one extra argument, a key, which we draw from the stateful key helper d2l.get_key.
def synthetic_data(w, b, noise, n):
"""n examples with standard normal features and labels Xw + b + noise."""
X = tf.random.normal((n, w.shape[0]))
eps = tf.random.normal((n, 1)) * noise
return X, d2l.matmul(X, d2l.reshape(w, (-1, 1))) + b + epsdef synthetic_data(w, b, noise, n, key):
"""n examples with standard normal features and labels Xw + b + noise."""
key1, key2 = jax.random.split(key)
X = jax.random.normal(key1, (n, w.shape[0]))
eps = jax.random.normal(key2, (n, 1)) * noise
return X, d2l.matmul(X, d2l.reshape(w, (-1, 1))) + b + epsdef 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 + epsLet us draw \(2{,}000\) examples using \(\mathbf{w}^* = (2, -3.4)\), \(b^* = 4.2\), and \(\sigma = 0.01\): we will reserve the first \(1{,}000\) for training and the remaining \(1{,}000\) for validation. Because the validation examples come from the exact same distribution but are never touched during fitting, evaluating our loss on them reveals how accurately the model predicts unseen data—a distinction we examine closely in Section 2.6.
w_star, b_star, noise = d2l.tensor([2, -3.4]), 4.2, 0.01
X, y = synthetic_data(w_star, b_star, noise, 2000)w_star, b_star, noise = d2l.tensor([2, -3.4]), 4.2, 0.01
X, y = synthetic_data(w_star, b_star, noise, 2000)w_star, b_star, noise = d2l.tensor([2, -3.4]), 4.2, 0.01
X, y = synthetic_data(w_star, b_star, noise, 2000, d2l.get_key())w_star, b_star, noise = d2l.tensor([2, -3.4]), 4.2, 0.01
X, y = synthetic_data(w_star, b_star, noise, 2000)Each row of X stores a two-dimensional feature vector and each row of y stores its corresponding scalar label. Inspecting the first example and backing out its noise \(\epsilon^{(1)} = y^{(1)} - (\mathbf{w}^{*\top}\mathbf{x}^{(1)} + b^*)\) gives us an immediate sanity check.
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
features: (0.5027, -0.0564)
label: 5.4010, noise: 0.0038
features: (-0.8760, 0.8323)
label: -0.3846, noise: -0.0030
features: (0.2088, 0.6338)
label: 2.4571, noise: -0.0057
For our first example, verify the math by hand: \(2 x_1^{(1)} - 3.4 x_2^{(1)} + 4.2\) matches \(y^{(1)}\) up to the tiny \(\mathcal{N}(0, 0.01^2)\) perturbation.
2.2.2 Inspecting the Data
Before fitting any model, let us plot the label \(y\) against each feature \(x_1\) and \(x_2\) individually:
d2l.set_figsize((7, 2.5))
_, axes = d2l.plt.subplots(1, 2, sharey=True)
for j, ax in enumerate(axes):
ax.scatter(d2l.numpy(X[:1000, j]), d2l.numpy(y[:1000, 0]), s=2)
ax.set_xlabel(f'$x_{j + 1}$')
ax.set_ylabel('$y$' if j == 0 else '')Each scatter plot reveals a clear linear trend with the expected sign: \(y\) climbs with \(x_1\) (slope \(+2\)) and falls more steeply with \(x_2\) (slope \(-3.4\)). Why does each 2D scatter plot look like a thick band rather than a razor-thin line when \(\sigma = 0.01\) is so tiny? Because plotting \(y\) against \(x_2\) alone ignores each point’s variation in \(x_1\): the unplotted term \(2 x_1\) has standard deviation \(2\), which spreads the vertical position of the points across a band several units wide. Viewing marginal 2D projections of a multivariate relationship always folds the unplotted coordinates into apparent vertical scatter.
2.2.3 Recovering the Parameters
Since we derived the closed-form normal equations in Section 2.1.2.1, let us compute the exact least-squares solution \((\hat{\mathbf{w}}, \hat{b})\) on our 1,000 examples right now using lstsq on the augmented design matrix \([\mathbf{X}, \mathbf{1}]\). This gives us the gold-standard finite-sample fit that minibatch SGD in Section 2.3 will aim to match:
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]n = 1000 # The training examples
X1 = tf.concat((X[:n], tf.ones((n, 1))), 1) # A column of ones for b
w_hat = tf.linalg.lstsq(X1, y[:n], fast=False)[:, 0]n = 1000 # The training examples
X1 = jnp.concatenate((X[:n], jnp.ones((n, 1))), 1) # A column of ones for b
w_hat = jnp.linalg.lstsq(X1, y[:n])[0][:, 0]n = 1000 # The training examples
X1 = mnp.concatenate((X[:n], mnp.ones((n, 1))), 1) # A column of ones for b
w_hat = mnp.linalg.lstsq(X1, y[:n], rcond=None)[0][:, 0]Now we print the actual estimation errors alongside our predicted standard error \(\sigma / \sqrt{n}\).
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
error in w: (4.1e-04, 5.2e-05)
error in b: -2.7e-04
standard error: 3.2e-04
error in w: (3.6e-04, -5.6e-05)
error in b: -3.2e-04
standard error: 3.2e-04
error in w: (-4.7e-04, -5.5e-05)
error in b: -6.4e-05
standard error: 3.2e-04
Even with lstsq solving the empirical loss to machine precision, \((\hat{\mathbf{w}}, \hat{b})\) differs from the true \((2, -3.4, 4.2)\) in the fourth decimal place. That tiny discrepancy is statistical estimation error, not numerical error: the 1,000 noise draws \(\boldsymbol{\epsilon}\) happen to correlate slightly with the columns of \(\mathbf{X}\), tilting the least-squares plane by a quantity of order \(\sigma / \sqrt{n} = 0.01 / \sqrt{1000} \approx 3 \times 10^{-4}\) (Exercise 1). This is a limit of the data, not of the solver: no unbiased estimator computed from these 1,000 noisy points has a smaller expected squared error (the Cramér–Rao bound), although a single run can land closer by luck. And as Exercise 2 explores, when the true data-generating function is nonlinear, least squares finds the best linear approximation to it over the feature distribution.
2.2.4 Summary
Generating synthetic data from a known linear model \(\mathbf{y} = \mathbf{X}\mathbf{w}^* + b^* + \boldsymbol{\epsilon}\) with \(\mathbf{w}^* = (2, -3.4)^\top\), \(b^* = 4.2\), and \(\sigma = 0.01\) gives us two quantitative checks that real data lack: an irreducible loss floor of \(\frac{1}{2}\sigma^2 = 5 \times 10^{-5}\) and known ground-truth parameters. Plotting \(y\) against a single coordinate \(x_j\) folds the variation of the unplotted features into the vertical spread, turning a nearly noiseless plane into a wide 2D band. Even an exact least-squares solver deviates from \((\mathbf{w}^*, b^*)\) by statistical estimation error of order \(\sigma/\sqrt{n}\) (\(\approx 3 \times 10^{-4}\) for \(n = 1{,}000\)), setting the accuracy target for iterative optimization in the next section.
2.2.5 Exercises
- [code] Recovery under noise. ● Repeat the least-squares fit of Section 2.2.3 on 1,000 independent datasets for each setting below, and measure the standard deviation of the estimation error \(\hat{w}_1 - w_1^*\) of the first weight.
- Vary
noiseover \(\{0.001, 0.01, 0.1, 1\}\) with 1,000 training examples, and the number \(n\) of training examples over \(\{10, 100, 1{,}000, 10{,}000\}\) withnoise=0.01. Plot both measurements against the prediction \(\sigma/\sqrt{n}\) on logarithmic axes. - Find the smallest \(n\) at which the measurement agrees with \(\sigma/\sqrt{n}\) to within 10%, and say which approximation behind that prediction fails for fewer examples.
- Write \(\tilde{\mathbf{X}} = [\mathbf{X}, \mathbf{1}]\), \(\tilde{\mathbf{w}}^* = (\mathbf{w}^*, b^*)\), and \(\hat{\tilde{\mathbf{w}}} = (\hat{\mathbf{w}}, \hat{b})\). Show from the normal equations that \(\hat{\tilde{\mathbf{w}}} - \tilde{\mathbf{w}}^* = (\tilde{\mathbf{X}}^\top\tilde{\mathbf{X}})^{-1}\tilde{\mathbf{X}}^\top\boldsymbol{\epsilon}\), and derive \(\textrm{Cov}(\hat{\tilde{\mathbf{w}}}) = \sigma^2(\tilde{\mathbf{X}}^\top\tilde{\mathbf{X}})^{-1}\) from it. Then generate correlated features \(x_2 = \rho x_1 + \sqrt{1 - \rho^2}\, z\), with \(x_1\) and \(z\) independent and standard normal, for \(\rho \in \{0, 0.9, 0.99\}\). Predict the standard error of \(\hat{w}_1\) from this formula, check it numerically, and explain why the predictions \(\hat{\tilde{\mathbf{w}}}^\top \tilde{\mathbf{x}}\), with \(\tilde{\mathbf{x}} = (\mathbf{x}, 1)\), on new examples drawn from the same distribution remain accurate when the weights do not.
- Vary
- [code] A model that does not fit. ● Add the term \(c\,x_1^2\) with \(c = 0.5\) to every label, so that the labels no longer follow a linear function of the features, and fit the linear model by least squares as in this section.
- Using \(\mathbb{E}[x_1^2] = 1\) and \(\mathbb{E}[x_1^3] = 0\), predict which of \(\hat{w}_1\), \(\hat{w}_2\), and \(\hat{b}\) end up away from the true values, and by about how much.
- Check the prediction for \(n \in \{100, 1{,}000, 10{,}000\}\) training examples. Which estimation errors shrink as \(n\) grows, which do not, and how do the shrinking ones compare with \(\sigma/\sqrt{n}\)?
- A test that flags any parameter error above \(10^{-3}\), about three standard errors, would pass a correct implementation on the data of this section. Would it declare a correct implementation faulty on these data? Explain what passing or failing such a test can tell you when the model does not fit the data.
- The loss floor and its fluctuation. The next section judges a training run by its validation loss, the average of \(\frac{1}{2}(\hat{y} - y)^2\) over the 1,000 validation examples.
- Show that a model with the true parameters has expected loss \(\sigma^2/2\) on a new example, and that no other parameters have a smaller one. This is the floor that a correct training run levels off at.
- For \(\epsilon \sim \mathcal{N}(0, \sigma^2)\) one has \(\mathbb{E}[\epsilon^4] = 3\sigma^4\). Compute the standard deviation of the loss \(\frac{1}{2}\epsilon^2\) of one example, and from it the standard error of the validation loss of the true parameters over \(n' = 1{,}000\) examples, as a fraction of the floor.
- [code] Check both numbers by evaluating the true parameters on many independent validation sets. Then use the result of part (a) to find the smallest parameter error that raises the expected loss by one standard error of the validation loss, and compare it with the parameter-error threshold of \(10^{-3}\) from the previous exercise.