Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correct small negative eigenvalues in covariance #152

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions src/qinfer/distributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,9 +393,16 @@ def particle_covariance_mtx(cls, weights, locations):
# positive-semidefinite covariance matrix. If a negative eigenvalue
# is produced, we should warn the caller of this.
assert np.all(np.isfinite(cov))
if not np.all(la.eig(cov)[0] >= 0):
warnings.warn('Numerical error in covariance estimation causing positive semidefinite violation.', ApproximationWarning)

vals, vecs = la.eig(cov)
small_vals = abs(vals) < 1e-12
mikedeltalima marked this conversation as resolved.
Show resolved Hide resolved
vals[small_vals] = 0
if not np.all(vals >= 0):
warnings.warn(
'Numerical error in covariance estimation causing positive semidefinite violation.',
ApproximationWarning
)
if np.any(small_vals):
return (vecs * vals) @ vecs.T.conj()
return cov

def est_mean(self):
Expand Down Expand Up @@ -1007,12 +1014,12 @@ def n_rvs(self):

def sample(self, n=1):
return self.dist.rvs(size=n)[:, np.newaxis]

class DirichletDistribution(Distribution):
r"""
The dirichlet distribution, whose pdf at :math:`x` is proportional to
:math:`\prod_i x_i^{\alpha_i-1}`.

:param alpha: The list of concentration parameters.
"""
def __init__(self, alpha):
Expand All @@ -1021,7 +1028,7 @@ def __init__(self, alpha):
raise ValueError('The input alpha must be a 1D list of concentration parameters.')

self._dist = st.dirichlet(alpha=self.alpha)

@property
def alpha(self):
return self._alpha
Expand Down