Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add some Gaussian noise to a tensor in PyTorch?

Tags:

pytorch

I have a tensor I created using

    temp = torch.zeros(5, 10, 20, dtype=torch.float64)
    ## some values I set in temp

Now I want to add to each temp[i,j,k] a Gaussian noise (sampled from normal distribution with mean 0 and variance 0.1). How do I do it? I would expect there is a function to noise a tensor, but couldn't find anything. I did find this:

How to add Poisson noise and Gaussian noise?

but it seems to be related to images.

like image 749
kloop Avatar asked Nov 28 '19 13:11

kloop


People also ask

How do you add Gaussian noise in Pytorch?

AddGaussianNoise adds gaussian noise using the specified mean and std to the input tensor in the preprocessing of the data. torch. randn creates a tensor filled with random numbers from the standard normal distribution (zero mean, unit variance) as described in the docs. In AddGaussianNoise.

How do you make a Gaussian noise?

White Gaussian Noise can be generated using randn function in Matlab which generates random numbers that follow a Gaussian distribution. Similarly, rand function can be used to generate Uniform White Noise in Matlab that follows a uniform distribution.


1 Answers

The function torch.randn produces a tensor with elements drawn from a Gaussian distribution of zero mean and unit variance. Multiply by sqrt(0.1) to have the desired variance.

x = torch.zeros(5, 10, 20, dtype=torch.float64)
x = x + (0.1**0.5)*torch.randn(5, 10, 20)
like image 185
iacolippo Avatar answered Sep 25 '22 09:09

iacolippo