Using The Methods Of Scipy's Rv_continuous When Creating A Cutom Continuous Distribution
I am trying to calculate E[f(x)] for some pdf that I generate/estimated from data. It says in the documentation: Subclassing New random variables can be defined by subclassing rv_
Solution 1:
For historical reasons, scipy distributions are instances, so that you need to have an instance of your subclass. For example:
>>> class MyRV(stats.rv_continuous):
... def _pdf(self, x, k):
... return k * np.exp(-k*x)
>>> my_rv = MyRV(name='exp', a=0.) # instantiation
Notice the need to specify the limits of the support: default values are a=-inf
and b=inf
.
>>> my_rv.a, my_rv.b
(0.0, inf)
>>> my_rv.numargs # gets figured out automagically
1
Once you've specified, say, _pdf
, you have a working distribution instance:
>>> my_rv.cdf(4, k=3)
0.99999385578764677
>>> my_rv.rvs(k=3, size=4)
array([ 0.37696127, 1.10192779, 0.02632473, 0.25516446])
>>> my_rv.expect(lambda x: 1, args=(2,)) # k=2 here
0.9999999999999999
Solution 2:
SciPy's rv_histogram method allows you to provide data and it provides the pdf, cdf and random generation methods.
Post a Comment for "Using The Methods Of Scipy's Rv_continuous When Creating A Cutom Continuous Distribution"