Created
February 2, 2016 16:59
-
-
Save JesseLivezey/5d80ef651e75b21a7079 to your computer and use it in GitHub Desktop.
Masked array change for loglikelihood in pykalman/utils.py
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
def log_multivariate_normal_density(X, means, covars, min_covar=1.e-7): | |
"""Log probability for full covariance matrices. """ | |
if hasattr(linalg, 'solve_triangular'): | |
# only in scipy since 0.9 | |
solve_triangular = linalg.solve_triangular | |
else: | |
# slower, but works | |
solve_triangular = linalg.solve | |
n_samples, n_dim = X.shape | |
nmix = len(means) | |
log_prob = np.empty((n_samples, nmix)) | |
for c, (mu, cv) in enumerate(zip(means, covars)): | |
try: | |
cv_chol = linalg.cholesky(np.asarray(cv), lower=True) | |
except linalg.LinAlgError: | |
# The model is most probabily stuck in a component with too | |
# few observations, we need to reinitialize this components | |
cv_chol = linalg.cholesky(np.asarray(cv + min_covar * np.eye(n_dim)), | |
lower=True) | |
cv_log_det = 2 * np.sum(np.log(np.diagonal(cv_chol))) | |
cv_sol = solve_triangular(cv_chol, np.asarray((X - mu).T), lower=True).T | |
log_prob[:, c] = - .5 * (np.sum(cv_sol ** 2, axis=1) + \ | |
n_dim * np.log(2 * np.pi) + cv_log_det) | |
return log_prob |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment