forked from ddbourgin/numpy-ml
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add a misc utils file for common math functions
- Loading branch information
Showing
2 changed files
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,9 @@ | ||
"""Utilities module""" | ||
|
||
from . import testing | ||
from . import data_structures | ||
from . import distance_metrics | ||
from . import kernels | ||
from . import windows | ||
from . import graphs | ||
from . import misc |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
"""Miscellaneous utility functions""" | ||
import numpy as np | ||
|
||
|
||
def logsumexp(log_probs, axis=None): | ||
""" | ||
Redefine scipy.special.logsumexp | ||
see: http://bayesjumping.net/log-sum-exp-trick/ | ||
""" | ||
_max = np.max(log_probs) | ||
ds = log_probs - _max | ||
exp_sum = np.exp(ds).sum(axis=axis) | ||
return _max + np.log(exp_sum) | ||
|
||
|
||
def log_gaussian_pdf(x_i, mu, sigma): | ||
"""Compute log N(x_i | mu, sigma)""" | ||
n = len(mu) | ||
a = n * np.log(2 * np.pi) | ||
_, b = np.linalg.slogdet(sigma) | ||
|
||
y = np.linalg.solve(sigma, x_i - mu) | ||
c = np.dot(x_i - mu, y) | ||
return -0.5 * (a + b + c) |