I am trying to fit my data to a Negative Binomial Distribution with the package scipy in Python. However, my validation seems to fail.
These are my steps:
- I have some demand data which is described by the statistics:
mu = 1.4
std = 1.59
print(mu, std)
- I use the parameterization function below, taken from this post to compute the two NB parameters.
def convert_params(mu, theta):
"""
Convert mean/dispersion parameterization of a negative binomial to the ones scipy supports
See https://en.wikipedia.org/wiki/Negative_binomial_distribution#Alternative_formulations
"""
r = theta
var = mu + 1 / r * mu ** 2
p = (var - mu) / var
return r, 1 - p
I pass (hopefully correctly...) my two statistics - the naming convention between different sources is rather confusing at this point p
, r
, k
firstParam, secondParam = convert_params(mu, std)
- I would then use these two parameters to fit the distribution:
from scipy.stats import nbinom
rv = nbinom(firstParam, secondParam)
Then I calculate a value R
with the Percent Point Function .ppf(0.95)
. The value R
in the context of my problem is a Reorder Point.
R = rv.ppf(0.95)
- Now is when I expect to validate the previous steps, but I do not manage to retrieve my original statistics
mu
andstd
withmean
andmath.sqrt(var)
respectively.
import math
mean, var = nbinom.stats(firstParam, secondParam, moments='mv')
print(mean, math.sqrt(var))
What am I missing? Any feedback about the parameterization implemented in Scipy
?