Created
March 8, 2022 15:05
-
-
Save seungwonpark/f4e60e13e011d1148fce9f4a88273f12 to your computer and use it in GitHub Desktop.
Optimizing arbitrary parameter using Adam optimizer from PyTorch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
import torch.nn as nn | |
LEARNING_RATE = 3e-4 | |
# we consider a toy example: minimize the squared value of single vector. | |
x = torch.randn(5) | |
m = nn.MSELoss() # for calculating loss | |
optimizer = torch.optim.Adam([x.requires_grad_()], lr=LEARNING_RATE) | |
# through this iteration, we can observe that the values (slowly) converge to 0. | |
# use larger LEARNING_RATE if you want a faster convergence. | |
for step in range(10): | |
print(x) | |
loss = m(x, torch.zeros(5)) | |
loss.backward() | |
optimizer.step() | |
optimizer.zero_grad() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: