You can visualize the loss landscape by perturbing model parameters along specific directions. Using the top Hessian eigenvector provides a more informative view of the landscape's curvature than random directions.
Workflow:
- Compute the top eigenvector using
hessian_comp.eigenvalues(). - Perturb the model parameters along that direction using a scalar $\lambda$.
- Measure the loss at each perturbation point.
Note: When perturbing, ensure you use a copy of the model to avoid modifying the original weights permanently.
# 1. Get top eigenvector
top_eigenvalues, top_eigenvector = hessian_comp.eigenvalues()
# 2. Define perturbation range
lams = np.linspace(-0.5, 0.5, 21).astype(np.float32)
# 3. Perturb and measure loss
loss_list = []
model_perb = copy_of_model
for lam in lams:
# Perturb model_perb along top_eigenvector[0] by amount 'lam'
model_perb = get_params(model, model_perb, top_eigenvector[0], lam)
loss_list.append(criterion(model_perb(inputs), targets).item())