pytorch l2 code example
Example 1: pytorch l2 regularization
# add l2 regularization to optimzer by just adding in a weight_decay
optimizer = torch.optim.Adam(model.parameters(),lr=1e-4,weight_decay=1e-5)
Example 2: Regularization pytorch
loss = mse(pred, target)
l1 = 0
for p in net.parameters():
l1 = l1 + p.abs().sum()
loss = loss + lambda_l1 * l1
loss.backward()
optimizer.step()