pymc.find_constrained_prior#

pymc.find_constrained_prior(distribution, lower, upper, init_guess, mass=0.95, fixed_params=None)[source]#

Find optimal parameters to get mass % of probability of pm_dist between lower and upper. Note: only works for one- and two-parameter distributions, as there are exactly two constraints. Fix some combination of parameters if you want to use it on >=3-parameter distributions.

Parameters
distributionpm.Distribution

PyMC distribution you want to set a prior on. Needs to have a logcdf method implemented in PyMC.

lowerfloat

Lower bound to get mass % of probability of pm_dist.

upperfloat

Upper bound to get mass % of probability of pm_dist.

init_guess: Dict[str, float]

Initial guess for scipy.optimize.least_squares to find the optimal parameters of pm_dist fitting the interval constraint. Must be a dictionary with the name of the PyMC distribution’s parameter as keys and the initial guess as values.

mass: float, default to 0.95

Share of the probability mass we want between lower and upper. Defaults to 95%.

fixed_params: Dict[str, float], Optional, default None

Only used when pm_dist has at least three parameters. Dictionary of fixed parameters, so that there are only 2 to optimize. For instance, for a StudenT, you fix nu to a constant and get the optimized mu and sigma.

Returns
The optimized distribution parameters as a dictionary with the parameters’
name as key and the optimized value as value.

Examples

# get parameters obeying constraints
opt_params = pm.find_constrained_prior(
    pm.Gamma, lower=0.1, upper=0.4, mass=0.75, init_guess={"alpha": 1, "beta": 10}
)

# use these parameters to draw random samples
samples = pm.Gamma.dist(**opt_params, size=100).eval()

# use these parameters in a model
with pm.Model():
    x = pm.Gamma('x', **opt_params)

# specify fixed values before optimization
opt_params = pm.find_constrained_prior(
    pm.StudentT,
    lower=0,
    upper=1,
    init_guess={"mu": 5, "sigma": 2},
    fixed_params={"nu": 7},
)