-
Notifications
You must be signed in to change notification settings - Fork 1
/
marginalizable_mixture_model.py
2103 lines (1887 loc) · 68.4 KB
/
marginalizable_mixture_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Implements a mixture of linear gaussian state space models that can be trained
with EM and can handle missing data and trajectories of differing lengths
"""
from __future__ import annotations
import datetime
import glob
import gzip
import hashlib
import os
import pickle
import string
import matplotlib as mpl
import matplotlib.pyplot as plt
import numba
import numpy as np
import scipy.stats as sp_stats
import sklearn.cluster as skl_cluster
import sklearn.linear_model as skl_lm
import statsmodels.api as sm
from framework import marginalizable_state_space_model as statespace
from util import util_state_space as util
plt.rcParams["figure.autolayout"] = True
plt.rcParams["legend.loc"] = "upper right"
plt.rcParams["font.family"] = "serif"
np_eps = np.finfo(float).eps
home_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class MMLinGaussSS_marginalizable:
"""
Provides a probabilistic mixture of linear gaussian state space models;
Implements expectation maximisation for this mixture on provided data
"""
def __init__(
self,
n_clusters: int,
states: np.array,
observations: np.array,
random_seed: int = 42,
init: str = "random",
alpha: float = 0.0,
):
"""Creates a model instance
Parameters
----------
n_clusters: int
number of clusters in the mixture
states: np.array
n_timesteps × n_data × d_states array of latent states
observations: np.array
n_timesteps × n_data × d_observations array of measurements
random_seed: int
for random number generation
init: str
cluster initialisation method;
either "random"
or ("kmeans","k-means") for k-means on first avail. hidden states
or ("kmeans-all","k-means-all") for k-means on all hidden states
alpha: float
regularisation parameter for linear models
"""
states, observations = map(np.atleast_3d, (states, observations))
self.n_clusters = int(n_clusters)
self.states = np.array(states)
self.observations = np.array(observations)
self.n_timesteps, self.n_data, self.d_states = self.states.shape
self.d_observations = self.observations.shape[-1]
self.cluster_propensities = (
np.ones(shape=[self.n_clusters]) / self.n_clusters
)
self.init_state_means = [
np.random.normal(size=[self.d_states])
for _ in range(self.n_clusters)
]
self.init_state_covs = [
np.random.normal(size=[self.d_states, self.d_states])
for _ in range(self.n_clusters)
]
self.init_state_covs = [
x @ x.T + np.eye(self.d_states) for x in self.init_state_covs
]
self.transition_matrices = [
np.random.normal(size=[self.d_states, self.d_states])
for _ in range(self.n_clusters)
]
self.transition_covs = [
np.random.normal(size=[self.d_states, self.d_states])
for _ in range(self.n_clusters)
]
self.transition_covs = [
x @ x.T + np.eye(self.d_states) for x in self.transition_covs
]
self.measurement_matrices = [
np.random.normal(size=[self.d_states, self.d_observations])
for _ in range(self.n_clusters)
]
self.measurement_covs = [
np.random.normal(size=[self.d_observations, self.d_observations])
for _ in range(self.n_clusters)
]
self.measurement_covs = [
x @ x.T + np.eye(self.d_observations)
for x in self.measurement_covs
]
self.random_seed = random_seed
self.rng = np.random.default_rng(seed=self.random_seed)
self.init = init
self.alpha = alpha if alpha > 2 * np_eps else 0
match self.init:
case "k-means" | "kmeans":
idx_first_non_null = np.argmax(
np.isfinite(self.states).all(axis=2), axis=0
).ravel()
first_non_null_state = np.vstack(
[
self.states[idx_first_non_null[i], i, :]
for i in range(self.n_data)
]
)
first_non_null_state = np.where(
np.isfinite(first_non_null_state),
first_non_null_state,
np.nanmean(first_non_null_state, axis=0, keepdims=True),
)
self.cluster_assignment = skl_cluster.KMeans(
n_clusters=self.n_clusters,
init="k-means++",
random_state=self.random_seed,
).fit_predict(first_non_null_state)
case "kmeans-all" | "k-means-all":
self.cluster_assignment = skl_cluster.KMeans(
n_clusters=self.n_clusters,
init="k-means++",
random_state=self.random_seed,
).fit_predict(
np.row_stack(
[
self.states[:, i, :].flatten()
for i in range(self.n_data)
]
)
)
case _:
self.cluster_assignment = self.rng.integers(
low=0, high=self.n_clusters, size=self.n_data
)
self._correspondence = dict(
zip(range(self.n_clusters), string.ascii_uppercase)
)
self.inverse_correspondence = {
v: k for k, v in self._correspondence.items()
}
self.hex_hash = hashlib.md5(
self.states.tobytes()
+ self.observations.tobytes()
+ str(self.n_clusters).encode("utf-8")
+ (
np.format_float_positional(self.alpha, unique=True).encode(
"utf-8"
)
if self.alpha > 2 * np_eps
else b""
)
).hexdigest()
self.time_stamp = (
datetime.datetime.now(datetime.timezone.utc)
.replace(microsecond=0)
.astimezone()
.isoformat()
)
self.last_trained = None
@property
def n_free_params(self) -> int:
return sum(
[
x.size
for x in [self.cluster_propensities]
+ self.init_state_means
+ self.transition_matrices
+ self.measurement_matrices
]
) + sum(
map(
lambda x: len(np.triu_indices_from(np.atleast_2d(x))[0]),
self.init_state_covs
+ self.transition_covs
+ self.measurement_covs,
)
)
@property
def correspondence(self) -> dict[int, str]:
return self._correspondence
@correspondence.setter
def correspondence(self, corr: dict[int, str]) -> None:
self._correspondence = corr
self.inverse_correspondence = {
v: k for k, v in self._correspondence.items()
}
def to_pickle(
self,
save_location: str | os.PathLike = os.path.join(home_dir, "tmp"),
there_can_only_be_one: bool = True,
include_training_data: bool = False,
):
os.makedirs(save_location, exist_ok=True)
ts = datetime.datetime.now(datetime.timezone.utc).strftime(
"%Y%m%dT%H%MZ"
)
if there_can_only_be_one:
list(
map(
os.remove,
glob.glob(
os.path.join(save_location, f"mmm-{self.hex_hash}*")
),
)
)
with gzip.open(
os.path.join(
save_location,
f"mmm-{self.hex_hash}-{ts}.p.gz",
),
"wb",
) as f:
pickle.dump(
{
"n_clusters": self.n_clusters,
"cluster_propensities": self.cluster_propensities,
"init_state_means": self.init_state_means,
"init_state_covs": self.init_state_covs,
"transition_matrices": self.transition_matrices,
"transition_covs": self.transition_covs,
"measurement_matrices": self.measurement_matrices,
"measurement_covs": self.measurement_covs,
"random_seed": self.random_seed,
"rng": self.rng,
"init": self.init,
"alpha": self.alpha,
"cluster_assignment": self.cluster_assignment,
"correspondence": self.correspondence,
"inverse_correspondence": self.inverse_correspondence,
"hex_hash": self.hex_hash,
"time_stamp": self.time_stamp,
"last_trained": self.last_trained,
}
| (
{"states": self.states, "observations": self.observations}
if include_training_data
else {}
),
f,
)
@staticmethod
def from_pickle(file: str | os.PathLike, training_data: dict = None):
with gzip.open(file, "rb") if os.path.splitext(file)[
-1
] == ".gz" else open(file, "rb") as f:
mdl_dict = pickle.load(f)
if training_data is not None:
mdl = MMLinGaussSS_marginalizable(
n_clusters=mdl_dict["n_clusters"],
states=training_data["states"],
observations=training_data["observations"],
random_seed=mdl_dict["random_seed"],
init=mdl_dict["init"],
alpha=mdl_dict["alpha"] if "alpha" in mdl_dict else 0,
)
else:
mdl = MMLinGaussSS_marginalizable(
n_clusters=mdl_dict["n_clusters"],
states=mdl_dict["states"],
observations=mdl_dict["observations"],
random_seed=mdl_dict["random_seed"],
init=mdl_dict["init"],
alpha=mdl_dict["alpha"] if "alpha" in mdl_dict else 0,
)
mdl.cluster_propensities = mdl_dict["cluster_propensities"]
mdl.init_state_means = mdl_dict["init_state_means"]
mdl.init_state_covs = mdl_dict["init_state_covs"]
mdl.transition_matrices = mdl_dict["transition_matrices"]
mdl.transition_covs = mdl_dict["transition_covs"]
mdl.measurement_matrices = mdl_dict["measurement_matrices"]
mdl.measurement_covs = mdl_dict["measurement_covs"]
mdl.rng = mdl_dict["rng"]
mdl.cluster_assignment = mdl_dict["cluster_assignment"]
mdl.correspondence = mdl_dict["correspondence"]
mdl.inverse_correspondence = mdl_dict["inverse_correspondence"]
mdl.time_stamp = mdl_dict["time_stamp"]
mdl.last_trained = mdl_dict["last_trained"]
return mdl
def print_model(
self,
*,
verbose: bool = False,
line_len: int = 79,
) -> None:
"""Print model parameters.
Parameters
----------
verbose: bool
additionally prints out covariance parameters
line_len: int
how wide should the print out be?
"""
print(
"MixtureModelLinearGaussianStateSpace |".ljust(line_len, "=")
+ "\n"
)
for s in string.ascii_uppercase[: self.n_clusters]:
c = self.inverse_correspondence[s]
print(f"Cluster {s} |".ljust(line_len, "-"))
print(f"Cluster propensity:\n {self.cluster_propensities[c]:.3f}")
print(
f"Initial state mean:\n "
f"{np.round(self.init_state_means[c], 3)}"
)
if verbose:
print(
f"Initial state cov:\n "
f"{np.round(self.init_state_covs[c], 3)}"
)
print(
f"State transition coeffs:\n "
f"{np.round(self.transition_matrices[c], 3)}"
)
if verbose:
print(
f"Transition cov:\n {np.round(self.transition_covs[c], 3)}"
)
print(
f"Measurement coeffs:\n "
f"{np.round(self.measurement_matrices[c], 3)}"
)
if verbose:
print(
f"Measurement cov:\n "
f"{np.round(self.measurement_covs[c], 3)}"
)
print(f"{self.last_trained=}")
print(f"{self.hex_hash=}")
print("=" * line_len)
def print_tests(
self,
*,
test_1: bool = False,
test_01: bool = False,
test_obs: bool = False,
) -> None:
"""Print tests for model parameters
Parameters
----------
test_1: bool
Should we test learned state evolution coefficients against 1?
test_01: bool
Should we test x0=0 & x1=1?
test_obs: bool
Should we test the observation / measurement models?
"""
for s in string.ascii_uppercase[: self.n_clusters]:
c = self.inverse_correspondence[s]
Zcprev = np.row_stack(
[*self.states[:-1, self.cluster_assignment == c, :]]
)
Zcnext = np.row_stack(
[*self.states[1:, self.cluster_assignment == c, :]]
)
trans_idx = np.isfinite(np.column_stack([Zcprev, Zcnext])).all(
axis=1
)
Zcprev = Zcprev[trans_idx, :]
Zcnext = Zcnext[trans_idx, :]
for i in range(self.d_states):
print(f" Cluster {s} -- State {i} ".center(78, "-"))
res = sm.OLS(endog=Zcnext[:, i], exog=Zcprev).fit()
print(res.summary())
if test_1:
t_res = res.t_test(f"x{i+1}=1", use_t=True)
print(f"testing x{i+1}=1")
print(t_res)
print(f"dof={t_res.df_denom}")
if test_01:
t_res = res.t_test(
f"x{1 if i+1 == 2 else 2}=0, x{i+1}=1", use_t=True
)
print(f"testing x{1 if i+1 == 2 else 2}=0, x{i+1}=1")
print(t_res)
print(f"dof={t_res.df_denom}")
if test_obs:
Xcs = np.row_stack(
[*self.observations[:, self.cluster_assignment == c, :]]
)
Zcs = np.row_stack(
[*self.states[:, self.cluster_assignment == c, :]]
)
meas_idx = np.isfinite(np.column_stack([Xcs, Zcs])).all(axis=1)
Xcs = Xcs[meas_idx, :]
Zcs = Zcs[meas_idx, :]
for j in range(self.d_observations):
print(f" Cluster {s} -- Observation {j} ")
print(sm.OLS(endog=Xcs[:, j], exog=Zcs).fit().summary())
def conditional_log_likelihoods_first_T0_steps(
self,
c: int,
T0: int,
*,
states: np.array = None,
observations: np.array = None,
) -> np.array:
"""Computes class-conditional log likelihoods for each data instance
restricted to steps 1<=t<=T0
Parameters
----------
c: int
cluster index between 0 and n_clusters-1
T0: int
time cutoff 1 <= T0 <= self.n_timesteps
states
(optionally) override the default of self.states
observations
(optionally) override the default of self.observations
Returns
-------
n_data length array of log likelihoods
for c-th mixture restricted to time steps 1<=t<=T0
"""
assert 1 <= T0 <= self.n_timesteps
if states is None:
states = self.states
observations = self.observations
_T0 = min(T0, states.shape[0])
full_mean_T0 = statespace.mm(
_T0,
self.init_state_means[c],
self.transition_matrices[c],
self.measurement_matrices[c],
)
full_cov_T0 = statespace.CC(
_T0,
self.init_state_covs[c],
self.transition_matrices[c],
self.transition_covs[c],
self.measurement_matrices[c],
self.measurement_covs[c],
)
return statespace.multivariate_normal_log_likelihood(
np.hstack((*states[:_T0], *observations[:_T0])),
full_mean_T0,
full_cov_T0,
np.zeros(states.shape[1]),
)
def conditional_log_likelihoods(
self,
c: int,
*,
states: np.array = None,
observations: np.array = None,
) -> np.array:
"""Computes class-conditional log likelihoods for each data instance
Parameters
----------
c: int
cluster index between 0 and n_clusters-1
states
(optionally) override the default of self.states
observations
(optionally) override the default of self.observations
Returns
-------
n_data length array of log likelihoods for c-th mixture
See Also
--------
conditional_log_likelihoods_first_T0_steps
to restrict the time horizon
"""
if states is None:
states = self.states
observations = self.observations
return self.conditional_log_likelihoods_first_T0_steps(
c, self.n_timesteps, states=states, observations=observations
)
def cluster_propensities_over_time(
self, *, states: np.array = None, observations: np.array = None
) -> np.array:
"""Computes probabilities of cluster membership for each training
datapoint given only first t timesteps, for 1 <= t <= T
Parameters
----------
states
(optionally) override the default of self.states
observations
(optionally) override the default of self.observations
Returns
-------
pc_t
an n_timesteps × n_data × n_clusters array where pc_t[t,i,:] is a
probability vector predicting cluster membership for the ith data
instance using only the first t+1 timesteps
"""
pc_t = np.stack(
[
np.column_stack(
[
self.cluster_propensities[c]
* np.exp(
self.conditional_log_likelihoods_first_T0_steps(
c,
t + 1,
states=states,
observations=observations,
)
)
for c in range(self.n_clusters)
]
)
for t in range(min(self.n_timesteps, states.shape[0]))
],
axis=0,
)
pc_t /= np.sum(pc_t, axis=-1, keepdims=True)
assert np.all(pc_t >= 0.0) and np.allclose(np.sum(pc_t, axis=-1), 1.0)
return pc_t
def e_complete_data_log_lik(
self,
*,
states: np.array = None,
observations: np.array = None,
) -> float:
"""Computes expected complete data log likelihood
Note: EM should increase this value after every iteration
Parameters
----------
states
(optionally) override the default of self.states
observations
(optionally) override the default of self.observations
Returns
-------
expected complete data log likelihood (Q)
"""
if states is None:
states = self.states
observations = self.observations
cluster_assignment = self.mle_cluster_assignment(
states=states, observations=observations
)
conditional_log_likelihoods = np.column_stack(
[
self.conditional_log_likelihoods(
c, states=states, observations=observations
)
for c in range(self.n_clusters)
]
)
return np.sum(
np.log(self.cluster_propensities[cluster_assignment])
) + np.sum(
[
conditional_log_likelihoods[i, cluster_assignment[i]]
for i in range(cluster_assignment.size)
]
)
def model_log_likelihood(
self,
*,
states: np.array = None,
observations: np.array = None,
) -> np.array:
"""Computes log likelihood over i.i.d. samples
Parameters
----------
states
(optionally) override the default of self.states
observations
(optionally) override the default of self.observations
Returns
-------
log likelihood
"""
if states is None:
states = self.states
observations = self.observations
Zcs = np.column_stack(
[
self.cluster_propensities[c]
* np.exp(
self.conditional_log_likelihoods(
c,
states=states,
observations=observations,
)
)
for c in range(self.n_clusters)
]
)
assert Zcs.shape == (states.shape[1], self.n_clusters)
lZ = np.log(np.sum(Zcs, axis=1))
assert lZ.shape[0] == states.shape[1]
return np.sum(lZ)
def aic(
self, states: np.array = None, observations: np.array = None
) -> float:
"""computes the AIC for the model on a given dataset (defaults to the
training dataset)
Parameters
----------
states
(optionally) override the default of self.states
observations
(optionally) override the default of self.observations
Returns
-------
AIC
for the model on the dataset
"""
return (
-2
* self.model_log_likelihood(
states=states, observations=observations
)
+ 2 * self.n_free_params
)
def bic(
self, states: np.array = None, observations: np.array = None
) -> float:
"""computes the BIC for the model on a given dataset (defaults to the
training dataset)
Parameters
----------
states
(optionally) override the default of self.states
observations
(optionally) override the default of self.observations
Returns
-------
BIC
for the model on the dataset
"""
return (
-2
* self.model_log_likelihood(
states=states, observations=observations
)
+ np.log(self.n_data if states is None else states.shape[1])
* self.n_free_params
)
def mle_cluster_assignment(
self,
*,
return_probs: bool = False,
return_prenormalized_log_probs: bool = False,
states: np.array = None,
observations: np.array = None,
) -> (
tuple[np.array, np.array, np.array]
| tuple[np.array, np.array]
| np.array
):
"""Hard assignment of each data instance to a cluster according to
maximum likelihood
Parameters
----------
return_probs: bool
should we also return probs?
return_prenormalized_log_probs: bool
should we return prenormalized log-probs?
states
(optionally) override the default of self.states
observations
(optionally) override the default of self.observations
Returns
-------
n_data length array of cluster indices in {0,...,n_clusters-1}
or a tuple, with a probability vector for cluster assignment
"""
if states is None:
states = self.states
observations = self.observations
cluster_likelihoods = np.stack(
[
self.cluster_propensities[c]
* np.exp(
self.conditional_log_likelihoods(
c, states=states, observations=observations
)
)
for c in range(self.n_clusters)
]
)
assignments = np.argmax(cluster_likelihoods, axis=0)
if not (return_probs or return_prenormalized_log_probs):
return assignments
else:
probs = np.divide(
cluster_likelihoods,
np.sum(cluster_likelihoods, axis=0, keepdims=True),
)
if not return_prenormalized_log_probs:
return assignments, probs
else:
prenorm = np.stack(
[
np.log(self.cluster_propensities[c])
+ self.conditional_log_likelihoods(
c, states=states, observations=observations
)
for c in range(self.n_clusters)
]
)
return assignments, probs, prenorm
def cluster_assignment_index(
self,
*,
cluster: str = "A",
states: np.array = None,
observations: np.array = None,
) -> np.array:
"""Return pre-normalized log-odds of assignment to cluster `cluster`"""
return self.mle_cluster_assignment(
states=states,
observations=observations,
return_probs=True,
return_prenormalized_log_probs=True,
)[-1][self.inverse_correspondence[cluster]]
def one_step_ahead_predictions(
self, *, states, observations
) -> tuple[np.array, np.array]:
"""given trajectories of states & observations in the usual form,
predicts cluster membership propensities and then forms the average
one-step-ahead prediction for each provided data instance
Parameters
----------
states: np.array
n_timesteps × n_data × d_states array of latent states
observations: np.array
n_timesteps × n_data × d_observations array of measurements
Returns
-------
predicted_states: np.array
1 × n_data × d_states array of predicted latent states
predicted_observations: np.array
1 × n_data × d_observations array of predicted measurements
"""
assignment_probs = self.mle_cluster_assignment(
states=states, observations=observations, return_probs=True
)[1]
next_states = np.zeros(shape=(1, *states.shape[1:]))
next_observations = np.zeros(shape=(1, *observations.shape[1:]))
these_states = states[-1]
assert assignment_probs.shape == (
self.n_clusters,
these_states.shape[0],
)
for i in range(self.n_clusters):
next_states_c = these_states @ self.transition_matrices[i]
next_observations_c = next_states_c @ self.measurement_matrices[i]
next_states += np.multiply(
np.expand_dims(assignment_probs[i], axis=-1), next_states_c
)
next_observations += np.multiply(
np.expand_dims(assignment_probs[i], axis=-1),
next_observations_c,
)
return next_states, next_observations
def one_step_ahead_predictions_no_history(
self, *, states, observations
) -> tuple[np.array, np.array]:
"""given trajectories of states & observations in the usual form,
predicts cluster membership propensities using only the most recent
pair of states and measurements, and then forms the average
one-step-ahead prediction for each provided data instance
Parameters
----------
states: np.array
n_timesteps × n_data × d_states array of latent states
observations: np.array
n_timesteps × n_data × d_observations array of measurements
Returns
-------
predicted_states: np.array
1 × n_data × d_states array of predicted latent states
predicted_observations: np.array
1 × n_data × d_observations array of predicted measurements
See Also
--------
one_step_ahead_predictions
a version of this function that uses history for cluster assignment
"""
states_no_history = np.nan * np.ones_like(states)
states_no_history[-1] = states[-1]
observations_no_history = np.nan * np.ones_like(observations)
observations_no_history[-1] = observations[-1]
assignment_probs = self.mle_cluster_assignment(
states=states_no_history,
observations=observations_no_history,
return_probs=True,
)[1]
next_states = np.zeros(shape=(1, *states.shape[1:]))
next_observations = np.zeros(shape=(1, *observations.shape[1:]))
these_states = states[-1]
assert assignment_probs.shape == (
self.n_clusters,
these_states.shape[0],
)
for i in range(self.n_clusters):
next_states_c = these_states @ self.transition_matrices[i]
next_observations_c = next_states_c @ self.measurement_matrices[i]
next_states += np.multiply(
np.expand_dims(assignment_probs[i], axis=-1), next_states_c
)
next_observations += np.multiply(
np.expand_dims(assignment_probs[i], axis=-1),
next_observations_c,
)
return next_states, next_observations
def initial_full_data_cluster_assignment(
self, *, states: np.array = None, observations: np.array = None
) -> np.array:
"""Hard assignment of each data instance to a cluster according to
only data available initially (both hidden and observed)
Parameters
----------
states
(optionally) override the default of self.states
observations
(optionally) override the default of self.observations
Returns
-------
n_data length array of cluster indices in {0,...,n_clusters-1}
or a tuple, with a probability vector for initial cluster assignment
with both hidden and observed data
"""
init_cluster_likelihoods = np.stack(
[
self.cluster_propensities[c]
* np.exp(
self.conditional_log_likelihoods_first_T0_steps(
c, 1, states=states, observations=observations
)
)
for c in range(self.n_clusters)
]
)
assignments = np.argmax(init_cluster_likelihoods, axis=0)
return assignments
def predictions_from_initial_data(
self, *, states: np.array = None, observations: np.array = None
) -> tuple[np.array, np.array]:
"""Predicted states and observations given only initial data, based
on cluster assignment from inital data
Parameters
----------
states
(optionally) override the default of self.states
observations
(optionally) override the default of self.observations
Returns
-------
tuple of predicted states and observations for each data instance using
only information available at initial time point
"""
assignments = self.initial_full_data_cluster_assignment(
states=states, observations=observations
)
predicted_states = np.zeros_like(
self.states if states is None else states
)
predicted_observations = np.zeros_like(
self.observations if observations is None else observations
)
for i in range(self.n_data):
predicted_states[:, i, :] = statespace.mmZ(
predicted_states.shape[0],
self.states[0, i, :],
self.transition_matrices[assignments[i]],
).reshape(
predicted_states.shape[0],
self.d_states,
)
assert np.array_equal(
predicted_states[0, i, :], self.states[0, i, :]
)
predicted_observations[:, i, :] = statespace.mmX(
predicted_observations.shape[0],
self.states[0, i, :],
self.transition_matrices[assignments[i]],
self.measurement_matrices[assignments[i]],
).reshape(
predicted_observations.shape[0],
self.d_observations,
)
return predicted_states, predicted_observations
def observed_condl_log_lik_first_T0_steps(
self, c: int, T0: int, *, observations: np.array = None
) -> np.array:
"""p(x|c), this marginalizes out the hidden states for a single