# Simple L2 regularization?

**URL:** <https://discuss.pytorch.org/t/simple-l2-regularization/139>\
**Category:** Uncategorized\
**Created:** [January 22, 2017, 10:47pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139 "2017-01-22T22:47:38Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![fmassa](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/fmassa/32/58_2.png) [@fmassa](https://discuss.pytorch.org/u/fmassa)\
**Post date:** [January 22, 2017, 11:04pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/2 "2017-01-22T23:04:44Z")

</div>

Hi,

The L2 regularization on the parameters of the model is already included in most optimizers, including `optim.SGD` and can be controlled with the `weight_decay` parameter as can be seen in [the SGD documentation](http://pytorch.org/docs/optim.html#torch.optim.SGD).

L1 regularization is not included by default in the optimizers, but could be added by including an extra loss `nn.L1Loss` in the weights of the model.

```python
l1_crit = nn.L1Loss(size_average=False)
reg_loss = 0
for param in model.parameters():
    reg_loss += l1_crit(param)

factor = 0.0005
loss += factor * reg_loss

```

Note that this might not be the best way of enforcing sparsity on the model though.

---

_[View the full topic](https://discuss.pytorch.org/t/simple-l2-regularization/139)._
