| 1 |
import functools |
| 2 |
import inspect |
| 3 |
import warnings |
| 4 |
|
| 5 |
import numpy as np |
| 6 |
from scipy import special |
| 7 |
from scipy.stats import multinomial, poisson |
| 8 |
from sklearn.utils import check_random_state |
| 9 |
|
| 10 |
from .base import BaseHMM, _AbstractHMM |
| 11 |
from .stats import log_multivariate_normal_density |
| 12 |
from .utils import fill_covars, log_normalize |
| 13 |
|
| 14 |
|
| 15 |
_CATEGORICALHMM_DOC_SUFFIX = """ |
| 16 |
|
| 17 |
Notes |
| 18 |
----- |
| 19 |
Unlike other HMM classes, `CategoricalHMM` ``X`` arrays have shape |
| 20 |
``(n_samples, 1)`` (instead of ``(n_samples, n_features)``). Consider using |
| 21 |
`sklearn.preprocessing.LabelEncoder` to transform your input to the right |
| 22 |
format. |
| 23 |
""" |
| 24 |
|
| 25 |
|
| 26 |
def _make_wrapper(func): |
| 27 |
return functools.wraps(func)(lambda *args, **kwargs: func(*args, **kwargs)) |
| 28 |
|
| 29 |
|
| 30 |
class BaseCategoricalHMM(_AbstractHMM): |
| 31 |
|
| 32 |
def __init_subclass__(cls): |
| 33 |
for name in [ |
| 34 |
"decode", |
| 35 |
"fit", |
| 36 |
"predict", |
| 37 |
"predict_proba", |
| 38 |
"sample", |
| 39 |
"score", |
| 40 |
"score_samples", |
| 41 |
]: |
| 42 |
meth = getattr(cls, name) |
| 43 |
doc = inspect.getdoc(meth) |
| 44 |
if doc is None or _CATEGORICALHMM_DOC_SUFFIX in doc: |
| 45 |
wrapper = meth |
| 46 |
else: |
| 47 |
wrapper = _make_wrapper(meth) |
| 48 |
wrapper.__doc__ = ( |
| 49 |
doc.replace("(n_samples, n_features)", "(n_samples, 1)") |
| 50 |
+ _CATEGORICALHMM_DOC_SUFFIX) |
| 51 |
setattr(cls, name, wrapper) |
| 52 |
|
| 53 |
def _check_and_set_n_features(self, X): |
| 54 |
""" |
| 55 |
Check if ``X`` is a sample from a categorical distribution, i.e. an |
| 56 |
array of non-negative integers. |
| 57 |
""" |
| 58 |
if not np.issubdtype(X.dtype, np.integer): |
| 59 |
raise ValueError("Symbols should be integers") |
| 60 |
if X.min() < 0: |
| 61 |
raise ValueError("Symbols should be nonnegative") |
| 62 |
if self.n_features is not None: |
| 63 |
if self.n_features - 1 < X.max(): |
| 64 |
raise ValueError( |
| 65 |
f"Largest symbol is {X.max()} but the model only emits " |
| 66 |
f"symbols up to {self.n_features - 1}") |
| 67 |
else: |
| 68 |
self.n_features = X.max() + 1 |
| 69 |
|
| 70 |
def _get_n_fit_scalars_per_param(self): |
| 71 |
nc = self.n_components |
| 72 |
nf = self.n_features |
| 73 |
return { |
| 74 |
"s": nc - 1, |
| 75 |
"t": nc * (nc - 1), |
| 76 |
"e": nc * (nf - 1), |
| 77 |
} |
| 78 |
|
| 79 |
def _compute_likelihood(self, X): |
| 80 |
if X.shape[1] != 1: |
| 81 |
warnings.warn("Inputs of shape other than (n_samples, 1) are " |
| 82 |
"deprecated.", DeprecationWarning) |
| 83 |
X = np.concatenate(X)[:, None] |
| 84 |
return self.emissionprob_[:, X.squeeze(1)].T |
| 85 |
|
| 86 |
def _initialize_sufficient_statistics(self): |
| 87 |
stats = super()._initialize_sufficient_statistics() |
| 88 |
stats['obs'] = np.zeros((self.n_components, self.n_features)) |
| 89 |
return stats |
| 90 |
|
| 91 |
def _accumulate_sufficient_statistics( |
| 92 |
self, stats, X, lattice, posteriors, fwdlattice, bwdlattice): |
| 93 |
super()._accumulate_sufficient_statistics(stats=stats, X=X, |
| 94 |
lattice=lattice, |
| 95 |
posteriors=posteriors, |
| 96 |
fwdlattice=fwdlattice, |
| 97 |
bwdlattice=bwdlattice) |
| 98 |
|
| 99 |
if 'e' in self.params: |
| 100 |
if X.shape[1] != 1: |
| 101 |
warnings.warn("Inputs of shape other than (n_samples, 1) are " |
| 102 |
"deprecated.", DeprecationWarning) |
| 103 |
X = np.concatenate(X)[:, None] |
| 104 |
np.add.at(stats['obs'].T, X.squeeze(1), posteriors) |
| 105 |
|
| 106 |
def _generate_sample_from_state(self, state, random_state=None): |
| 107 |
cdf = np.cumsum(self.emissionprob_[state, :]) |
| 108 |
random_state = check_random_state(random_state) |
| 109 |
return [(cdf > random_state.rand()).argmax()] |
| 110 |
|
| 111 |
|
| 112 |
class BaseGaussianHMM(_AbstractHMM): |
| 113 |
|
| 114 |
def _get_n_fit_scalars_per_param(self): |
| 115 |
nc = self.n_components |
| 116 |
nf = self.n_features |
| 117 |
return { |
| 118 |
"s": nc - 1, |
| 119 |
"t": nc * (nc - 1), |
| 120 |
"m": nc * nf, |
| 121 |
"c": { |
| 122 |
"spherical": nc, |
| 123 |
"diag": nc * nf, |
| 124 |
"full": nc * nf * (nf + 1) // 2, |
| 125 |
"tied": nf * (nf + 1) // 2, |
| 126 |
}[self.covariance_type], |
| 127 |
} |
| 128 |
|
| 129 |
def _compute_log_likelihood(self, X): |
| 130 |
return log_multivariate_normal_density( |
| 131 |
X, self.means_, self._covars_, self.covariance_type) |
| 132 |
|
| 133 |
def _initialize_sufficient_statistics(self): |
| 134 |
stats = super()._initialize_sufficient_statistics() |
| 135 |
stats['post'] = np.zeros(self.n_components) |
| 136 |
stats['obs'] = np.zeros((self.n_components, self.n_features)) |
| 137 |
stats['obs**2'] = np.zeros((self.n_components, self.n_features)) |
| 138 |
if self.covariance_type in ('tied', 'full'): |
| 139 |
stats['obs*obs.T'] = np.zeros((self.n_components, self.n_features, |
| 140 |
self.n_features)) |
| 141 |
return stats |
| 142 |
|
| 143 |
def _accumulate_sufficient_statistics( |
| 144 |
self, stats, X, lattice, posteriors, fwdlattice, bwdlattice): |
| 145 |
super()._accumulate_sufficient_statistics(stats=stats, X=X, |
| 146 |
lattice=lattice, |
| 147 |
posteriors=posteriors, |
| 148 |
fwdlattice=fwdlattice, |
| 149 |
bwdlattice=bwdlattice) |
| 150 |
|
| 151 |
if self._needs_sufficient_statistics_for_mean(): |
| 152 |
stats['post'] += posteriors.sum(axis=0) |
| 153 |
stats['obs'] += posteriors.T @ X |
| 154 |
|
| 155 |
if self._needs_sufficient_statistics_for_covars(): |
| 156 |
if self.covariance_type in ('spherical', 'diag'): |
| 157 |
stats['obs**2'] += posteriors.T @ X**2 |
| 158 |
elif self.covariance_type in ('tied', 'full'): |
| 159 |
|
| 160 |
|
| 161 |
stats['obs*obs.T'] += np.einsum( |
| 162 |
'ij,ik,il->jkl', posteriors, X, X) |
| 163 |
|
| 164 |
def _needs_sufficient_statistics_for_mean(self): |
| 165 |
""" |
| 166 |
Whether the sufficient statistics needed to update the means are |
| 167 |
updated during calls to `fit`. |
| 168 |
""" |
| 169 |
raise NotImplementedError("Must be overriden in subclass") |
| 170 |
|
| 171 |
def _needs_sufficient_statistics_for_covars(self): |
| 172 |
""" |
| 173 |
Whhether the sufficient statistics needed to update the covariances are |
| 174 |
updated during calls to `fit`. |
| 175 |
""" |
| 176 |
raise NotImplementedError("Must be overriden in subclass") |
| 177 |
|
| 178 |
def _generate_sample_from_state(self, state, random_state): |
| 179 |
return random_state.multivariate_normal( |
| 180 |
self.means_[state], self.covars_[state] |
| 181 |
) |
| 182 |
|
| 183 |
|
| 184 |
class BaseGMMHMM(BaseHMM): |
| 185 |
|
| 186 |
def _get_n_fit_scalars_per_param(self): |
| 187 |
nc = self.n_components |
| 188 |
nf = self.n_features |
| 189 |
nm = self.n_mix |
| 190 |
return { |
| 191 |
"s": nc - 1, |
| 192 |
"t": nc * (nc - 1), |
| 193 |
"m": nc * nm * nf, |
| 194 |
"c": { |
| 195 |
"spherical": nc * nm, |
| 196 |
"diag": nc * nm * nf, |
| 197 |
"full": nc * nm * nf * (nf + 1) // 2, |
| 198 |
"tied": nc * nf * (nf + 1) // 2, |
| 199 |
}[self.covariance_type], |
| 200 |
"w": nm - 1, |
| 201 |
} |
| 202 |
|
| 203 |
def _compute_log_weighted_gaussian_densities(self, X, i_comp): |
| 204 |
cur_means = self.means_[i_comp] |
| 205 |
cur_covs = self.covars_[i_comp] |
| 206 |
if self.covariance_type == 'spherical': |
| 207 |
cur_covs = cur_covs[:, None] |
| 208 |
log_cur_weights = np.log(self.weights_[i_comp]) |
| 209 |
|
| 210 |
return log_multivariate_normal_density( |
| 211 |
X, cur_means, cur_covs, self.covariance_type |
| 212 |
) + log_cur_weights |
| 213 |
|
| 214 |
def _compute_log_likelihood(self, X): |
| 215 |
logprobs = np.empty((len(X), self.n_components)) |
| 216 |
for i in range(self.n_components): |
| 217 |
log_denses = self._compute_log_weighted_gaussian_densities(X, i) |
| 218 |
with np.errstate(under="ignore"): |
| 219 |
logprobs[:, i] = special.logsumexp(log_denses, axis=1) |
| 220 |
return logprobs |
| 221 |
|
| 222 |
def _initialize_sufficient_statistics(self): |
| 223 |
stats = super()._initialize_sufficient_statistics() |
| 224 |
stats['post_mix_sum'] = np.zeros((self.n_components, self.n_mix)) |
| 225 |
stats['post_sum'] = np.zeros(self.n_components) |
| 226 |
|
| 227 |
if 'm' in self.params: |
| 228 |
lambdas, mus = self.means_weight, self.means_prior |
| 229 |
stats['m_n'] = lambdas[:, :, None] * mus |
| 230 |
if 'c' in self.params: |
| 231 |
stats['c_n'] = np.zeros_like(self.covars_) |
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
return stats |
| 241 |
|
| 242 |
def _accumulate_sufficient_statistics(self, stats, X, lattice, |
| 243 |
post_comp, fwdlattice, bwdlattice): |
| 244 |
super()._accumulate_sufficient_statistics( |
| 245 |
stats, X, lattice, post_comp, fwdlattice, bwdlattice |
| 246 |
) |
| 247 |
|
| 248 |
n_samples, _ = X.shape |
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
post_mix = np.zeros((n_samples, self.n_components, self.n_mix)) |
| 256 |
for p in range(self.n_components): |
| 257 |
log_denses = self._compute_log_weighted_gaussian_densities(X, p) |
| 258 |
log_normalize(log_denses, axis=-1) |
| 259 |
with np.errstate(under="ignore"): |
| 260 |
post_mix[:, p, :] = np.exp(log_denses) |
| 261 |
|
| 262 |
with np.errstate(under="ignore"): |
| 263 |
post_comp_mix = post_comp[:, :, None] * post_mix |
| 264 |
|
| 265 |
stats['post_mix_sum'] += post_comp_mix.sum(axis=0) |
| 266 |
stats['post_sum'] += post_comp.sum(axis=0) |
| 267 |
|
| 268 |
if 'm' in self.params: |
| 269 |
stats['m_n'] += np.einsum('ijk,il->jkl', post_comp_mix, X) |
| 270 |
|
| 271 |
if 'c' in self.params: |
| 272 |
centered = X[:, None, None, :] - self.means_ |
| 273 |
|
| 274 |
def outer_f(x): |
| 275 |
return x[..., :, None] * x[..., None, :] |
| 276 |
|
| 277 |
if self.covariance_type == 'full': |
| 278 |
centered_dots = outer_f(centered) |
| 279 |
c_n = np.einsum('ijk,ijklm->jklm', post_comp_mix, |
| 280 |
centered_dots) |
| 281 |
elif self.covariance_type == 'diag': |
| 282 |
centered2 = np.square(centered, out=centered) |
| 283 |
c_n = np.einsum('ijk,ijkl->jkl', post_comp_mix, centered2) |
| 284 |
elif self.covariance_type == 'spherical': |
| 285 |
|
| 286 |
centered_norm2 = np.einsum('...i,...i', centered, centered) |
| 287 |
c_n = np.einsum('ijk,ijk->jk', post_comp_mix, centered_norm2) |
| 288 |
elif self.covariance_type == 'tied': |
| 289 |
centered_dots = outer_f(centered) |
| 290 |
c_n = np.einsum('ijk,ijklm->jlm', post_comp_mix, centered_dots) |
| 291 |
|
| 292 |
stats['c_n'] += c_n |
| 293 |
|
| 294 |
def _generate_sample_from_state(self, state, random_state): |
| 295 |
cur_weights = self.weights_[state] |
| 296 |
i_gauss = random_state.choice(self.n_mix, p=cur_weights) |
| 297 |
if self.covariance_type == 'tied': |
| 298 |
|
| 299 |
|
| 300 |
covs = self.covars_ |
| 301 |
else: |
| 302 |
covs = self.covars_[:, i_gauss] |
| 303 |
covs = fill_covars(covs, self.covariance_type, |
| 304 |
self.n_components, self.n_features) |
| 305 |
return random_state.multivariate_normal( |
| 306 |
self.means_[state, i_gauss], covs[state] |
| 307 |
) |
| 308 |
|
| 309 |
|
| 310 |
class BaseMultinomialHMM(BaseHMM): |
| 311 |
|
| 312 |
def _check_and_set_n_features(self, X): |
| 313 |
""" |
| 314 |
Check if ``X`` is a sample from a multinomial distribution, i.e. an |
| 315 |
array of non-negative integers, summing up to n_trials. |
| 316 |
""" |
| 317 |
super()._check_and_set_n_features(X) |
| 318 |
if not np.issubdtype(X.dtype, np.integer) or X.min() < 0: |
| 319 |
raise ValueError("Symbol counts should be nonnegative integers") |
| 320 |
if self.n_trials is None: |
| 321 |
self.n_trials = X.sum(axis=1) |
| 322 |
elif not (X.sum(axis=1) == self.n_trials).all(): |
| 323 |
raise ValueError("Total count for each sample should add up to " |
| 324 |
"the number of trials") |
| 325 |
|
| 326 |
def _get_n_fit_scalars_per_param(self): |
| 327 |
nc = self.n_components |
| 328 |
nf = self.n_features |
| 329 |
return { |
| 330 |
"s": nc - 1, |
| 331 |
"t": nc * (nc - 1), |
| 332 |
"e": nc * (nf - 1), |
| 333 |
} |
| 334 |
|
| 335 |
def _compute_likelihood(self, X): |
| 336 |
probs = np.empty((len(X), self.n_components)) |
| 337 |
n_trials = X.sum(axis=1) |
| 338 |
for c in range(self.n_components): |
| 339 |
probs[:, c] = multinomial.pmf( |
| 340 |
X, n=n_trials, p=self.emissionprob_[c, :]) |
| 341 |
return probs |
| 342 |
|
| 343 |
def _compute_log_likelihood(self, X): |
| 344 |
logprobs = np.empty((len(X), self.n_components)) |
| 345 |
n_trials = X.sum(axis=1) |
| 346 |
for c in range(self.n_components): |
| 347 |
logprobs[:, c] = multinomial.logpmf( |
| 348 |
X, n=n_trials, p=self.emissionprob_[c, :]) |
| 349 |
return logprobs |
| 350 |
|
| 351 |
def _initialize_sufficient_statistics(self): |
| 352 |
stats = super()._initialize_sufficient_statistics() |
| 353 |
stats['obs'] = np.zeros((self.n_components, self.n_features)) |
| 354 |
return stats |
| 355 |
|
| 356 |
def _accumulate_sufficient_statistics(self, stats, X, framelogprob, |
| 357 |
posteriors, fwdlattice, bwdlattice): |
| 358 |
super()._accumulate_sufficient_statistics( |
| 359 |
stats, X, framelogprob, posteriors, fwdlattice, bwdlattice) |
| 360 |
if 'e' in self.params: |
| 361 |
stats['obs'] += posteriors.T @ X |
| 362 |
|
| 363 |
def _generate_sample_from_state(self, state, random_state): |
| 364 |
try: |
| 365 |
n_trials, = np.unique(self.n_trials) |
| 366 |
except ValueError: |
| 367 |
raise ValueError("For sampling, a single n_trials must be given") |
| 368 |
return multinomial.rvs(n=n_trials, p=self.emissionprob_[state, :], |
| 369 |
random_state=random_state) |
| 370 |
|
| 371 |
|
| 372 |
class BasePoissonHMM(BaseHMM): |
| 373 |
|
| 374 |
def _get_n_fit_scalars_per_param(self): |
| 375 |
nc = self.n_components |
| 376 |
nf = self.n_features |
| 377 |
return { |
| 378 |
"s": nc - 1, |
| 379 |
"t": nc * (nc - 1), |
| 380 |
"l": nc * nf, |
| 381 |
} |
| 382 |
|
| 383 |
def _compute_likelihood(self, X): |
| 384 |
probs = np.empty((len(X), self.n_components)) |
| 385 |
for c in range(self.n_components): |
| 386 |
probs[:, c] = poisson.pmf(X, self.lambdas_[c]).prod(axis=1) |
| 387 |
return probs |
| 388 |
|
| 389 |
def _compute_log_likelihood(self, X): |
| 390 |
logprobs = np.empty((len(X), self.n_components)) |
| 391 |
for c in range(self.n_components): |
| 392 |
logprobs[:, c] = poisson.logpmf(X, self.lambdas_[c]).sum(axis=1) |
| 393 |
return logprobs |
| 394 |
|
| 395 |
def _initialize_sufficient_statistics(self): |
| 396 |
stats = super()._initialize_sufficient_statistics() |
| 397 |
stats['post'] = np.zeros(self.n_components) |
| 398 |
stats['obs'] = np.zeros((self.n_components, self.n_features)) |
| 399 |
return stats |
| 400 |
|
| 401 |
def _accumulate_sufficient_statistics(self, stats, obs, lattice, |
| 402 |
posteriors, fwdlattice, bwdlattice): |
| 403 |
super()._accumulate_sufficient_statistics( |
| 404 |
stats, obs, lattice, posteriors, fwdlattice, bwdlattice) |
| 405 |
if 'l' in self.params: |
| 406 |
stats['post'] += posteriors.sum(axis=0) |
| 407 |
stats['obs'] += posteriors.T @ obs |
| 408 |
|
| 409 |
def _generate_sample_from_state(self, state, random_state): |
| 410 |
return random_state.poisson(self.lambdas_[state]) |