Skip to content

Instantly share code, notes, and snippets.

@PDiracDelta
Last active November 7, 2021 16:48
Show Gist options
  • Save PDiracDelta/afe319c332cf3e765906a022909f9956 to your computer and use it in GitHub Desktop.
Save PDiracDelta/afe319c332cf3e765906a022909f9956 to your computer and use it in GitHub Desktop.
Python3 use fmin_l_bfgs_b to get MLE of Negative Binomial
from scipy.optimize import fmin_l_bfgs_b
""" Get reasonable initial values """
# estimates from fitdistr function in R
m = np.mean(X)
v = np.var(X)
size = (m ** 2) / (v - m) if v > m else 1
# convert mu/size parametrization to prob/size
p0 = size / ((size + m) if size + m != 0 else 1)
r0 = size
initial_params = np.array([r0, p0])
""" Obtain MLE of parameters """
optimized_result = fmin_l_bfgs_b(log_likelihood,
x0=initial_params,
args=(X_raw,),
approx_grad=True,
bounds=[(infinitesimal, None), (infinitesimal, 1)])
MLE_params = {'size': optimized_result[0][0], 'prob': optimized_result[0][1]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment