-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsgd.py
35 lines (29 loc) · 1.18 KB
/
sgd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from torch.optim import Optimizer
# adapted from pytorch official implementation.
class SGD_Simple(Optimizer):
r"""Implements stochastic gradient descent.
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float): learning rate
"""
def __init__(self, params, lr, weight_decay=0):
print("Using optimizer: SGD_Simple")
if lr < 0.0:
raise ValueError("Invalid learning rate: {}".format(lr))
if weight_decay < 0.0:
raise ValueError("Invalid weight decay: {}".format(weight_decay))
defaults = dict(lr=lr, weight_decay=weight_decay)
super(SGD_Simple, self).__init__(params, defaults)
def step(self):
"""Performs a single optimization step.
"""
for group in self.param_groups:
weight_decay = group['weight_decay']
for p in group['params']:
if p.grad is None:
continue
d_p = p.grad.data
if weight_decay != 0:
d_p.add_(weight_decay, p.data)
p.data.add_(-group['lr'], d_p)