Coverage for bmm_multitask_learning/coalescent/inverse_wishart.py: 0%
35 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-13 13:33 +0000
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-13 13:33 +0000
2import numpy as np
5class InverseWishart:
6 """
7 class to handle methods of InverseWishart distribution
8 """
9 def __init__(self, d, degrees_of_freedom, init_cov=None, corr_mat=False):
10 """
11 :param d: dimension of the covariance matrix
12 :param degrees_of_freedom: degrees of freedom of the
13 inverse Wishart distribution
14 :param init_cov: initial covariance matrix
15 :param corr_mat: if True, the covariance matrix is a correlation
16 matrix (i.e., it has ones on the diagonal)
17 """
18 self.d = d
19 if init_cov is None:
20 init_cov = np.eye(d)
21 else:
22 assert init_cov.shape == (d, d)
24 self.cov = init_cov
25 self.degrees_of_freedom = degrees_of_freedom
26 self.corr_mat = corr_mat
28 @staticmethod
29 def cov2corr(cov):
30 """
31 Conver covariance matrox to correlation matrix
32 """
33 if len(cov.shape) == 0:
34 cov = cov[None]
36 std_devs = 1/np.sqrt(np.diag(cov))
37 D = np.diag(std_devs)
39 d = len(cov.shape)
41 if d == 1:
42 D = D[None]
43 cov = cov[None]
44 R = D @ cov @ D
45 return R
47 def update_posterior(self, samples):
48 """
49 :param samples: shape=(n x d)
50 """
51 assert len(samples.shape) == 2 and samples.shape[1] == self.d
52 K = samples.shape[0]
53 self.degrees_of_freedom += K
55 S = samples.T @ samples # d x d
56 self.cov += S
57 return
59 def get_most_prob(self):
60 """
61 returns the mode of the inverse Wishart distribution
62 """
63 cov = self.cov
64 cov = cov/(self.degrees_of_freedom + self.d + 1)
66 if self.corr_mat:
67 cov = InverseWishart.cov2corr(cov)
68 return cov