-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.py
77 lines (63 loc) · 1.92 KB
/
utils.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import numpy as np
from scipy.misc import factorial
def loggamma_vec(x_vec, a, b):
"""
sum_i log Gamma(x_vec[i], a[i], b[i])
Parameters
----------
x_vec : np.array
a : np.array or float
b : np.array or float
Returns
-------
float
"""
p_x = a * np.log(b) - np.log(factorial(a - 1.0)) + (a - 1.0) * np.log(x_vec) - b * x_vec
return np.sum(p_x)
def logpoisson_vec(lam_vec, x_vec):
"""
sum_i logPoisson(lam_vec[i], x_vec[i])
Parameters
----------
lam_vec : np.array
1 dimensional (D,) size numpy array for the Poisson mean
x_vec : np.array
1 dimensional (D,) size numpy array
Returns
-------
float
"""
lam_vec = np.array(lam_vec)
if np.prod(lam_vec) == 0:
for i, l in enumerate(lam_vec):
if l == 0:
lam_vec[i] = 1e-7
x_vec = np.array(x_vec)
return np.sum(-lam_vec + x_vec * np.log(lam_vec) - np.log(factorial(x_vec)))
def logpoisson_vec_all(lam_vec, x_mat, gam_prior=False, a=1.0, b=1.0):
"""
Get an array of log likelihood for each x_mat[i], using lam_vec
loglik[i] = logpoisson_vec(lam_vec, x_mat[i])
Parameters
----------
lam_vec : np.array
1 dimensional (D,) size numpy array for the Poisson mean
x_mat : np.array
2 dimensional (N, D) size numpy array
Returns
-------
np.array
(N,) size log probabilities
"""
logprob= np.zeros(x_mat.shape[0])
if gam_prior:
for i in range(x_mat.shape[0]):
xi = x_mat[i]
const = np.log(factorial(a + xi - 1)) - np.log(factorial(a - 1)) \
- np \
.log ( factorial(xi)) + a* np.log(b) - (a + xi)* np.log(b+1)
logprob[i] = loggamma_vec( lam_vec, a+xi, b+1) + np.sum(const)
else:
for i in range(x_mat.shape[0]):
logprob[i] = logpoisson_vec(lam_vec, x_mat[i])
return logprob