Evaluating (not Sampling from) Beta Distribution in Numpy
Asked Answered
L

1

8

I am trying to calculate Beta(x; a, b) for many specific values of x, taking a = 1, b = 25. There is a beta function in numpy, namely numpy.random.beta(a, b). But it samples from the beta distribution, rather than evaluating for specific values of x.

Any quick way around this, rather than having to code in the formula for beta?

Lansquenet answered 26/7, 2019 at 6:42 Comment(4)
So you want the beta pdf function?Couchman
Yes, the pdf Ok, I tried: from scipy.stats import beta print(beta.pdf(number,1,25)) But no matter what I put in for number, I always get 0.0. What's wrong? ThanksLansquenet
try beta(a, b).pdf(x)Couchman
print(beta(1,25).pdf(1.5)) still yields 0.0 :(Lansquenet
C
8

You are most likely looking for the scipy.stats.beta class. This lets you create a distribution for a particular pair of a, b values:

dist = scipy.stats.beta(a, b)

You can then get the PDF and evaluate at any x:

dist.pdf(x)

x can be any numpy array, not just a scalar. You can evaluate the cumulative distribution in a similar manner:

dist.cdf(x)

You don't even need to create an instance object. This is especially useful if you want to evaluate the function once. In your particular use-case, it would probably be better to create an instance:

scipy.stats.beta.pdf(x, a, b)

The same applies to the CDF. The linked documentation shows lots of other things you can do with the distribution object.

scipy.stats contains many of other common continuous distributions that all follow a similar interface. Any time you have a question related to basic statistics, scipy is the place to start.

Couchman answered 26/7, 2019 at 6:47 Comment(4)
@Warren. I don't think there's much ambiguity. A distribution is sampled according to its PDF, sort of by definition. I'd be happy to add the CDF as well. It's useful information, and there's a chance you may be right.Couchman
how to calculate PDF between two probabilities? I've tried dist.pdf(x2) - dist.pdf(x1) however it doesn't seem correct...Height
@haneulkim. I have no idea what that means. Consider asking a question with an MCVE. You can ping me here when you do if you want me to take a look.Couchman
@Height coming back to your question some years later, I'm pretty sure you want the difference between the CDFs, which gives you the area of the PDF between those points.Couchman

© 2022 - 2024 — McMap. All rights reserved.