# How to add noise to image in denoising autoencoders

**URL:** <https://discuss.pytorch.org/t/how-to-add-noise-to-image-in-denoising-autoencoders/87755>\
**Category:** Uncategorized\
**Created:** [July 2, 2020, 4:12pm UTC](https://discuss.pytorch.org/t/how-to-add-noise-to-image-in-denoising-autoencoders/87755 "2020-07-02T16:12:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![arjun\_pukale](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/arjun_pukale/32/22716_2.png) [@arjun\_pukale](https://discuss.pytorch.org/u/arjun_pukale)\
**Post date:** [July 2, 2020, 4:12pm UTC](https://discuss.pytorch.org/t/how-to-add-noise-to-image-in-denoising-autoencoders/87755/1 "2020-07-02T16:12:58Z")

</div>

I want to implement denoising autoencoder in pytorch.  
when I am in the training loop:

```auto
for inputs,labels in trainloader:
        noised_inputs=add_noise(inputs)
        opt.zero_grad()
        outputs = net(noised_inputs)
        loss = loss_fn(outputs,inputs)
        loss.backward()
        opt.step()

```

Please tell me how to implement this add\_noise function which can add gaussian noise to the entire batch input of images

---

<div class="post-metadata">

**Author:** ![chetan\_patil](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/chetan_patil/32/25122_2.png) [@chetan\_patil](https://discuss.pytorch.org/u/chetan_patil)\
**Post date:** [July 2, 2020, 4:21pm UTC](https://discuss.pytorch.org/t/how-to-add-noise-to-image-in-denoising-autoencoders/87755/2 "2020-07-02T16:21:54Z")

</div>

You can use the `torch.randn_like()` function to create a noisy tensor of the same size of input. Then add it.  
In your case ,

```auto
def add_noise(inputs):
     noise = torch.randn_like(inputs)
     return inputs + noise

```

---

<div class="post-metadata">

**Author:** ![arjun\_pukale](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/arjun_pukale/32/22716_2.png) [@arjun\_pukale](https://discuss.pytorch.org/u/arjun_pukale)\
**Post date:** [July 2, 2020, 5:23pm UTC](https://discuss.pytorch.org/t/how-to-add-noise-to-image-in-denoising-autoencoders/87755/3 "2020-07-02T17:23:50Z")

</div>

It worked!!! also we can multiply it with factor like 0.2 to reduce the noise

```auto
def add_noise(inputs):
     noise = torch.randn_like(inputs)*0.2
     return inputs + noise

```

Original Image:  
 ![image](https://discuss.pytorch.org/uploads/default/original/3X/6/8/68fc26730ef15656a2e57a90e5e98a34e3d473d8.png)

Noised Image:  
 ![image](https://discuss.pytorch.org/uploads/default/original/3X/b/8/b88a5f50c2770f99cefa09715a4c02d1904ed6bf.png)
