Optimizers help a machine learning model learn by adjusting its settings to make better guesses.
Optimizers (SGD, Adam) in PyTorch
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # or optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
SGD stands for Stochastic Gradient Descent, a simple way to update model settings.
Adam is a smarter optimizer that adapts learning rates for each setting automatically.
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)optimizer = torch.optim.Adam(model.parameters(), lr=0.001)optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
This code trains a simple model to learn the rule y = 2x + 1 using SGD optimizer. It prints loss each step and shows prediction for input 5.
import torch import torch.nn as nn import torch.optim as optim # Simple model: one linear layer model = nn.Linear(1, 1) # Data: y = 2x + 1 x = torch.tensor([[1.0], [2.0], [3.0], [4.0]]) y = torch.tensor([[3.0], [5.0], [7.0], [9.0]]) # Choose optimizer: SGD or Adam optimizer = optim.SGD(model.parameters(), lr=0.1) # optimizer = optim.Adam(model.parameters(), lr=0.1) # Loss function criterion = nn.MSELoss() # Training loop for epoch in range(10): optimizer.zero_grad() # Clear old gradients outputs = model(x) # Predict loss = criterion(outputs, y) # Calculate loss loss.backward() # Calculate gradients optimizer.step() # Update model print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}") # Final prediction test_input = torch.tensor([[5.0]]) prediction = model(test_input).item() print(f"Prediction for input 5: {prediction:.2f}")
SGD is simple and works well for many problems but may need tuning of learning rate.
Adam often works better without much tuning because it adjusts learning rates automatically.
Always clear gradients with optimizer.zero_grad() before backpropagation.
Optimizers help models learn by updating their settings to reduce mistakes.
SGD is a basic optimizer; Adam is more advanced and adapts learning rates.
Choosing the right optimizer and learning rate affects how fast and well your model learns.
Practice
Solution
Step 1: Understand optimizer behavior
Adam optimizer adjusts learning rates for each parameter based on past gradients.Step 2: Compare with SGD
SGD uses a fixed learning rate for all parameters without adaptation.Final Answer:
Adam -> Option AQuick Check:
Adaptive learning rate = Adam [OK]
- Confusing SGD as adaptive optimizer
- Thinking RMSprop is the only adaptive optimizer
- Assuming Adagrad is default in PyTorch
Solution
Step 1: Check PyTorch optimizer syntax
Correct syntax uses torch.optim.SGD with model.parameters() and lr argument.Step 2: Identify errors in other options
The option with torch.SGD(model.parameters(), learning_rate=0.01) uses wrong module and argument name; the option with Adam uses wrong optimizer; the option passing model instead of parameters is incorrect.Final Answer:
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) -> Option DQuick Check:
Correct syntax = optimizer = torch.optim.SGD(model.parameters(), lr=0.01) [OK]
- Passing model instead of model.parameters()
- Using wrong argument name like learning_rate
- Confusing Adam with SGD
import torch import torch.nn as nn model = nn.Linear(2, 1) optimizer = torch.optim.SGD(model.parameters(), lr=0.1) criterion = nn.MSELoss() inputs = torch.tensor([[1.0, 2.0]]) target = torch.tensor([[1.0]]) optimizer.zero_grad() output = model(inputs) loss = criterion(output, target) loss.backward() optimizer.step() print(round(loss.item(), 3))
Solution
Step 1: Understand loss calculation
Loss depends on random initial weights of model, so exact value varies each run.Step 2: Check code behavior
Since weights are random, output and loss are not fixed; cannot predict exact loss value.Final Answer:
Cannot determine exact value -> Option CQuick Check:
Random init means loss unknown [OK]
- Assuming fixed loss value without checking randomness
- Ignoring model initialization effect
- Confusing loss before and after optimizer step
optimizer = torch.optim.Adam(model.parameters, lr=0.001)
Solution
Step 1: Check method usage
model.parameters is a method and must be called with parentheses to get parameters.Step 2: Validate other options
Adam accepts lr argument; SGD is not mandatory; lr can be float.Final Answer:
model.parameters should be called as model.parameters() -> Option BQuick Check:
Call parameters() method correctly [OK]
- Forgetting parentheses on model.parameters
- Thinking Adam can't take lr argument
- Assuming lr must be integer
Solution
Step 1: Consider optimizer suitability for noisy data
Adam adapts learning rates and handles noisy gradients better than SGD.Step 2: Choose appropriate learning rate
Typical starting lr for Adam is 0.001; too high (0.1) can cause instability.Final Answer:
Adam with lr=0.001 -> Option AQuick Check:
Adaptive optimizer + moderate lr = Adam 0.001 [OK]
- Using too high learning rate with Adam
- Choosing SGD for noisy data without adaptation
- Confusing learning rate scales
Ready to prove it?
Pass the test and this pattern moves unknown
