◢◤ ARKANE_
SYS_TIME UTC+0
Work with me
/W03

实验Lab: Gradient descent by hand

week 3
Dataset
Palmer penguins (344 rows, CC0)
Time
2 to 3 hours

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

  1. Write the mean squared error loss and its gradient for a linear model with weights ww and bias bb. Derive the gradient on paper first.
  2. Check your gradient numerically. Compare it with a finite-difference estimate at a random point. They should agree to about four decimal places.
  3. Run gradient descent on the raw features. Try learning rates of 10−210^{-2}, 10−510^{-5} and 10−710^{-7}. Plot the loss curves and read them with Procedure 4.2. Which diverges? Which crawls?
  4. Standardise the features. Run it again. Choose a starting learning rate with Procedure 4.1. How many steps does it need now?
  5. Add momentum. Compare the loss curves with and without it.
  6. 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.

online /teaching/semester-1/labs/3 Newcastle, UK v0.1.0 // rss