Search code examples
pythonrandompytorchnormal-distribution

Normally distributed vector given mean, stddev|variance


how to do this in torch

 np.random.normal(loc=mean,scale=stdev,size=vsize)

i.e. by providing mean, stddev or variance


Solution

  • There's a similar torch function torch.normal:

    torch.normal(mean=mean, std=std)
    

    If mean and std are scalars, this will produce a scalar value. You can simply repeat them for the target you want it to be, eg:

    mean = 2
    std = 10
    size = (3,3)
    r = torch.normal(mean=torch.full(size,mean).float(),std=torch.full(size,mean).float())
    print(r)
    
    > tensor([[ 2.2263,  1.1374,  4.5766],
        [ 3.4727,  2.6712,  2.4878],
        [-0.1787,  2.9600,  2.7598]])