12  Lab 3: Parameter Updates and Generalization

Calculate, interpret, and read training code

Author

Pedro Gomes

12.1 How to use this sheet

This lab page contains take-home and exam-preparation exercises, accompanying the concepts chapter. The full paper-exercise route takes about 2–3 hours.

Exercises 1–9 are pen-and-paper exercises. Work through the code-reading questions on paper, just as you would in a written exam. Show intermediate steps and justify your conclusions. These questions illustrate practice formats, as could be found in a written exam.

Worked solutions are collected in collapsed boxes at the end. A separate optional computer investigation lets you test the same ideas on a larger example; it is not needed to complete the paper exercises.

Route Focus
Exercises 1–3 Updates, learning rates, and stationary points
Exercises 4–6 Stochastic gradients, momentum, and L2
Exercises 7–9 Validation decisions and reading code
Check and revisit Compare with the worked solutions

Conventions. A gradient-descent update subtracts the gradient. Unless stated otherwise, squared-error loss is half mean squared error. L2 means \(\lambda\sum_j\theta_j^2\), whose gradient contribution is \(2\lambda\theta_j\) for each penalized parameter. Exercise-specific functions and data are self-contained; you do not need to memorize the chapter’s numerical examples.

12.2 Part A: calculate and explain

12.2.1 Exercise 1 — One gradient-descent update

About 15 minutes. See Section 12.3 and Section 12.5 in the concepts chapter.

For observations \((x_1,y_1)=(1,2)\) and \((x_2,y_2)=(2,4)\), fit \(\hat y_i=wx_i+b\) using

\[ L(w,b)=\frac{1}{2n}\sum_{i=1}^n(wx_i+b-y_i)^2,\qquad n=2. \]

  1. Identify the parameters, the observed data, and the learning-rate hyperparameter.
  2. Starting from \(w=b=0\), calculate predictions, prediction-minus-target errors, and loss.
  3. Derive both partial derivatives and evaluate them at the starting point.
  4. With \(\eta=0.1\), update both parameters using the old parameters. Calculate the new predictions and loss.
  5. Does the lower training loss establish better performance on new data? Explain.

12.2.2 Exercise 2 — Learning rate and curvature

About 15 minutes. See Section 12.5.

