Implement Custom SGD Optimizer
Problem Statement
Implement a basic SGD optimizer from scratch by subclassing torch.optim.Optimizer.
Background
Building a custom optimizer teaches the fundamentals: iterate parameter groups, access .grad, and update .data in-place.
Your Task
The starter code defines a SimpleSGD class with init already implemented. Implement the step method that applies the basic SGD update rule to each parameter that has a gradient.
The training loop and verification are pre-filled.
Output Format
Returns a dictionary with "initial_weight", "final_weight", "weight_changed", and "is_optimizer".
Example
None
{'initial_weight': [0.7645, -0.8049, 0.2343], 'final_weight': [0.8373, -0.3944, 0.9289], 'weight_changed': True, 'is_optimizer': True}- We start by defining the
SimpleSGDclass, which inherits fromtorch.optim.Optimizer, and create an instance of it with a learning rate of 0.1. - We then create a
nn.Linear(3, 1)model, record its initial weights, and run 5 training steps using theSimpleSGDoptimizer with mean squared error (MSE) loss: , where is the target and is the predicted output. - In each training step, the weights are updated according to the SGD update rule: , where is the learning rate and is the gradient of the loss with respect to the parameter.
- After the training steps, we record the final weights and compare them to the initial weights to determine if the weights have changed, and check if
SimpleSGDis an instance oftorch.optim.Optimizerto determine the value of"is_optimizer".
Constraints
- Subclass torch.optim.Optimizer
- Implement step() with basic SGD update rule
- Use @torch.no_grad() for step method