15

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.

1 Answer 1

32

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)
3
  • Why do you multiply by sqrt(0.1) instead of just 0.1? Commented Aug 6, 2020 at 14:03
  • 5
    Ah, the you use sqrt(0.1) because variance is standard deviation squared Commented Aug 6, 2020 at 14:08
  • 2
    A slight (more general) clarification, it's because if you have any random variable X with variance v and mean m, if you let Y = kX where k is a scalar, Y will have mean km but variance k^2 v. Since torch.randn is a normally distributed random variable (X with variance 1), if you want a variance of 0.1, you need to multiply by sqrt(0.1) so that the resulting variance will be sqrt(0.1)^2 = 0.1. Hope that's useful!
    – Joud C
    Commented Aug 11, 2023 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.