/W03
实验Lab: Gradient descent by hand
- Dataset
- Palmer penguins (344 rows, CC0)
- Time
- 2 to 3 hours
- Before you start
- slides ch 4 quiz ch 4 notebook (opens in a new tab)
This week you'll be able to
- Compute a gradient by hand and with code for a small function.
- Implement gradient descent and diagnose a learning rate that is too large or too small.
- Explain what momentum and Adam change about a gradient step.
Goal
Write gradient descent yourself, watch it fail with a bad learning rate, and fix it. Then check your answer against the closed form from week 2.
Data
import numpy as np
import pandas as pd
penguins = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv").dropna()
X = penguins[["flipper_length_mm", "bill_length_mm", "bill_depth_mm"]].to_numpy()
y = penguins["body_mass_g"].to_numpy()Tasks
- Write the mean squared error loss and its gradient for a linear model with weights and bias . Derive the gradient on paper first.
- Check your gradient numerically. Compare it with a finite-difference estimate at a random point. They should agree to about four decimal places.
- Run gradient descent on the raw features. Try learning rates of , and . Plot the loss curves and read them with Procedure 4.2. Which diverges? Which crawls?
- Standardise the features. Run it again. Choose a starting learning rate with Procedure 4.1. How many steps does it need now?
- Add momentum. Compare the loss curves with and without it.
- Compare your final weights with the normal-equation solution and with
scipy.optimize.minimize(Procedure 4.3). Remember to convert standardised weights back to the original units.
Deliverable
A notebook with the loss-curve plots for tasks 3 to 5 and a table of final weights from all three methods.
Done when
- The numerical gradient check passes.
- The loss plot shows at least one learning rate that diverges and one that converges.
- Final weights match the closed form to within 1%.
Stretch
Add a decaying learning rate (Procedure 4.4). Then implement Adam and compare its curve with momentum's.