# 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:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kalamaya](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/kalamaya/32/381_2.png) [@Kalamaya](https://discuss.pytorch.org/u/Kalamaya)\
**Post date:** [January 22, 2017, 10:47pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/1 "2017-01-22T22:47:38Z")

</div>

Hi, does simple L2 / L1 regularization exist in pyTorch? I did not see anything like that in the losses.

I guess the way we could do it is simply have the data\_loss + reg\_loss computed, (I guess using nn.MSEloss for the L2), but is an explicit way we can use it without doing it this way?

Thanks

---

<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.

---

<div class="post-metadata">

**Author:** ![Kalamaya](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/kalamaya/32/381_2.png) [@Kalamaya](https://discuss.pytorch.org/u/Kalamaya)\
**Post date:** [January 22, 2017, 11:15pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/3 "2017-01-22T23:15:55Z")

</div>

Thanks @fmassa - although I must say that’s odd that a regularization loss in included in the _optimizer_ here. 0\_0

---

<div class="post-metadata">

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

</div>

Yeah, that’s been added there as an optimization, as L2 regularization is often used.

---

<div class="post-metadata">

**Author:** ![Kalamaya](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/kalamaya/32/381_2.png) [@Kalamaya](https://discuss.pytorch.org/u/Kalamaya)\
**Post date:** [January 23, 2017, 12:38am UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/5 "2017-01-23T00:38:18Z")

</div>

Got it thanks! 🙂

---

<div class="post-metadata">

**Author:** ![ecolss](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ecolss/32/5045_2.png) [@ecolss](https://discuss.pytorch.org/u/ecolss)\
**Post date:** [March 11, 2017, 1:36am UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/6 "2017-03-11T01:36:08Z")

</div>

what do you recommend which would be a better way to enforce sparsity instead of L1?

---

<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:** [March 11, 2017, 11:05am UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/7 "2017-03-11T11:05:27Z")

</div>

This comment might be helpful [https://github.com/torch/optim/pull/41#issuecomment-73935805](https://github.com/torch/optim/pull/41#issuecomment-73935805)

---

<div class="post-metadata">

**Author:** ![ecolss](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ecolss/32/5045_2.png) [@ecolss](https://discuss.pytorch.org/u/ecolss)\
**Post date:** [March 11, 2017, 1:12pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/8 "2017-03-11T13:12:34Z")

</div>

Thanks for the note 🙂

---

<div class="post-metadata">

**Author:** ![ncullen93](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ncullen93/32/68760_2.png) [@ncullen93](https://discuss.pytorch.org/u/ncullen93)\
**Post date:** [April 12, 2017, 9:23pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/9 "2017-04-12T21:23:14Z")

</div>

@fmassa does this still work? It seems that `nn.L1Loss` requires a target - giving the error `TypeError: forward() missing 1 required positional argument: 'target'`

example:

```python
xx = nn.Parameter(torch.from_numpy(np.ones((3,3))))
l1_crit = nn.L1Loss()
l1_crit(xx)

```

---

<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:** [April 13, 2017, 10:14am UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/10 "2017-04-13T10:14:47Z")

</div>

I forgot to add the `target`, which in some cases would be a zero-tensor.  
So something like

```python
xx = nn.Parameter(torch.from_numpy(np.ones((3,3))))
target = Variable(torch.from_numpy(np.zeros((3,3))))
l1_crit = nn.L1Loss()
l1_crit(xx, target)

```

---

<div class="post-metadata">

**Author:** ![Ja-Keoung\_Koo](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ja-keoung_koo/32/12628_2.png) [@Ja-Keoung\_Koo](https://discuss.pytorch.org/u/Ja-Keoung_Koo)\
**Post date:** [May 6, 2017, 4:43am UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/11 "2017-05-06T04:43:58Z")

</div>

I have two questions about L1 regularization:

- How do we backpropagate for L1 regularization? I wonder it because the term is not differentiable.

- Where can I see the implementation of L1 regularization? In the following link, there is only `pass`.

> <https://github.com/pytorch/pytorch/blob/ecd51f8510bb1c593b0613f3dc7caf31dc29e16b/torch/nn/modules/loss.py#L39>

---

<div class="post-metadata">

**Author:** ![smth](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/smth/32/13_2.png) [@smth](https://discuss.pytorch.org/u/smth)\
**Post date:** [May 7, 2017, 2:31pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/12 "2017-05-07T14:31:57Z")

</div>

you can see the implementation of L1Loss here: [https://github.com/pytorch/pytorch/blob/ecd51f8510bb1c593b0613f3dc7caf31dc29e16b/torch/lib/THNN/generic/L1Cost.c](https://github.com/pytorch/pytorch/blob/ecd51f8510bb1c593b0613f3dc7caf31dc29e16b/torch/lib/THNN/generic/L1Cost.c)

---

<div class="post-metadata">

**Author:** ![gwg](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/gwg/32/1367_2.png) [@gwg](https://discuss.pytorch.org/u/gwg)\
**Post date:** [September 14, 2017, 6:31pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/13 "2017-09-14T18:31:22Z")

</div>

@fmassa, so because of PyTorch’s autograd functionality, we do not need to worry about L1 regularization during the backward pass, i.e. applying the derivative of the L1 regularization term to the gradient of the output? That will be handled by the autograd variables?

---

<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:** [September 17, 2017, 12:06pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/14 "2017-09-17T12:06:07Z")

</div>

If you add the L1 regularization to the loss as I explained in a previous post, the gradients will be handled by autograd automatically.

---

<div class="post-metadata">

**Author:** ![yibo](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/yibo/32/2861_2.png) [@yibo](https://discuss.pytorch.org/u/yibo)\
**Post date:** [December 26, 2017, 7:15pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/15 "2017-12-26T19:15:49Z")

</div>

I like to use `l1_loss=F.l1_loss(xx, target=torch.zeros_like(xx), size_average=False)`

---

<div class="post-metadata">

**Author:** ![Brando\_Miranda](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/brando_miranda/32/14355_2.png) [@Brando\_Miranda](https://discuss.pytorch.org/u/Brando_Miranda)\
**Post date:** [February 3, 2018, 10:59pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/16 "2018-02-03T22:59:22Z")

</div>

if I want to use a custom Regularizer `R` can is the following code good:

```
batch_loss = loss(input=y_pred,target=batch_ys)
batch_loss += lambda*R

```

?

---

<div class="post-metadata">

**Author:** ![hughperkins](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/hughperkins/32/915_2.png) [@hughperkins](https://discuss.pytorch.org/u/hughperkins)\
**Post date:** [June 4, 2018, 12:59am UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/17 "2018-06-04T00:59:52Z")

</div>

@fmassa You say “this might not be the best way of enforcing sparsity on the model”, and “This comment might be helpful [https://github.com/torch/optim/pull/41#issuecomment-73935805](https://github.com/torch/optim/pull/41#issuecomment-73935805) 1.2k”, which comment explains to explicitly set to 0 any weights changing sign. Does this mean that you feel that L1 with explicit zeroing of weights crossing zero is an appropriate way of encouraging sparsity? Or do you mean, there are some other approach(es) that can work well?

---

<div class="post-metadata">

**Author:** ![Neta\_Zmora](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/neta_zmora/32/23393_2.png) [@Neta\_Zmora](https://discuss.pytorch.org/u/Neta_Zmora)\
**Post date:** [June 8, 2018, 5:48pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/18 "2018-06-08T17:48:25Z")

</div>

Hi @hughperkins,

If you are interested in inducing sparsity, you might want to checkout [this project](https://github.com/NervanaSystems/distiller) from Intel AI Labs. The [documentation](https://nervanasystems.github.io/distiller/index.html) tries to shed some light on recent research related to sparsity inducing methods.

The project includes a stand-alone Jupyter [notebook that attempts to show how L1 regularization](https://github.com/NervanaSystems/distiller/blob/master/jupyter/L1-regularization.ipynb) can be used to induce sparsity (by “stand-alone” I mean that the notebook does not import any code from Distiller, so you can just try it out).

Cheers,  
Neta

---

<div class="post-metadata">

**Author:** ![shirui-japina](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/shirui-japina/32/15285_2.png) [@shirui-japina](https://discuss.pytorch.org/u/shirui-japina)\
**Post date:** [September 22, 2019, 7:00am UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/19 "2019-09-22T07:00:29Z")

</div>

Sorry for question here.  
It is said that when regularization L2, it should **only** for **weight parameters** , but not **bias parameters**.(Is it right?😳)  
But the L2 regularization included in most optimizers in PyTorch, is for all of the parameters in the model (weight and bias).  
 ![least_squares_l2](https://discuss.pytorch.org/uploads/default/original/3X/3/2/32a7aae3a3acf117c289c5561aca95ca064c3fe3.png)  
I mean the parameters in the red box should be weight parameters only. (If what I heard of is right.)  
How can I deal with it?

```auto
weight_p, bias_p = [],[]
for name, p in model.named_parameters():
  if 'bias' in name:
    bias_p += [p]
  else:
    weight_p += [p]

optim.SGD(
  [
    {'params': weight_p, 'weight_decay':1e -5},
    {'params': bias_p, 'weight_decay':0}
  ],
  lr=1e-2, momentum=0.9
)

```

Code here can deal with the problem above, is it right?😳😳

---

<div class="post-metadata">

**Author:** ![Deepak](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/deepak/32/18744_2.png) [@Deepak](https://discuss.pytorch.org/u/Deepak)\
**Post date:** [April 25, 2020, 4:19pm UTC](https://discuss.pytorch.org/t/simple-l2-regularization/139/20 "2020-04-25T16:19:27Z")

</div>

We do regularization to handle the high variance problem (overfitting). It’s good if the regularization includes all the learnable parameters (both weight and bias). But since bias is only a single parameter out of the large number of parameters, it’s usually not included in the regularization; and exclusion of bias hardly affects the results.

[Next page](https://discuss.pytorch.org/t/simple-l2-regularization/139.md?page=2)
