-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlogsumexp.py
41 lines (34 loc) · 1.16 KB
/
logsumexp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# from https://raw.githubusercontent.com/scipy/scipy/v0.19.0/scipy/special/_logsumexp.py
import numpy as np
#from scipy._lib._util import _asarray_validated
def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):
#a = _asarray_validated(a, check_finite=False)
if b is not None:
a, b = np.broadcast_arrays(a,b)
if np.any(b == 0):
a = a + 0. # promote to at least float
a[b == 0] = -np.inf
a_max = np.amax(a, axis=axis, keepdims=True)
if a_max.ndim > 0:
a_max[~np.isfinite(a_max)] = 0
elif not np.isfinite(a_max):
a_max = 0
if b is not None:
b = np.asarray(b)
tmp = b * np.exp(a - a_max)
else:
tmp = np.exp(a - a_max)
# suppress warnings about log of zero
with np.errstate(divide='ignore'):
s = np.sum(tmp, axis=axis, keepdims=keepdims)
if return_sign:
sgn = np.sign(s)
s *= sgn # /= makes more sense but we need zero -> zero
out = np.log(s)
if not keepdims:
a_max = np.squeeze(a_max, axis=axis)
out += a_max
if return_sign:
return out, sgn
else:
return out