Debian Codegraph @

src/hmmlearn/_utils.py

raw symbols SCIP
1 """Private utilities."""
2
3 import warnings
4
5 import numpy as np
6
7
8 def logdet(a):
9 sign, logdet = np.linalg.slogdet(a)
10 if (sign < 0).any():
11 warnings.warn("invalid value encountered in log", RuntimeWarning)
12 return np.where(sign < 0, np.nan, logdet)
13 else:
14 return logdet
15
16
17 def split_X_lengths(X, lengths):
18 if lengths is None:
19 return [X]
20 else:
21 cs = np.cumsum(lengths)
22 n_samples = len(X)
23 if cs[-1] != n_samples:
24 raise ValueError(
25 f"lengths array {lengths} doesn't sum to {n_samples} samples")
26 return np.split(X, cs)[:-1]
27
28
29 # Copied from scikit-learn 0.19.
30 def _validate_covars(covars, covariance_type, n_components):
31 """Do basic checks on matrix covariance sizes and values."""
32 from scipy import linalg
33 if covariance_type == 'spherical':
34 if len(covars) != n_components:
35 raise ValueError("'spherical' covars have length n_components")
36 elif np.any(covars <= 0):
37 raise ValueError("'spherical' covars must be positive")
38 elif covariance_type == 'tied':
39 if covars.shape[0] != covars.shape[1]:
40 raise ValueError("'tied' covars must have shape (n_dim, n_dim)")
41 elif (not np.allclose(covars, covars.T)
42 or np.any(linalg.eigvalsh(covars) <= 0)):
43 raise ValueError("'tied' covars must be symmetric, "
44 "positive-definite")
45 elif covariance_type == 'diag':
46 if len(covars.shape) != 2:
47 raise ValueError("'diag' covars must have shape "
48 "(n_components, n_dim)")
49 elif np.any(covars <= 0):
50 raise ValueError("'diag' covars must be positive")
51 elif covariance_type == 'full':
52 if len(covars.shape) != 3:
53 raise ValueError("'full' covars must have shape "
54 "(n_components, n_dim, n_dim)")
55 elif covars.shape[1] != covars.shape[2]:
56 raise ValueError("'full' covars must have shape "
57 "(n_components, n_dim, n_dim)")
58 for n, cv in enumerate(covars):
59 if (not np.allclose(cv, cv.T)
60 or np.any(linalg.eigvalsh(cv) <= 0)):
61 raise ValueError("component %d of 'full' covars must be "
62 "symmetric, positive-definite" % n)
63 else:
64 raise ValueError("covariance_type must be one of " +
65 "'spherical', 'tied', 'diag', 'full'")
66
67
68 # Copied from scikit-learn 0.19.
69 def distribute_covar_matrix_to_match_covariance_type(
70 tied_cv, covariance_type, n_components):
71 """Create all the covariance matrices from a given template."""
72 if covariance_type == 'spherical':
73 cv = np.tile(tied_cv.mean() * np.ones(tied_cv.shape[1]),
74 (n_components, 1))
75 elif covariance_type == 'tied':
76 cv = tied_cv
77 elif covariance_type == 'diag':
78 cv = np.tile(np.diag(tied_cv), (n_components, 1))
79 elif covariance_type == 'full':
80 cv = np.tile(tied_cv, (n_components, 1, 1))
81 else:
82 raise ValueError("covariance_type must be one of " +
83 "'spherical', 'tied', 'diag', 'full'")
84 return cv