Skip to content

Commit 8b3f72e

Browse files
committed
add a misc utils file for common math functions
1 parent 0bd908a commit 8b3f72e

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

numpy_ml/utils/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
"""Utilities module"""
2+
13
from . import testing
24
from . import data_structures
35
from . import distance_metrics
46
from . import kernels
57
from . import windows
68
from . import graphs
9+
from . import misc

numpy_ml/utils/misc.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""Miscellaneous utility functions"""
2+
import numpy as np
3+
4+
5+
def logsumexp(log_probs, axis=None):
6+
"""
7+
Redefine scipy.special.logsumexp
8+
see: http://bayesjumping.net/log-sum-exp-trick/
9+
"""
10+
_max = np.max(log_probs)
11+
ds = log_probs - _max
12+
exp_sum = np.exp(ds).sum(axis=axis)
13+
return _max + np.log(exp_sum)
14+
15+
16+
def log_gaussian_pdf(x_i, mu, sigma):
17+
"""Compute log N(x_i | mu, sigma)"""
18+
n = len(mu)
19+
a = n * np.log(2 * np.pi)
20+
_, b = np.linalg.slogdet(sigma)
21+
22+
y = np.linalg.solve(sigma, x_i - mu)
23+
c = np.dot(x_i - mu, y)
24+
return -0.5 * (a + b + c)

0 commit comments

Comments
 (0)