hanugm
hanugm

Reputation: 1387

Getting the probability density value for a given distribution in PyTorch

Consider the following code for generating a random sample from a normal distribution with given mean and standard deviation

# import the torch module
import torch

# create the mean with 5 values
mean = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])

# create the standard deviation with 5 values
std = torch.tensor([1.22, 0.78, 0.56, 1.23, 0.23])

# create normal distribution
print(torch.normal(mean, std))

Output:

tensor([-0.0367,  1.7494,  2.3784,  4.2227,  5.0095])

But I want to calculate the probability density value of the normal distribution for a particular sample given the mean and standard deviation. Is there any function available in PyTorch for doing the same?

Note that I can get the pdf value by coding the analytical expression for the normal distribution with the given mean and standard deviation. But, I want to use an inbuilt from PyTorch.

Upvotes: 1

Views: 4040

Answers (1)

dx2-66
dx2-66

Reputation: 2851

There's torch.distributions, providing some helpful methods. How about:

dist = torch.distributions.normal.Normal(mean, std)
print(torch.exp(dist.log_prob(torch.Tensor(my_value))))

The result seems to be the same as scipy.stats.norm.pdf() yields.

Upvotes: 5

Related Questions