Consider the separate objective \(L(w)=\frac54(w-2)^2\), starting at \(w_0=0\).

  1. Find \(L'(w)\), the curvature \(c=L''(w)\), and the minimizer.
  2. Calculate two updates for \(\eta=0.2\).
  3. Use \(w_{t+1}-2=(1-\eta c)(w_t-2)\) to classify rates \(0.2\), \(0.6\), \(0.8\), and \(1.0\): approach from one side, alternating convergence, a nonconvergent cycle, or divergence.
  4. For \(\eta=0.6\), do alternating parameter values imply an alternating or increasing loss? Justify your answer without calculating many updates.

12.2.3 Exercise 3 — What does a zero gradient tell us?

About 10 minutes. See Section 12.4.

Consider the following functions. A Hessian calculation is not required.

\[ f(u,v)=u^2+v^2,\qquad g(u,v)=u^2-v^2,\qquad h(u,v)=-(u^2+v^2). \]

  1. For each function, calculate its gradient at the origin and classify that point. Justify your answer by considering nearby points.
  2. Would exact, deterministic gradient descent initialized at the origin move for any of these functions?
  3. Does convexity alone guarantee a unique minimizer? Give a simple counterexample if it does not.

12.2.4 Exercise 4 — Full batches, stochastic updates, and epochs

About 15 minutes. See Section 12.6.

Let two example losses be \(\ell_1(w)=\frac12(w-1)^2\) and \(\ell_2(w)=\frac12(w-3)^2\), with average loss \(L=(\ell_1+\ell_2)/2\). Start at \(w=2\) and use \(\eta=0.1\).

  1. Calculate each example gradient and the full-batch gradient. What full-batch update follows?
  2. Calculate the two possible stochastic updates, sampling one example uniformly. What is their expected updated parameter?
  3. Evaluate the full loss before and after either stochastic update. Explain how an unbiased gradient estimate can still increase the full loss on an individual update.
  4. A dataset has 100 examples. With batch size 32 and the final partial batch retained, how many updates occur per epoch and over five epochs? Compare with full-batch training over five epochs. What is matched by an equal-epoch comparison, and what is not?

12.2.5 Exercise 5 — Momentum by hand

About 10 minutes. See Section 12.7.

Use \(L(w)=\frac12w^2\), \(w_0=2\), \(v_0=0\), \(\eta=0.1\), and \(\beta=0.5\):

\[ v_{t+1}=\beta v_t+L'(w_t),\qquad w_{t+1}=w_t-\eta v_{t+1}. \]

  1. Calculate \((v_1,w_1)\) and \((v_2,w_2)\).
  2. Calculate two ordinary gradient-descent updates with the same initial weight and learning rate.
  3. Explain the difference using the stored gradient history. Does this calculation prove that momentum is always faster or never oscillates?

12.2.6 Exercise 6 — L2 changes the objective

About 15 minutes. See Section 12.9.

For \(\lambda\geq0\), consider

\[ J(w)=\frac54(w-2)^2+\lambda w^2. \]

  1. Derive \(J'(w)\) and the minimizer \(w^*_{\lambda}\).
  2. Find that minimizer for \(\lambda=0\) and \(\lambda=0.5\). Explain what changes as \(\lambda\) increases.
  3. Starting from \(w=1\), calculate one update for \(\eta=0.2\) and \(\lambda=0.5\). Rewrite the update as a weight-decay factor plus an unregularized loss-gradient step.
  4. How do the roles of \(\lambda\) and \(\eta\) differ? Why can the same L2-versus-decay equivalence not simply be transferred to Adam?
  5. Suppose a polynomial’s intercept is unpenalized. As regularization becomes extremely strong, must the prediction approach zero, or can it approach a nonzero constant?

12.3 Part B: interpret evidence and read code

12.3.1 Exercise 7 — Select a checkpoint without using the test set

About 15 minutes. See Section 12.8 and Section 12.9.

Validation is checked once after each epoch. Any strict decrease is an improvement, and patience is two consecutive checks without improvement. The model is saved whenever validation loss improves.

Epoch Training loss Validation loss
1 0.90 0.95
2 0.60 0.70
3 0.42 0.58
4 0.30 0.60
5 0.23 0.62
6 0.18 0.54
  1. At which epoch would this rule stop? Which saved parameters would it return?
  2. The table was obtained from a complete six-epoch run. Which checkpoint is best retrospectively? Explain why an online stopping rule need not find it.
  3. What does the pattern through epoch 5 suggest, and what does it fail to prove? Give one alternative explanation or diagnostic check.
  4. A colleague chooses patience and L2 strength by test loss, then reports that same test loss as final performance. Explain the problem and propose a valid procedure.

12.3.2 Exercise 8 — Trace a training loop on paper

About 10 minutes. Do not execute this code before answering.

The objective is \(L(w)=\frac12(w-3)^2\).

w = 2.0
eta = 0.5
history = []
for step in range(2):
    history.append(0.5 * (w - 3.0)**2)
    gradient = w - 3.0
    w = w - eta * gradient
  1. Make a table showing w before each update, the recorded loss, the gradient, and w afterward.
  2. What are the final w and the contents of history?
  3. Does history[-1] contain the loss of the final returned parameter? Explain and write one additional line that would include that final loss.
  4. Identify the line that computes the gradient and the line that updates the parameter. Which role would backpropagation perform in a larger model?

12.3.3 Exercise 9 — Find two checkpoint mistakes

About 15 minutes. Assume theta is a mutable NumPy array, gradient is correct, and the loss functions return scalar prediction losses. The aim is to save the parameters with lowest validation loss.

best_loss = float("inf")
best_theta = None
for step in range(100):
    theta -= eta * gradient(theta)
    train_loss = training_loss(theta)
    val_loss = validation_loss(theta)
    if train_loss < best_loss:
        best_loss = train_loss
        best_theta = theta
  1. Identify two mistakes in how the checkpoint is selected or stored.
  2. Rewrite the if block correctly. Use .copy() to make an independent array.
  3. Does the corrected loop actually stop early, or does it select a checkpoint from a fixed-budget run? What additional rule would be needed for early stopping?
  4. Why is using validation loss here different from differentiating it to update theta?

12.4 Optional computer investigation

This extension is for understanding through experiments, not for memorizing code for a closed-computer exam. Allow another 30–45 minutes if you choose it. The supplied dataset and training routine are complete and run independently of the concepts page. Your work is to predict, compare, and interpret; no backpropagation implementation is needed.

We reuse the chapter’s seed-7 synthetic sine data and degree-9 polynomial. The feature columns are \([x^9,\ldots,x,1]\), divided by their training standard deviations; the constant column stays unchanged. Thus the coefficients below multiply scaled features, not the raw powers. Training and validation each contain 20 examples. There is no test set: these are validation-based investigations, not final performance estimates.

The objective is half mean squared error plus \(\lambda\) times the squared non-intercept coefficients. The gradient therefore adds \(2\lambda\theta_j\) for penalized coefficients. Unlike the chapter’s final worked helper, this routine does not penalize the intercept. The earlier ridge illustration also excludes the intercept, but uses a different polynomial basis; numeric penalty strengths should not be transferred between bases.

Supplied data and training routine
import numpy as np
import torch
import matplotlib.pyplot as plt

BLUE, GREEN, ORANGE = "#0072B2", "#009E73", "#D55E00"


def make_data(seed=7, n_total=40, n_train=20, degree=9):
    rng = np.random.default_rng(seed)
    x_all = np.sort(rng.uniform(0, 6, n_total))
    y_all = np.sin(x_all) + rng.normal(scale=0.25, size=n_total)
    train_idx = rng.choice(n_total, size=n_train, replace=False)
    val_idx = np.setdiff1d(np.arange(n_total), train_idx)
    x_train, x_val = x_all[train_idx], x_all[val_idx]
    X_raw = np.vander(x_train, degree + 1)
    V_raw = np.vander(x_val, degree + 1)
    scale = X_raw.std(axis=0)
    scale[scale == 0] = 1.0
    data = tuple(torch.tensor(a, dtype=torch.float64) for a in
                 (X_raw / scale, y_all[train_idx],
                  V_raw / scale, y_all[val_idx]))
    return data, x_train, x_val, scale


data, x_train, x_val, scale = make_data()
X, y, V, z = data
print(f"Training: {tuple(X.shape)}; validation: {tuple(V.shape)}")
print(f"Training input range: {x_train.min():.2f} to {x_train.max():.2f}")
print(f"Validation input range: {x_val.min():.2f} to {x_val.max():.2f}")


def train(data, eta=0.02, lam=0.0, updates=3000, patience=None):
    X, y, V, z = data
    theta = torch.zeros(X.shape[1], dtype=X.dtype)
    penalty_mask = torch.ones_like(theta)
    penalty_mask[-1] = 0.0
    history, best = [], None
    for step in range(updates + 1):
        residual = y - X @ theta
        training_loss = 0.5 * residual.square().mean().item()
        validation_loss = 0.5 * (V @ theta - z).square().mean().item()
        if not np.isfinite([training_loss, validation_loss]).all():
            raise ValueError("Non-finite loss: inspect the learning rate and inputs.")
        history.append([training_loss, validation_loss])
        if best is None or validation_loss < best["loss"]:
            best = {"step": step, "loss": validation_loss,
                    "theta": theta.clone()}
        if step == updates:
            break
        if patience is not None and step - best["step"] >= patience:
            break
        gradient = -X.T @ residual / len(X) + 2 * lam * penalty_mask * theta
        theta = theta - eta * gradient
    return {"history": np.array(history), "best": best,
            "final_theta": theta.clone(), "stop_step": step}
Training: (20, 10); validation: (20, 10)
Training input range: 0.03 to 5.38
Validation input range: 0.02 to 5.97

Here data contains training features and targets, followed by validation features and targets. The history records update 0 and every subsequent update. best stores a copied checkpoint, its update number, and its validation loss. A patience value counts consecutive validation checks without a strict improvement; None runs the entire budget.

Before running the comparison below, write your predictions:

  1. With 100 updates and no penalty, compare learning rates 0.002, 0.02, and 0.18. Which runs do you expect to be stable? Compare final training losses; explain why the threshold from Exercise 2 does not apply directly.
  2. With rate 0.02, compare an unregularized 3000-update run with patience 50 and 400. Record the stopping update separately from the selected update. Does the smaller patience miss a later improvement?
  3. Keeping all other settings fixed, compare final models for L2 strengths 0, 0.001, 0.01, 0.05, 0.1, and 0.5. Then compare the best final regularized model with the best unregularized checkpoint. Explain why all reported losses exclude the penalty.
Code
for eta in [0.002, 0.02, 0.18]:
    run = train(data, eta=eta, updates=100)
    print(f"Rate {eta}: final training loss {run['history'][-1, 0]:.4g}")

baseline = train(data)
for patience in [50, 400]:
    run = train(data, patience=patience)
    print(f"Patience {patience}: stop {run['stop_step']}, "
          f"selected {run['best']['step']}, validation {run['best']['loss']:.4f}")

print("lambda | final train | final validation | best validation | best update")
for lam in [0, 0.001, 0.01, 0.05, 0.1, 0.5]:
    run = train(data, lam=lam)
    last, best = run["history"][-1], run["best"]
    print(f"{lam:6g} | {last[0]:.4f} | {last[1]:.4f} | "
          f"{best['loss']:.4f} | {best['step']}")

fig, ax = plt.subplots(figsize=(7, 3.8))
ax.semilogy(baseline["history"][:, 0], color=BLUE, lw=2, label="Training")
ax.semilogy(baseline["history"][:, 1], color=GREEN, lw=2, label="Validation")
ax.axvline(baseline["best"]["step"], color="0.4", ls="--", label="Best checkpoint")
ax.set(xlabel="Update", ylabel="Half mean squared error")
ax.spines[["top", "right"]].set_visible(False)
ax.grid(axis="y", alpha=0.15)
ax.legend(frameon=False)
fig.tight_layout()
plt.show()
Rate 0.002: final training loss 0.2561
Rate 0.02: final training loss 0.1301
Rate 0.18: final training loss 1.094e+15
Patience 50: stop 53, selected 3, validation 0.1925
Patience 400: stop 695, selected 295, validation 0.0842
lambda | final train | final validation | best validation | best update
     0 | 0.0354 | 0.7366 | 0.0842 | 295
 0.001 | 0.0362 | 0.6809 | 0.0842 | 296
  0.01 | 0.0465 | 0.3585 | 0.0845 | 313
  0.05 | 0.0795 | 0.0913 | 0.0865 | 479
   0.1 | 0.0960 | 0.1046 | 0.1043 | 879
   0.5 | 0.1243 | 0.2496 | 0.1927 | 3
Training loss falls while validation loss reaches its lowest value at update 295 and then rises. A dashed line marks that checkpoint.
Figure 12.1: The full unregularized degree-9 run, with the best validation checkpoint marked. This marker is selected retrospectively and is not the stopping time of a patience-based rule.

For a further extension, repeat with data, x_train, x_val, scale = make_data(seed=8) and then seed 9. Re-run the comparison each time. A changed seed changes the observations and split; the full-batch algorithm itself is deterministic for fixed data and initialization. Do not require every seed to reproduce the same ranking.

12.5 Worked solutions — open after attempting the exercises

These are example solutions. Equivalent reasoning and valid alternative diagnostic checks are welcome.

1.1 The learned parameters are \(w,b\); \(x_i,y_i\) are observed data; \(\eta\) is a hyperparameter.

1.2 Substitute \(w=0\) and \(b=0\) into each prediction:

\[\hat y_1=0\cdot1+0=0,\qquad \hat y_2=0\cdot2+0=0.\]

The prediction-minus-target errors are \(e_1=0-2=-2\) and \(e_2=0-4=-4\). Since \(n=2\), the normalization is \(1/(2n)=1/4\):

\[L(0,0)=\frac14\left[(-2)^2+(-4)^2\right] =\frac{4+16}{4}=5.\]

1.3 Write \(e_i=wx_i+b-y_i\). The chain rule gives

\[\frac{\partial(e_i^2)}{\partial w}=2e_i\frac{\partial e_i}{\partial w}=2e_ix_i, \qquad \frac{\partial(e_i^2)}{\partial b}=2e_i\frac{\partial e_i}{\partial b}=2e_i.\]

Multiplying by \(1/(2n)\) cancels the factor 2. Thus

\[\partial_wL=\frac1n\sum_i e_ix_i,\qquad \partial_bL=\frac1n\sum_i e_i.\]

At the initial parameters, substitute \(e_1=-2\), \(e_2=-4\), \(x_1=1\), and \(x_2=2\):

\[\partial_wL=\frac{(-2)(1)+(-4)(2)}2=\frac{-10}2=-5,\]

\[\partial_bL=\frac{-2-4}2=-3.\]

1.4 Subtract the learning rate times each derivative:

\[w_1=0-0.1(-5)=0.5,\qquad b_1=0-0.1(-3)=0.3.\]

Both derivatives use the old parameters \((0,0)\). Recomputing one derivative after updating the other parameter would be a different procedure.

Now calculate the new predictions and errors:

\[\hat y_1=0.5(1)+0.3=0.8,\qquad e_1=0.8-2=-1.2,\]

\[\hat y_2=0.5(2)+0.3=1.3,\qquad e_2=1.3-4=-2.7.\]

Therefore

\[L(w_1,b_1)=\frac{(-1.2)^2+(-2.7)^2}{4} =\frac{1.44+7.29}{4}=2.1825<5.\]

1.5 This calculation establishes lower training loss only; it contains no evidence about unseen data.

2.1 Differentiate the squared term using the chain rule:

\[L'(w)=\frac54\cdot2(w-2)\cdot1=\frac52(w-2), \qquad L''(w)=\frac52=c.\]

Set \(L'(w)=0\): \(\frac52(w-2)=0\) implies \(w^*=2\). The positive second derivative confirms this is a minimum; the quadratic is strictly convex, so it is the unique global minimum.

2.2 At \(w_0=0\), \(L'(0)=\frac52(-2)=-5\), so

\[w_1=w_0-0.2L'(w_0)=0-0.2(-5)=1.\]

Recompute the gradient at this new point: \(L'(1)=\frac52(-1)=-2.5\). Hence

\[w_2=1-0.2(-2.5)=1.5.\]

2.3 Subtract the minimizer from the update:

\[w_{t+1}-2=w_t-2-\eta\frac52(w_t-2) =(1-2.5\eta)(w_t-2).\]

Let \(r=1-2.5\eta\). A positive \(r\) preserves the error’s sign; a negative \(r\) reverses it. The error shrinks when \(|r|<1\), stays the same size when \(|r|=1\), and grows when \(|r|>1\). Substituting each rate gives:

Rate Error multiplier \(1-\eta c\) Behavior from \(w_0=0\)
0.2 0.5 Converges from below
0.6 −0.5 Alternates around 2 with shrinking error
0.8 −1 Cycles between 0 and 4; constant loss 5
1.0 −1.5 Alternates with growing error; diverges

2.4 Substitute the error recurrence into the loss:

\[L(w_{t+1})=\frac54\left[(1-\eta c)(w_t-2)\right]^2 =(1-\eta c)^2L(w_t).\]

For \(\eta=0.6\), \(1-0.6(2.5)=-0.5\), so the loss multiplier is \((-0.5)^2=0.25\). For example, \(w_0=0\), \(w_1=3\), and \(w_2=1.5\), while their losses are \(5\), \(1.25\), and \(0.3125\). The parameter alternates, but the loss decreases.

For convergence from a nonoptimal starting point,

\[|1-2.5\eta|<1 \iff -1<1-2.5\eta<1 \iff 0<2.5\eta<2 \iff 0<\eta<0.8.\]

3.1 For a partial derivative with respect to \(u\), hold \(v\) fixed, and vice versa:

\[\nabla f=(2u,2v),\qquad \nabla g=(2u,-2v),\qquad \nabla h=(-2u,-2v).\]

Substituting \(u=v=0\) gives \((0,0)\) for all three gradients. Their values at the origin are also all zero, but their nearby values differ:

  • For \(f\), \(u^2+v^2>0\) whenever \((u,v)\ne(0,0)\), so the origin is the unique global minimum.
  • For \(g\), choose any small \(\epsilon\ne0\). Then \(g(\epsilon,0)=\epsilon^2>0\), whereas \(g(0,\epsilon)=-\epsilon^2<0\). Values increase in one direction and decrease in another: the origin is a saddle.
  • For \(h\), \(-(u^2+v^2)<0\) whenever \((u,v)\ne(0,0)\), so the origin is the unique global maximum.

3.2 The update at the origin is

\[(u_1,v_1)=(0,0)-\eta(0,0)=(0,0).\]

Repeating the same calculation leaves the parameters there forever for all three functions. This is an exact deterministic statement; perturbations or numerical effects are separate.

3.3 Consider \(q(u,v)=u^2\). It is convex because it is a convex quadratic in \(u\) and is constant in \(v\). Since \(u^2\geq0\), its smallest value is zero. Every point with \(u=0\) attains that value: for example, \(q(0,0)=q(0,1)=q(0,-2)=0\). Thus convexity does not imply a unique minimizing parameter vector.

4.1 Differentiate each example loss:

\[\ell_1'(w)=\tfrac12\cdot2(w-1)=w-1,\qquad \ell_2'(w)=w-3.\]

At \(w=2\), these are \(1\) and \(-1\). The full gradient averages them:

\[L'(2)=\frac{1+(-1)}2=0,\qquad w_{\mathrm{new}}=2-0.1(0)=2.\]

4.2 The two possible updates are

\[w_{\mathrm{new},1}=2-0.1(1)=1.9,\qquad w_{\mathrm{new},2}=2-0.1(-1)=2.1.\]

Since each example is sampled with probability \(1/2\),

\[\mathbb E[w_{\mathrm{new}}]=\tfrac12(1.9)+\tfrac12(2.1)=2.\]

Likewise, the expected sampled gradient is \(\tfrac12(1)+\tfrac12(-1)=0=L'(2)\): it is unbiased at the current parameter.

4.3 Averaging the two half-squared losses gives

\[L(w)=\frac{(w-1)^2+(w-3)^2}{4}.\]

Before the update,

\[L(2)=\frac{1^2+(-1)^2}{4}=0.5.\]

After each possible update,

\[L(1.9)=\frac{0.9^2+(-1.1)^2}{4}=\frac{0.81+1.21}{4}=0.505,\]

\[L(2.1)=\frac{1.1^2+(-0.9)^2}{4}=0.505.\]

Consequently \(\mathbb E[L(w_{\mathrm{new}})]=0.505\), even though \(L(\mathbb E[w_{\mathrm{new}}])=L(2)=0.5\). An unbiased gradient estimate does not guarantee a loss-decreasing update: loss is nonlinear, and here we started at its minimum. Sequential stochastic updates also evaluate gradients at changing parameters, so their full trajectory is not the full-batch trajectory.

4.4 With 100 examples and batch size 32, batches have sizes 32, 32, 32, and 4: four updates per epoch, or 20 in five epochs. Full-batch training uses five updates in five epochs. Equal epochs match passes through the examples, not parameter-update counts or elapsed time.

5.1 Differentiating gives \(L'(w)=\frac12\cdot2w=w\). First compute the new velocity, then use it in the parameter update:

\[v_1=\beta v_0+L'(w_0)=0.5(0)+2=2,\]

\[w_1=w_0-\eta v_1=2-0.1(2)=1.8.\]

At the second step, evaluate the gradient at \(w_1=1.8\):

\[v_2=0.5(2)+1.8=2.8,\]

\[w_2=1.8-0.1(2.8)=1.8-0.28=1.52.\]

5.2 Ordinary gradient descent has no velocity term:

\[w_1=2-0.1L'(2)=2-0.1(2)=1.8,\]

\[w_2=1.8-0.1L'(1.8)=1.8-0.1(1.8)=1.62.\]

5.3 Momentum’s second step includes a contribution from the previous gradient, so it travels farther toward zero in this example. This is not a general convergence or speed guarantee. Other rates, momentum coefficients, or curvatures can cause overshooting or instability. The recurrence uses an unnormalized accumulation, not an average with a \((1-\beta)\) factor.

6.1 Differentiate the data-loss and penalty terms separately:

\[J'(w)=\frac54\cdot2(w-2)+\lambda\cdot2w =\frac52(w-2)+2\lambda w.\]

At a stationary point,

\[0=\frac52w-5+2\lambda w =(2.5+2\lambda)w-5.\]

Move the constant to the other side and divide:

\[(2.5+2\lambda)w=5 \quad\Longrightarrow\quad w^*_{\lambda}=\frac{5}{2.5+2\lambda}.\]

For \(\lambda\geq0\), \(J''(w)=2.5+2\lambda>0\). Thus this stationary point is the unique global minimum.

6.2 Substitute each strength into the formula:

\[w^*_0=\frac5{2.5}=2,\]

\[w^*_{0.5}=\frac5{2.5+2(0.5)}=\frac5{3.5}=\frac{10}7\approx1.429.\]

As lambda grows, the positive denominator increases while the numerator stays fixed. The optimum therefore shrinks toward zero. The penalty trades some fit to the data for a smaller weight.

6.3 At \(w=1\) and \(\lambda=0.5\),

\[J'(1)=2.5(1-2)+2(0.5)(1)=-2.5+1=-1.5.\]

Therefore

\[w_{\mathrm{new}}=1-0.2(-1.5)=1+0.3=1.3.\]

To obtain the weight-decay form, expand and collect the terms multiplying \(w\):

\[\begin{aligned} w_{\mathrm{new}} &=w-\eta\left[L'(w)+2\lambda w\right]\\ &=w-2\eta\lambda w-\eta L'(w)\\ &=(1-2\eta\lambda)w-\eta L'(w). \end{aligned}\]

The decay factor is \(1-2(0.2)(0.5)=0.8\), while \(L'(1)=-2.5\). Substituting yields the same answer: \(0.8(1)-0.2(-2.5)=0.8+0.5=1.3\).

6.4 Lambda changes the objective and its optimum. Eta controls the numerical update and its stability; a convergent run on the same objective has the same optimum. In Adam, adding an L2 gradient also changes the moving averages and adaptive scaling, whereas decoupled weight decay applies shrinkage separately.

6.5 When penalized coefficients approach zero, only the unpenalized intercept \(b\) remains, so the prediction is constant. Its squared-error loss is

\[L(b)=\frac1{2n}\sum_i(b-y_i)^2.\]

Differentiate and set the derivative to zero:

\[L'(b)=\frac1n\sum_i(b-y_i) =b-\frac1n\sum_i y_i=0.\]

Hence \(b^*=\frac1n\sum_i y_i\), the training-target mean. It need not be zero.

7.1 Compare each validation loss with the best value seen so far, resetting the counter only on a strict improvement:

Epoch Validation loss Best loss so far Checks without improvement Action
1 0.95 0.95 0 Save epoch 1
2 0.70 0.70 0 Save epoch 2
3 0.58 0.58 0 Save epoch 3
4 0.60 0.58 1 Keep epoch 3
5 0.62 0.58 2 Stop; restore epoch 3

The stopping epoch is 5, but the returned parameters come from epoch 3, where validation loss was 0.58.

7.2 A retrospective search over the complete table selects epoch 6, with loss 0.54. The online rule never observes that result. Patience is a choice, not a guarantee of finding the best future checkpoint.

7.3 Through epoch 5, decreasing training loss with rising validation loss is consistent with overfitting. It is not proof of a unique cause. Reasonable checks include split representativeness, preprocessing, validation-set size, and whether losses were measured consistently. Epoch 6 demonstrates that improvement can resume.

7.4 Selecting patience or lambda with test loss uses the test set for model selection, making the reported result optimistic as a final independent assessment. Fit on training data, tune on validation data, freeze the procedure, then evaluate once on an untouched test set. If the test set has already been used repeatedly for selection, it no longer provides that untouched assessment.

8.1 The loop records loss before updating the weight. At step 0:

\[L(2)=\tfrac12(2-3)^2=0.5,\qquad g_0=2-3=-1,\]

\[w_1=2-0.5(-1)=2.5.\]

At step 1, use this new weight:

\[L(2.5)=\tfrac12(-0.5)^2=0.125,\qquad g_1=2.5-3=-0.5,\]

\[w_2=2.5-0.5(-0.5)=2.75.\]

Collecting these results:

Loop step Weight before update Recorded loss Gradient Weight afterward
0 2 0.5 −1 2.5
1 2.5 0.125 −0.5 2.75

8.2 The final weight is 2.75 and history is [0.5, 0.125].

8.3 Its last entry describes the weight before the final update. The final loss is \(\frac12(2.75-3)^2=\frac12(-0.25)^2=\frac12(0.0625)=0.03125\). After the loop, add:

history.append(0.5 * (w - 3.0)**2)

8.4 gradient = w - 3.0 computes a derivative; w = w - eta * gradient updates the parameter. Backpropagation would compute derivatives for a larger computation graph. The optimizer would use those derivatives to update its parameters.

9.1 The code selects on training loss instead of validation loss. It also assigns another reference to the same mutable array; subsequent in-place updates change the purported saved checkpoint.

For example, suppose a checkpoint is saved when theta contains [1.0]. With best_theta = theta, both names refer to that array. If a later in-place update changes it to [1.5], best_theta also contains [1.5], even if validation never improved. A copy would retain [1.0].

9.2 The code should be:

if val_loss < best_loss:
    best_loss = val_loss
    best_theta = theta.copy()

9.3 This selects the best checkpoint seen during all 100 updates; it does not stop early. Add a counter of validation checks without improvement and terminate when it reaches the chosen patience, then return the saved parameters.

9.4 The selection rule uses validation to choose among trained candidates; it does not differentiate validation loss to fit parameters. Nevertheless, repeated choices can overfit the validation set, which is why a separate test set is needed for final evaluation.

Question 1 — Learning rates. The first two learning rates are stable over 100 updates; 0.18 diverges on this dataset. The curvature of this multi-parameter, scaled design differs from the scalar objective in Exercise 2, so its threshold cannot be transferred.

Question 2 — Patience and checkpoints. The complete unregularized run has final training loss about 0.0354 and validation loss 0.7366. Its best validation loss is about 0.0842 at update 295. Patience 50 stops at update 53 and returns update 3 (about 0.1925); patience 400 stops at update 695 and returns update 295.

Question 3 — Regularization comparison.

L2 strength Final training loss Final validation loss
0 0.0354 0.7366
0.001 0.0362 0.6809
0.01 0.0465 0.3585
0.05 0.0795 0.0913
0.1 0.0960 0.1046
0.5 0.1243 0.2496

Lambda 0.05 selects the best final model on this grid, but its validation loss is still above that of the best unregularized checkpoint. All values exclude the penalty so that models are compared using the same prediction metric. Penalized training objectives differ with lambda and are not a common selection metric. The ranking is evidence for this sample and budget, not a universal preference for one remedy. Some validation inputs lie outside the training range, so boundary extrapolation is relevant too.

12.6 Check your understanding

Without looking back, explain the difference between a parameter and a hyperparameter, between an optimizer and its objective, and between a stopping update and a selected checkpoint. Choose one calculation you initially got wrong and redo it with different numbers. For exam preparation, being able to explain the method matters more than recalling the reference values.