Skip to content

Instantly share code, notes, and snippets.

@PDiracDelta
Last active November 7, 2021 12:27
Show Gist options
  • Save PDiracDelta/747a67c7208688f24869f7e635eb4dbf to your computer and use it in GitHub Desktop.
Save PDiracDelta/747a67c7208688f24869f7e635eb4dbf to your computer and use it in GitHub Desktop.
Python3 log likelihood of Negative Binomial
# inspired by https://github.com/gokceneraslan/fit_nbinom/blob/master/fit_nbinom.py
import numpy as np
from scipy.special import gammaln
from scipy.misc import factorial
infinitesimal = np.finfo(np.float).eps
def log_likelihood(params, *args):
r, p = params
X = args[0]
N = X.size
result = np.sum(gammaln(X + r)) \
- np.sum(np.log(factorial(X))) \
- N * (gammaln(r)) \
+ np.sum(X * np.log(1 - (p if p < 1 else 1 - infinitesimal))) \
+ N * r * np.log(p)
return -result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment