Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does log_prob do?

In some (e.g. machine learning) libraries, we can find log_prob function. What does it do and how is it different from taking just regular log?

For example, what is the purpose of this code:

dist = Normal(mean, std)
sample = dist.sample()
logprob = dist.log_prob(sample)

And subsequently, why would we first take a log and then exponentiate the resulting value instead of just evaluating it directly:

prob = torch.exp(dist.log_prob(sample))
like image 982
cerebrou Avatar asked Feb 11 '19 16:02

cerebrou


People also ask

What does categorical do in Pytorch?

Categorical. Creates a categorical distribution parameterized by either probs or logits (but not both). It is equivalent to the distribution that torch.


2 Answers

As your own answer mentions, log_prob returns the logarithm of the density or probability. Here I will address the remaining points in your question:

  • How is that different from log? Distributions do not have a method log. If they did, the closest possible interpretation would indeed be something like log_prob but it would not be a very precise name since if begs the question "log of what"? A distribution has multiple numeric properties (for example its mean, variance, etc) and the probability or density is just one of them, so the name would be ambiguous.

The same does not apply to the Tensor.log() method (which may be what you had in mind) because Tensor is itself a mathematical quantity we can take the log of.

  • Why take the log of a probability only to exponentiate it later? You may not need to exponentiate it later. For example, if you have the logs of probabilities p and q, then you can directly compute log(p * q) as log(p) + log(q), avoiding intermediate exponentiations. This is more numerically stable (avoiding underflow) because probabilities may become very close to zero while their logs do not. Addition is also more efficient than multiplication in general, and its derivative is simpler. There is a good article about those topics at https://en.wikipedia.org/wiki/Log_probability.
like image 95
user118967 Avatar answered Jan 04 '23 09:01

user118967


Part of the answer is that log_prob returns the log of the probability density/mass function evaluated at the given sample value.

like image 24
cerebrou Avatar answered Jan 04 '23 09:01

cerebrou