Home > Net >  Pythonic way to calculate cumulative sum with complex math over numpy array
Pythonic way to calculate cumulative sum with complex math over numpy array

Time:10-03

I'm performing Data Science and am calculating the Log Likelihood of a Poisson Distribution of arrival times.

def LogLikelihood(arrival_times, _lambda):
  """Calculate the likelihood that _lambda predicts the arrival_times well."""
  ll = 0
  for t in arrival_times:
    ll  = -(_lambda)   t*np.log(_lambda) - np.log(factorial(t))
  return ll

Mathematically, the expression is on the last line:

Text

Is there a more pythonic way to perform this sum? Perhaps in one line?

CodePudding user response:

Seems perfectly Pythonic to me; but since numpy is already here, why not to vectorize the whole thing?

return (
    -_lambda
      arrival_times * np.log(_lambda)
    - np.log(np.vectorize(np.math.factorial)(arrival_times))
).sum()

CodePudding user response:

This looks ugly to me but it fits a single line:

def LogLikelihood(arrival_times, _lambda):
    return np.cumsum(list(map(lambda t: -(_lambda)   t*np.log(_lambda) - np.log(factorial(t)),arrival_times)))[-1]
  • Related