2.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 , you have no way of knowing the true data-generating parameters 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 and bias , the sample size , and the noise level . That gives us two direct checks on our code: we can test whether the learned parameters approach , and we can compare the final loss against the theoretical noise floor . 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 training examples with features. We draw the design matrix with independent standard normal entries , and generate the labels from the linear model
using ground-truth parameters
and additive Gaussian noise with standard deviation . Notice that the signal varies on a scale of several units, whereas the noise is hundreds of times smaller—so any healthy optimizer should recover and to within a few thousandths.
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 + epsLet us draw examples using , , and : we will reserve the first for training and the remaining 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)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 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
For our first example, verify the math by hand: matches up to the tiny perturbation.
2.2.2 Inspecting the Data#
Before fitting any model, let us plot the label against each feature and 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: climbs with (slope ) and falls more steeply with (slope ). Why does each 2D scatter plot look like a thick band rather than a razor-thin line when is so tiny? Because plotting against alone ignores each point's variation in : the unplotted term has standard deviation , 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 on our 1,000 examples right now using lstsq on the augmented design matrix . 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]Now we print the actual estimation errors alongside our predicted standard error .
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
Even with lstsq solving the empirical loss to machine precision, differs from the true in the fourth decimal place. That tiny discrepancy is statistical estimation error, not numerical error: the 1,000 noise draws happen to correlate slightly with the columns of , tilting the least-squares plane by a quantity of order (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 with , , and gives us two quantitative checks that real data lack: an irreducible loss floor of and known ground-truth parameters. Plotting against a single coordinate 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 by statistical estimation error of order ( for ), 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 of the first weight.
- Vary
noiseover with 1,000 training examples, and the number of training examples over withnoise=0.01. Plot both measurements against the prediction on logarithmic axes. - Find the smallest at which the measurement agrees with to within 10%, and say which approximation behind that prediction fails for fewer examples.
- Write , , and . Show from the normal equations that , and derive from it. Then generate correlated features , with and independent and standard normal, for . Predict the standard error of from this formula, check it numerically, and explain why the predictions , with , 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 with 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 and , predict which of , , and end up away from the true values, and by about how much.
- Check the prediction for training examples. Which estimation errors shrink as grows, which do not, and how do the shrinking ones compare with ?
- A test that flags any parameter error above , 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 over the 1,000 validation examples.
- Show that a model with the true parameters has expected loss 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 one has . Compute the standard deviation of the loss of one example, and from it the standard error of the validation loss of the true parameters over 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 from the previous exercise.