-
Notifications
You must be signed in to change notification settings - Fork 0
/
vbem_dlm.jl
2277 lines (1768 loc) · 73.1 KB
/
vbem_dlm.jl
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
### A Pluto.jl notebook ###
# v0.19.25
using Markdown
using InteractiveUtils
# ╔═╡ c6e50d2a-df8e-11ed-2859-b1d221d06c6d
begin
using Distributions, Plots, Random
using LinearAlgebra
using StatsFuns
using SpecialFunctions
using PlutoUI
end
# ╔═╡ bfe253c8-3ab4-4629-9a6b-423a64d8fe32
TableOfContents()
# ╔═╡ 5e08403b-2475-45d2-950a-ab4cf2aada5a
md"""
# VBEM Derivation for DLM
"""
# ╔═╡ 7971c689-4438-47ff-a896-6e61fc62d10b
md"""
A linear Gaussian state space model (LDS / DLM) can be defined as follows:
State Transition Model (**State Equation**):
$$x_t = Ax_{t-1} + w_t, \ w_t \sim \mathcal N(0, Q)$$
where $A (K \times K)$ is the state transition matrix, $Q (K \times K)$
Observation Model (**Observation Equation**):
$$y_t = Cx_t + v_t, \ v_t \sim \mathcal N(0, R)$$
where $C (D \times K)$ is the observation/emission matrix, $R (D \times D)$.
We can fix $Q$ to the identity matrix $I$ and denote the set of DLM parameters as:
$$\mathbf{θ} = (A, C, R)$$
Suppose $R$ is defined through a precision vector $\mathbf{ρ}$, such that $diag(\mathbf{ρ})$ = $R^{-1}$, and
$p(\mathbf{ρ}|a, b) = \prod_{s=1}^D \mathcal Gam(ρ_s| a, b)$
The joint probability of hidden and observed sequences are:
$p(x_{1:T}, y_{1:T}) = p(x_1)p(y_1|x_1) \prod_{t=2}^T p(x_t|x_{t-1}) p(y_t|x_t)$
It should be noted that, **SSM and HMM have closely related basic assumptions and recursive computations**.
"""
# ╔═╡ 9000f45e-0f28-4b72-ba19-34dd944b274b
md"""
## Prior specification
### Rows of the state transition matrix:
For each row j $(j = 1, 2,... K)$ of $A$, we can define a prior as follows:
$a_j \sim \mathcal N(\mathbf{0}, \ diag(\mathbf{α})^{-1})$
Here, $\mathbf{α}$ is a K-dimensional precision hyperparameter vector, and $diag(\mathbf{α})$ is a K x K diagonal matrix formed from the precision vector $\mathbf{α}$. This prior implies that the transition dynamics are regularized towards zero, and the precision hyperparameters $\mathbf{α}$ control the strength of the regularization.
### Rows of the observation/emission matrix:
For each row s $(s = 1, 2 ... D)$ of $C$, we can define a prior as follows:
$c_s \sim \mathcal N(\mathbf{0}, \ diag(ρ_s \mathbf{γ})^{-1})$
Here, $ρ_s$ is a scalar gamma-distributed random variable with hyperparameters a and b:
$ρ_s \sim \mathcal Gam(a, b)$
The vector $\mathbf{γ}$ is a K-dimensional precision hyperparameter vector, and $diag(ρ_s \mathbf{γ})$ is a K x K diagonal matrix formed by element-wise multiplication of $ρ_s$ and $$\mathbf{γ}$$.
This prior on the rows of C assumes that the mapping between hidden states and observations is regularized towards zero, with the strength of the regularization controlled by the precision parameters $ρ_s$ and $$\mathbf{γ}$$.
### Hidden State Sequence
Let $p(x_0 | μ_0, Σ_0) \sim \mathcal N(x_0 | μ_0, Σ_0)$ be an auxiliary hidden state at time $t=0$, we can express $p(x_1)$ as:
$\begin{align}
p(x_1 |μ_0, Σ_0, \mathbf{θ}) &= \int dx_0 \ p(x_0 | μ_0, Σ_0) p(x_1|x_0,\mathbf{θ})\\
&= \mathcal N(x_1|Aμ_0, A^TΣ_0A + Q)
\end{align}$
where $Σ_0$ is a multiple of the identity matrix.
"""
# ╔═╡ 477f8dbf-6797-4e7c-91be-31387f82ece7
md"""
## Variational Treatment/Approximation
Full joint probability:
$p(A, C, \mathbf{ρ}, x_{0:T}, y_{1:T}) = p(A|\mathbf{α}) p(\mathbf{ρ}|a, b) p(C|\mathbf{ρ}, \mathbf{γ}) p(x_0 | μ_0, Σ_0) \prod_{t=1}^T p(x_t|x_{t-1}, A) p(y_t|x_t, C, \mathbf{ρ})$
Log marginal likelihood:
$\begin{align}
\ln p(y_{1:T}) &= \ln \int dA \ dC \ d\mathbf{ρ} \ dx_{0:T} \ p(A, C, \mathbf{ρ}, x_{0:T}, y_{1:T}) \\
&\geq \int dA \ dC \ d\mathbf{ρ} \ dx_{0:T} \ q(A, C, \mathbf{ρ}, x_{0:T}) \ln \frac{p(A, C, \mathbf{ρ}, x_{0:T}, y_{1:T})}{q(A, C, \mathbf{ρ}, x_{0:T})}\\
&= \mathcal F
\end{align}$
"""
# ╔═╡ c5fc190c-63a1-4d94-ac29-f56d0556452f
md"""
Choose $q(...)$ such that $\mathcal F$ is of tractable form:
$q(A, C, \mathbf{ρ}, x_{0:T}) = q(A) q(C, \mathbf{ρ}) q(x_{0:T})$
$q(C, \mathbf{ρ}) = q( \mathbf{ρ}) q (C| \mathbf{ρ})$
From the prior specification:
$q(A, C, \mathbf{ρ}) = \prod_{j=1}^K q(a_j) \prod_{s=1}^D q(ρ_s) q(c_s|ρ_s)$
"""
# ╔═╡ 74482089-10fe-446b-b3f6-dc1b81b1a424
md"""
## VBM Step: θ distributions
Given expected complete data sufficient statistics: $W_A, S_A, W_C, S_C$, all are matrices obtained from VBE Step.
c.f. Beale Chap 5 5.36
$q(A) = \prod_{j=1}^K \mathcal N(a_j|Λ_A^{-1} S_{A, j}, \ Λ_A^{-1})$
where $Λ_A = diag(\mathbf{α}) + W_A$, $S_{A,j}$ is the jth column of matrix $S_A$
cf. Beale Chap 5 5.42, 5.44
$q(\mathbf{ρ}) = \prod_{s=1}^D \mathcal Ga(ρ_s| a + \frac{T}{2}, b + \frac{G_{ss}}{2})$
$q(C|\mathbf{ρ}) = \prod_{s=1}^D \mathcal N(c_s|Λ_C^{-1} S_{C, s}, \ ρ_s^{-1} Λ_C^{-1})$
where $Λ_C = diag(\mathbf{γ}) + W_C$, $S_{C,s}$ is the sth column of matrix $S_C$,
$G = \sum_{t=1}^T y_t y_t^T - S_C^T Λ_C^{-1} S_C$
After integrating out the precision vector $\mathbf{ρ}$, full marginal of C should be Student-t distributed.
### Natural parameterisation
$ϕ(\mathbf{θ}) = ϕ(A, C, R) = \{A, \ A^TA, \ C, \ R^{-1}, C^TR^{-1}C, \ R^{-1}C \}$
The VBM Step computes the expected natural parameter: $\langle ϕ(\mathbf{θ}) \rangle_{q_θ(θ)}$
"""
# ╔═╡ 9381e183-5b4e-489f-a109-4e606212986e
# hidden state sufficient statistics
struct HSS
W_A::Matrix{Float64}
S_A::Matrix{Float64}
W_C::Matrix{Float64}
S_C::Matrix{Float64}
# can be extended to incorporate driving input/ HSSMs
end
# ╔═╡ 45b0255d-72fd-4fa7-916a-4f73e730f4d5
# expected natural parameters
struct Exp_ϕ
A
AᵀA
C
R⁻¹
CᵀR⁻¹C
R⁻¹C
CᵀR⁻¹
# TO-DO: ELBO computation and Convergence check
"""
log_det_R⁻¹
"""
end
# ╔═╡ 6c1a13d3-9089-4b54-a0e5-a02fb5fdf4a1
# hyper-prior parameters
struct HPP
α::Vector{Float64} # precision vector for transition A
γ::Vector{Float64} # precision vector for emission C
a::Float64 # gamma rate of ρ
b::Float64 # gamma inverse scale of ρ
μ_0::Vector{Float64} # auxiliary hidden state mean
Σ_0::Matrix{Float64} # auxiliary hidden state co-variance
end
# ╔═╡ a8b50581-e5f3-449e-803e-ab31e6e0b812
# input: data, hyperprior, and e-step suff stats
# infer parameter posterior q_θ(θ)
function vb_m(ys, hps::HPP, ss::HSS)
D, T = size(ys)
W_A = ss.W_A
S_A = ss.S_A
W_C = ss.W_C
S_C = ss.S_C
α = hps.α
γ = hps.γ
a = hps.a
b = hps.b
K = length(α)
# q(A), q(ρ), q(C|ρ)
Σ_A = inv(diagm(α) + W_A)
Σ_C = inv(diagm(γ) + W_C)
G = sum(ys[:, t] * ys[:, t]' for t in 1:T) - S_C' * Σ_C * S_C
a_ = a + 0.5 * T
a_s = a_ * ones(D)
b_s = [b + 0.5 * G[i, i] for i in 1:D]
q_ρ = Gamma.(a_s, 1 ./ b_s)
ρ̄ = mean.(q_ρ)
# Exp_ϕ
Exp_A = S_A'*Σ_A
Exp_AᵀA = Exp_A'*Exp_A + K*Σ_A
Exp_C = S_C'*Σ_C
Exp_R⁻¹ = diagm(ρ̄)
Exp_CᵀR⁻¹C = Exp_C'*Exp_R⁻¹*Exp_C + D*Σ_C
Exp_R⁻¹C = Exp_R⁻¹*Exp_C
Exp_CᵀR⁻¹ = Exp_C'*Exp_R⁻¹
# update hyperparameter (after m-step)
α_n = [K/((K*Σ_A + Σ_A*S_A*S_A'*Σ_A)[j, j]) for j in 1:K]
γ_n = [D/((D*Σ_C + Σ_C*S_C*Exp_R⁻¹*S_C'*Σ_C)[j, j]) for j in 1:K]
# for updating gamma hyperparam a, b
exp_ρ = a_s ./ b_s
exp_log_ρ = [(digamma(a_) - log(b_s[i])) for i in 1:D]
# return expected natural parameters :: Exp_ϕ (for e-step)
return Exp_ϕ(Exp_A, Exp_AᵀA, Exp_C, Exp_R⁻¹, Exp_CᵀR⁻¹C, Exp_R⁻¹C, Exp_CᵀR⁻¹), α_n, γ_n, exp_ρ, exp_log_ρ
end
# ╔═╡ 85e2ada1-0adc-41a8-ab34-8043379ca0a4
md"""
### Testing M-step
"""
# ╔═╡ 01b6b048-6bd6-4c5a-8586-066cecf3ed51
md"""
## VBE Step: Forward Backward
"""
# ╔═╡ 781d041c-1e4d-4354-b240-12511207bde0
md"""
### Forward recursion (filtering)
**Variational derivation**
$\begin{align}
α_t(x_t) &= \frac{1}{ζ_t^{'}} \int dx_{t-1} \ \mathcal N(x_{t-1}|μ_{t-1}, Σ_{t-1}) \ \langle p(x_t| x_{t-1}) p(y_t|x_t) \rangle_{q_θ(θ)} \\
&= \frac{1}{ζ_t^{'}} \int dx_{t-1} \ \mathcal N(x_{t-1}|μ_{t-1}, Σ_{t-1}) \\
&* \exp \frac{-1}{2} (\langle (x_t - Ax_{t-1})^T I (x_t - Ax_{t-1}) + (y_t - Cx_t)^T R^{-1} (y_t - Cx_t) + K \ln|2π| + \ln|2π R| \rangle_{q_θ(θ)}) \\
&= \frac{1}{ζ_t^{'}} \int dx_{t-1} \ \mathcal N(x_{t-1}|μ_{t-1}, Σ_{t-1}) \\
&* \exp \frac{-1}{2} \{ x_{t-1}^T \langle A^TA \rangle_{q_θ(θ)} x_{t-1} - 2x_{t-1}^T \langle A \rangle_{q_θ(θ)} x_t + x_t^T \langle C^TR^{-1}C \rangle_{q_θ(θ)} x_t - 2x_t^T\langle C^TR^{-1}\rangle_{q_θ(θ)} y_t + const. \}\\
&= \mathcal N(x_t|μ_t, Σ_t)
\end{align}$
where $\langle \cdot \rangle_{q_θ(θ)}$, expectation under the variational posterior parameters are calculated from the VBM step.
Recognizing quadratic terms of $x_t$ and $x_{t-1}$ in the exponent. Analog to point-parameter derviation above, parameter expectations $\langle \cdot \rangle_{q_θ(θ)}$ from VBM step now take the place of fixed $A,C,R$, yielding:
$\mathbf{Σ^*} = (Σ_{t-1}^{-1} + \langle A^TA \rangle)^{-1}$
$m^* = Σ^* (Σ_{t-1}^{-1}μ_{t-1} + \langle A \rangle^Tx_t)$
and filtered mean and co-variance as:
$Σ_t = (I + \langle C^T R^{-1} C \rangle - \langle A \rangle \mathbf{Σ^*} \langle A \rangle^T)^{-1}$
$μ_t = Σ_t (\langle C^TR^{-1} \rangle y_t + \langle A \rangle \mathbf{Σ^*}Σ_{t-1}^{-1}μ_{t-1})$
where $t = \{1, ... T\}$
"""
# ╔═╡ cb1a9949-59e1-4ccb-8efc-aa2ffbadaab2
function v_forward(ys::Matrix{Float64}, exp_np::Exp_ϕ, hpp::HPP)
D, T = size(ys)
K = size(exp_np.A, 1)
μs = zeros(K, T)
Σs = zeros(K, K, T)
Σs_ = zeros(K, K, T)
# TO-DO: ELBO and convergence check
#Qs = zeros(D, D, T)
#fs = zeros(D, T)
# Extract μ_0 and Σ_0 from the HPP struct
μ_0 = hpp.μ_0
Σ_0 = hpp.Σ_0
# initialise for t=1
Σ₀_ = inv(inv(Σ_0) + exp_np.AᵀA)
Σs_[:, :, 1] = Σ₀_
Σs[:, :, 1] = inv(I + exp_np.CᵀR⁻¹C - exp_np.A*Σ₀_*exp_np.A')
μs[:, 1] = Σs[:, :, 1]*(exp_np.CᵀR⁻¹*ys[:, 1] + exp_np.A*Σ₀_*inv(Σ_0)μ_0)
# iterate over T
for t in 2:T
Σₜ₋₁_ = inv(inv(Σs[:, :, t-1]) + exp_np.AᵀA)
Σs_[:, :, t] = Σₜ₋₁_
Σs[:, :, t] = inv(I + exp_np.CᵀR⁻¹C - exp_np.A*Σₜ₋₁_*exp_np.A')
μs[:, t] = Σs[:, :, t]*(exp_np.CᵀR⁻¹*ys[:, t] + exp_np.A*Σₜ₋₁_*inv(Σs[:, :, t-1])μs[:, t-1])
end
return μs, Σs, Σs_
end
# ╔═╡ c9d3b75e-e1ff-4ad6-9c66-6a1b89a1b426
md"""
### Backward recursion (smoothing)
**Variational analysis** (parallel implementation)
Similarly, we use expectation of natural parameter under variational distribution (VBM outputs) to replace the fixed point $A,C,R$ in Point-parameter implementation.
$\mathbf{Ψ_t^*} = (I + \langle C^TR^{-1}C \rangle + Ψ_t^{-1})^{-1}$
$Ψ_{t-1} = (\langle A^TA \rangle - \langle A \rangle^T\mathbf{Ψ_t^*} \langle A \rangle)^{-1}$
$η_{t-1} = Ψ_{t-1} \langle A \rangle^T \mathbf{Ψ_t^*}(\langle C^TR^{-1} \rangle y_t + Ψ_t^{-1}η_t)$
where, $t = \{T, ..., 1\}$
"""
# ╔═╡ 8cb62a79-7dbc-4c94-ae7b-2e2cc12764f4
function v_backward(ys::Matrix{Float64}, exp_np::Exp_ϕ)
D, T = size(ys)
K = size(exp_np.A, 1)
ηs = zeros(K, T)
Ψs = zeros(K, K, T)
# Initialize the filter, t=T, β(x_T-1)
Ψs[:, :, T] = zeros(K, K)
ηs[:, T] = ones(K)
Ψₜ = inv(I + exp_np.CᵀR⁻¹C)
Ψs[:, :, T-1] = inv(exp_np.AᵀA - exp_np.A'*Ψₜ*exp_np.A)
ηs[:, T-1] = Ψs[:, :, T-1]*exp_np.A'*Ψₜ*exp_np.CᵀR⁻¹*ys[:, T]
for t in T-2:-1:1
Ψₜ₊₁ = inv(I + exp_np.CᵀR⁻¹C + inv(Ψs[:, :, t+1]))
Ψs[:, :, t] = inv(exp_np.AᵀA - exp_np.A'*Ψₜ₊₁*exp_np.A)
ηs[:, t] = Ψs[:, :, t]*exp_np.A'*Ψₜ₊₁*(exp_np.CᵀR⁻¹*ys[:, t+1] + inv(Ψs[:, :, t+1])ηs[:, t+1])
end
# for t=1, this correspond to β(x_0), the probability of all the data given the setting of the auxiliary x_0 hidden state.
Ψ₁ = inv(I + exp_np.CᵀR⁻¹C + inv(Ψs[:, :, 1]))
Ψ_0 = inv(exp_np.AᵀA - exp_np.A'*Ψ₁*exp_np.A)
η_0 = Ψs[:, :, 1]*exp_np.A'*Ψ₁*(exp_np.CᵀR⁻¹*ys[:, 1] + inv(Ψs[:, :, 1])ηs[:, 1])
return ηs, Ψs, η_0, Ψ_0
end
# ╔═╡ d5457335-bc65-4bf1-b6ed-796dd5e2ab69
md"""
### Marginal and Pairwise beliefs
**Variational Bayesian**
We get **marginal beliefs** ($\mathbf{γ}$) by combining α and β messages from forward and backward recursion:
$\begin{align}
p(x_t|y_{1:T}) &\propto p(x_t|y_{1:t}) \ p(y_{t+1:T}|x_t) \\
&= α_t(x_t)\ β_t(x_t) \\
&= \mathcal N(x_t|ω_t, Υ_{t,t})
\end{align}$
Product of two Normal distributions are still normally distributed, with
$Υ_{t,t} = (Σ_t^{-1} + Ψ_t^{-1})^{-1}$
$ω_t = Υ_{t,t}(Σ_t^{-1}μ_t + Ψ_t^{-1}η_t)$
We get **pairwise beliefs** ($\mathbf{ξ}$) as:
$\begin{align}
p(x_t, x_{t+1}|y_{1:T}) &\propto p(x_t|y_{1:t}) \ p(x_{t+1}|x_t)\ p(y_{t+1}|x_{t+1})\ p(y_{t+2:T}|x_{t+1}) \\
&= α_t(x_t)\ p(x_{t+1}|x_t) \ p(y_{t+1}|x_{t+1}) \ β_{t+1}(x_{t+1}) \\
&\xrightarrow{VB} α_t(x_t) \ \exp \langle \ln p(x_{t+1}|x_t) + \ln p(y_{t+1}|x_{t+1}) \rangle \ β_{t+1}(x_{t+1}) \\
&= \mathcal N(\begin{bmatrix} x_t \\ x_{t+1} \end{bmatrix}|\begin{bmatrix} ω_t \\ ω_{t+1} \end{bmatrix}, \begin{bmatrix} Υ_{t,t} \ \ Υ_{t,t+1} \\ Υ_{t,t+1}^T \ \ Υ_{t+1,t+1}\end{bmatrix})\\
\end{align}$
where $Υ_{t,t+1} = \mathbf{Σ^*} \langle A \rangle^T (I + \langle C^T R^{-1} C \rangle + Ψ_{t+1}^{-1} - \langle A \rangle \mathbf{Σ^*} \langle A \rangle^T)^{-1}$
"""
# ╔═╡ 96ff4afb-fe7f-471a-b15e-26676c600090
# combine forward and backward pass
# marginals beliefs t = 0, ..., T (re-use for VB)
function parallel_smoother(μs, Σs, ηs, Ψs, η_0, Ψ_0, μ_0, Σ_0)
K, T = size(μs)
Υs = zeros(K, K, T)
ωs = zeros(K, T)
# ending condition t=T
Υs[:, :, T] = Σs[:, :, T]
ωs[:, T] = μs[:, T]
for t in 1:(T-1)
Υs[:, :, t] = inv(inv(Σs[:, :, t]) + inv(Ψs[:, :, t]))
ωs[:, t] = Υs[:, :, t]*(inv(Σs[:, :, t])μs[:, t] + inv(Ψs[:, :, t])ηs[:, t])
end
# t = 0
Υ_0 = inv(inv(Σ_0) + inv(Ψ_0))
ω_0 = Υ_0*(inv(Σ_0)μ_0 + inv(Ψ_0)η_0)
return ωs, Υs, ω_0, Υ_0
end
# ╔═╡ 14d4e0a3-8db0-4c57-bb33-497e1bd3c64c
md"""
In summary, VBE Step consists of a forward pass (α_messages) and a backward pass (β-messages), and computing the marginal and pair-wise beliefs.
N.B. **calculating marginals straight after each $β_t(x_t)$ could be more efficient**
"""
# ╔═╡ c1640ff6-3047-42a5-a5cd-d0c77aa41179
function v_pairwise_x(Σs_, exp_np::Exp_ϕ, Ψs)
T = size(Σs_, 3)
K = size(exp_np.A, 1)
# cross-covariance is then computed for all time steps t = 0, ..., T−1
Υ_ₜ₋ₜ₊₁ = zeros(K, K, T)
for t in 1:T-2
Υ_ₜ₋ₜ₊₁[:, :, t+1] = Σs_[:, :, t+1]*exp_np.A'*inv(I + exp_np.CᵀR⁻¹C + inv(Ψs[:, :, t+1]) - exp_np.A*Σs_[:, :, t+1]*exp_np.A')
end
# t=0, the cross-covariance between the zeroth and first hidden states.
Υ_ₜ₋ₜ₊₁[:, :, 1] = Σs_[:, :, 1]*exp_np.A'*inv(I + exp_np.CᵀR⁻¹C + inv(Ψs[:, :, 1]) - exp_np.A*Σs_[:, :, 1]*exp_np.A')
# t=T-1, Ψs[T] = 0 special case
Υ_ₜ₋ₜ₊₁[:, :, T] = Σs_[:, :, T]*exp_np.A'*inv(I + exp_np.CᵀR⁻¹C - exp_np.A*Σs_[:, :, T]*exp_np.A')
return Υ_ₜ₋ₜ₊₁
end
# ╔═╡ 6749ddf8-633b-498e-aecb-9e1592050ed2
md"""
### Expected sufficient statistics $W_A, S_A, W_C, S_C$
$W_A = \sum_{t=1}^T \langle x_{t-1} x_{t-1}^T \rangle = \sum_{t=1}^T Υ_{t-1,t-1} + ω_{t-1} ω_{t-1}^T$
$S_A = \sum_{t=1}^T \langle x_{t-1} x_t^T \rangle = \sum_{t=1}^T Υ_{t-1,t} + ω_{t-1} ω_t^T$
$W_C = \sum_{t=1}^T \langle x_t x_t^T \rangle = \sum_{t=1}^T Υ_{t,t} + ω_t ω_t^T$
$S_C = \sum_{t=1}^T \langle x_t \rangle y_t^T = \sum_{t=1}^T ω_ty_t^T$
"""
# ╔═╡ 52a70be4-fb8c-40d8-9c7a-226649ada6e3
md"""
**Debug notes**: if all hidden states are treated as observed, i.e. parse true x from data generation
$\langle x_t x_t^T \rangle = \int x_t x_t^T q(x_t) \ dx_t$
if $x_t$ is observed, $q(x_t)$ can be viewed as direct measure (delta function), hence
$\langle x_t x_t^T \rangle = x_t x_t^T$
"""
# ╔═╡ fbc24a7c-48a0-43cc-9dd2-440acfb41c39
# infer hidden state distribution q_x(x_0:T)
function vb_e(ys::Matrix{Float64}, exp_np::Exp_ϕ, hpp::HPP, smooth_out=false)
_, T = size(ys)
# forward pass α_t(x_t)
μs, Σs, Σs_ = v_forward(ys, exp_np, hpp)
# backward pass β_t(x_t)
ηs, Ψs, η₀, Ψ₀ = v_backward(ys, exp_np)
# marginal (smoothed) means, covs, and pairwise beliefs
ωs, Υs, ω_0, Υ_0 = parallel_smoother(μs, Σs, ηs, Ψs, η₀, Ψ₀, hpp.μ_0, hpp.Σ_0)
Υ_ₜ₋ₜ₊₁ = v_pairwise_x(Σs_, exp_np, Ψs)
# hidden state sufficient stats
W_A = sum(Υs[:, :, t-1] + ωs[:, t-1] * ωs[:, t-1]' for t in 2:T)
W_A += Υ_0 + ω_0*ω_0'
S_A = sum(Υ_ₜ₋ₜ₊₁[:, :, t] + ωs[:, t-1] * ωs[:, t]' for t in 2:T)
S_A += Υ_ₜ₋ₜ₊₁[:, :, 1] + ω_0*ωs[:, 1]'
W_C = sum(Υs[:, :, t] + ωs[:, t] * ωs[:, t]' for t in 1:T)
S_C = sum(ωs[:, t] * ys[:, t]' for t in 1:T)
if (smooth_out) # return variational smoothed mean, cov of hidden states
return ωs, Υs
end
return HSS(W_A, S_A, W_C, S_C), ω_0, Υ_0
end
# ╔═╡ a810cf76-2c64-457c-b5ea-eaa8bf4b1d42
md"""
### Testing E-step
"""
# ╔═╡ 408dd6d8-cb5f-49ce-944b-50a0d9cebef5
md"""
Ground truth HSS using x_true
"""
# ╔═╡ 9373df69-ba17-46e0-a48a-ab1ca7dc3a9f
md"""
### Hyper-param learning - Hierachical Model
N.B. should be cautious with model comparison and structure discovery tasks.
Our prior specification involves a few hyper-parameters $\mathbf{α}, \mathbf{γ}$, and the prior parameters $Σ_0$ and $μ_0$
Straight after the VBM Step, the following can be updated:
$α_j^{-1} = \frac{1}{K}\{K Σ_A + Σ_AS_AS_A^TΣ_A\}_{j, j}$
$γ_j^{-1} = \frac{1}{D}\{D Σ_C + Σ_C S_C diag(\mathbf{\bar{ρ}}) S_C^T Σ_C \}_{j, j}$
$Σ_0 = Υ_{0, 0}$
$μ_0 = ω_0$
The **+ve** hyperparameters $a, b$ governing the prior distribution over the output noise,
$R = diag (\mathbf{ρ})$, are set to the fixed point of the equations [See Beal Appendix C.2 for how to solve]:
$ψ(a) = \ln b + \frac{1}{D} \sum_{s=1}^D \bar{\ln ρ_s}$
$\frac{1}{b} = \frac{1}{D \times a} \sum_{s=1}^D \bar{ρ_s}$
Updated during learning, for a valid gamma distribution, both a and b needs to be positive!
Using properties of Gamma distribution (shape $a$, inverse scale $b$), expectation and log expectation are given by:
$\bar{ρ_s} \equiv \langle ρ_s \rangle = \frac{a + 0.5 T}{b + 0.5 G_{ss}}$
$\bar{\ln ρ_s} \equiv \langle \ln ρ_s \rangle = ψ(a + 0.5T) - \ln(b + 0.5 G_{ss})$
To avoid solving for -ve values of $a$, we can re-parameterize $a$ to $a'$ such that $a = \exp(a')$ to ensure $a$ is always positive, and then solve a different fixed point equation for $a'$:
$a_n' = a' - \frac{g(a')}{g'(a')}$
$\exp(a_n') = \exp(a') \exp(-\frac{g(a')}{g'(a')})$
$g(a') = ψ(\exp(a')) - a' + \ln d - c$
$g'(a') = ψ'(\exp(a')) \exp(a') - 1$
Hence,
$a_n = a \exp(- \frac{ψ(a) - \ln (a) + \ln d - c}{a ψ'(a) -1)})$
"""
# ╔═╡ 87667a9e-02aa-4104-b5a0-0f6b9e98ba96
# cf. Newton's method, from Beal appendix C2
function update_ab(hpp::HPP, exp_ρ::Vector{Float64}, exp_log_ρ::Vector{Float64})
D = length(exp_ρ)
d = mean(exp_ρ)
c = mean(exp_log_ρ)
# Update `a` using fixed point iteration
a = hpp.a
for _ in 1:100
ψ_a = digamma(a)
ψ_a_p = trigamma(a)
a_new = a * exp(-(ψ_a - log(a) + log(d) - c) / (a * ψ_a_p - 1))
a = a_new
# check convergence
if abs(a_new - a) < 1e-5
break
end
end
# Update `b` using the converged value of `a`
b = a/d
return a, b
end
# ╔═╡ b0b1f14d-4fbd-4995-845f-f19990460329
md"""
## VB DLM
"""
# ╔═╡ 1902c1f1-1246-4ab3-88e6-35619d685cdd
function vb_dlm(ys::Matrix{Float64}, hpp::HPP, hpp_learn=false, max_iter=100, r_seed=99, debug=false)
D, T = size(ys)
K = length(hpp.α)
"""
# random initialisation
Random.seed!(r_seed)
W_A = rand(K, K) + K*I
S_A = rand(K, K) + K*I
W_C = rand(K, K) + K*I
S_C = rand(D, K) + D*I
"""
# no random initialistion
W_A = Matrix{Float64}(T*I, K, K)
S_A = Matrix{Float64}(T*I, K, K)
W_C = Matrix{Float64}(T*I, K, K)
S_C = Matrix{Float64}(T*I, K, K)
hss = HSS(W_A, S_A, W_C, S_C)
exp_np = missing
for i in 1:max_iter
exp_np, α_n, γ_n, exp_ρ, exp_log_ρ = vb_m(ys, hpp, hss)
hss, ω_0, Υ_0 = vb_e(ys, exp_np, hpp)
if (hpp_learn)
if (i%5 == 0) # update hyperparam every 5 iterations
a, b = update_ab(hpp, exp_ρ, exp_log_ρ)
hpp = HPP(α_n, γ_n, a, b, ω_0, Υ_0)
end
end
#TO-DO: ELBO and Convergence check
if (i == max_iter)
if (debug) # debug a, b update
return exp_ρ, exp_log_ρ
end
end
end
return exp_np
end
# ╔═╡ 73fb09dd-9e2e-481e-a198-6b026e3bde3a
md"""
# Testing with Synthetic data
"""
# ╔═╡ 3c63b27b-76e3-4edc-9b56-345738b97c41
md"""
Ground truth values of DLM parameters A, C, R
"""
# ╔═╡ 3508a99a-e0d3-41ec-a040-5b7405d6212b
md"""
### Model parameter inference
"""
# ╔═╡ 17c0f85b-f1f2-4a26-a0f2-5fae3c3615fd
md"""
### Hidden state x inference (variational)
"""
# ╔═╡ 7b185270-58d5-4406-8768-103d798fa326
md"""
### With Hyperparameter learning
"""
# ╔═╡ dab1fe9c-20a4-4376-beaf-02b5292ca7cd
md"""
Adding hyperparameter learning showed better results of learning A, C, R.
Hidden state (xs) learning outperform Kalman Filter and very close to Kalman smoother.
"""
# ╔═╡ 24de2bcb-cf9d-44f7-b1d7-f80ae8c08ed1
md"""
## Extra Testing
"""
# ╔═╡ e3e78fb1-00aa-4399-8330-1d4a08742b42
md"""
Case **probabilistic PCA**, To reduce a DLM to PPCA, we should set:
The state transition matrix A to be a zero matrix. This means that the hidden state does not depend on the previous hidden state, which is consistent with the assumption of PPCA where hidden states are independently drawn from a Gaussian distribution.
The process noise covariance matrix Q to be an identity matrix. This means that the hidden states are sampled from a standard Gaussian distribution.
The initial state mean to be a zero vector and the initial state covariance to be an identity matrix. This is consistent with the assumption in PPCA where the hidden states are sampled from a standard Gaussian distribution.
With these settings, the DLM essentially becomes a model where the observed variables are linear functions of the hidden states (with some Gaussian noise), and the hidden states are independently drawn from a Gaussian distribution. This is the setting of PPCA.
"""
# ╔═╡ b2818ed9-6ef8-4398-a9d4-63b1d399169c
md"""
## Appendix
"""
# ╔═╡ 8fed847c-93bc-454b-94c7-ba1d13c73b04
md"""
**Generate test data**
"""
# ╔═╡ a5ae35dc-cc4b-48bd-869e-37823b8073d2
function gen_data(A, C, Q, R, μ_0, Σ_0, T)
K, _ = size(A)
D, _ = size(C)
x = zeros(K, T)
y = zeros(D, T)
x[:, 1] = rand(MvNormal(A*μ_0, A'*Σ_0*A + Q))
y[:, 1] = C * x[:, 1] + rand(MvNormal(zeros(D), R))
for t in 2:T
if (tr(Q) != 0)
x[:, t] = A * x[:, t-1] + rand(MvNormal(zeros(K), Q))
else
x[:, t] = A * x[:, t-1] # Q zero matrix special case
end
y[:, t] = C * x[:, t] + rand(MvNormal(zeros(D), R))
end
return y, x
end
# ╔═╡ baca3b20-16ac-4e37-a2bb-7512d1c99eb8
md"""
### Kalman Filter
"""
# ╔═╡ e7ca9061-64dc-44ef-854e-45b8015abad1
md"""
Aside, **Point-parameter** Kalman Filter for DLM (cf. Beale Chap 5 5.80, 5.81, 5.85)
Filtering density: $α_t(x_t) \equiv p(x_t|y_{1:t})$
$\begin{align}
α_t(x_t) &= \frac{p(x_t|y_{1:t-1}) p(y_t|x_t)}{p(y_t|y_{1:t-1})}\\
&= \int dx_{t-1} \ p(x_{t-1}|y_{1:t-1}) p(x_t|x_{t-1}) \frac{p(y_t|x_t)}{p(y_t|y_{1:t-1})} \\
&= \frac{1}{p(y_t|y_{1:t-1})} \int dx_{t-1} \ α_{t-1}(x_{t-1}) \ p(x_t|x_{t-1}) \ p(y_t|x_t) \\
&= \frac{1}{ζ_t} \int dx_{t-1} \ \mathcal N(x_{t-1}|μ_{t-1}, Σ_{t-1}) \ \mathcal N(x_t|Ax_{t-1}, I) \ \mathcal N(y_t| Cx_t, R)\\
&= \mathcal N(x_t|μ_t, Σ_t)
\end{align}$
Complete the square of qudratic terms involving $x_{t-1}$ form a Normal distribution $\mathcal N(x_{t-1}|m^*, Σ^*)$
$\mathbf{Σ^*} = (Σ_{t-1}^{-1} + A^TA)^{-1}$
$m^* = Σ^* (Σ_{t-1}^{-1}μ_{t-1} + A^T x_t)$
Filtered mean $μ_t$ and co-variance $Σ_t$ are computed by marginalising $x_{t-1}$, using the expression $\mathbf{Σ^*}$:
$Σ_t = (I + C^T R^{-1} C - A\mathbf{Σ^*}A^T)^{-1}$
$μ_t = Σ_t (C^TR^{-1}y_t + A\mathbf{Σ^*}Σ_{t-1}^{-1}μ_{t-1})$
The denominator of the normalising constant $ζ_t(y_t)$ is also a Normal distribution, and we have (using DLM with R notations):
$p(y_{1:T}) = p(y_1) \prod_{t=2}^T p(y_t|y_{1:t-1}) = \prod_{t=1}^T ζ_t(y_t)$
$ζ_t(y_t) \sim \mathcal N(y_t|f_t, Q_t)$
$Q_t = (R^{-1} - R^{-1}CΣ_tC^TR^{-1})^{-1}$
$f_t = Q_tR^{-1}CΣ_tA\mathbf{Σ^*}Σ_{t-1}^{-1}μ_{t-1}$
N.B. Unlike `Dynamic Linear Model with R` Chap 2.7.2, results above taken from Beal's thesis have not been simplified, this is a purposeful choice in order to get an analog with the **Variational Bayesian derviation** next.
"""
# ╔═╡ 59bcc9bf-276c-47e1-b6a9-86f90571c0fb
# using Beale 5.77, 5.80, 5.81, forward pass - Kalman-filter
function p_forward(ys, A, C, R, μ₀, Σ₀)
D, T = size(ys)
K = size(A, 1)
μs = zeros(K, T)
Σs = zeros(K, K, T)
Σs_ = zeros(K, K, T)
Qs = zeros(D, D, T)
fs = zeros(D, T)
# Initialize the filter, t=1
Σ₀_ = inv(inv(Σ₀) + A'A)
Σs_[:, :, 1] = Σ₀_
Σs[:, :, 1] = inv(I + C'inv(R)C - A*Σ₀_*A')
μs[:, 1] = Σs[:, :, 1]*(C'inv(R)ys[:, 1] + A*Σ₀_*inv(Σ₀)μ₀)
Qs[:, :, 1] = inv(inv(R) - inv(R)*C*Σs[:, :, 1]*C'*inv(R))
fs[:, 1] = Qs[:, :, 1]*inv(R)*C*Σs[:, :, 1]*A*Σ₀_*inv(Σ₀)*μ₀
#fs[:, 1] = C*A*μ₀
#Qs[:, :, 1] = R + C*(I+A*Σ₀*A')*C'
for t in 2:T
Σₜ₋₁_ = inv(inv(Σs[:, :, t-1]) + A'A)
Σs_[:, :, 1] = Σₜ₋₁_
Σs[:, :, t] = inv(I + C'inv(R)C - A*Σₜ₋₁_*A')
μs[:, t] = Σs[:, :, t]*(C'inv(R)ys[:, t] + A*Σₜ₋₁_*inv(Σs[:, :, t-1])μs[:, t-1])
Qs[:, :, t] = inv(inv(R) - inv(R)*C*Σs[:, :, t]*C'*inv(R))
fs[:, t] = Qs[:, :, t]*inv(R)*C*Σs[:, :, t]*A*Σₜ₋₁_*inv(Σs[:, :, t-1])*μs[:, t-1]
#fs[:, t] = C*A*μs[:, t-1]
#Qs[:, :, 1] = R + C*(I+A*Σs[:, :, t-1]*A')*C'
end
return μs, Σs, fs, Qs, Σs_
end
# ╔═╡ 1a129b6f-74f0-404c-ae4f-3ae39c8431aa
begin
# Ground truth values (A, C, R)
A = [0.8 -0.1; 0.2 0.75]
C = [1.0 0.0; 0.0 1.0]
R = Diagonal([0.33, 0.33]) # prefer small R to get better filtered accuracy, c.f signal to noise ratio (DLM with R Chap 2)
μ_0 = [0.0, 0.0]
Σ_0 = Diagonal([1.0, 1.0])
T = 2000
# Generate the toy dataset
Random.seed!(100)
y, x_true = gen_data(A, C, Diagonal([1.0, 1.0]), R, μ_0, Σ_0, T)
# Test the Kalman filter
x_hat, Px, y_hat, Py, _ = p_forward(y, A, C, R, μ_0, Σ_0)
end
# ╔═╡ 2c9a233f-3a96-43dc-b783-b82642a82590
A, C, R
# ╔═╡ d9cb7c74-007d-4229-a576-a7a41fff565b
let
D, T = size(y)
K = size(A, 1)
# DEBUG, initialise HSS using real x from data generation
W_A = sum(x_true[:, t-1] * x_true[:, t-1]' for t in 2:T)
W_A += μ_0*μ_0'
S_A = sum(x_true[:, t-1] * x_true[:, t]' for t in 2:T)
S_A += μ_0*x_true[:, 1]'
W_C = sum(x_true[:, t] * x_true[:, t]' for t in 1:T)
S_C = sum(x_true[:, t] * y[:, t]' for t in 1:T)
hss = HSS(W_A, S_A, W_C, S_C)
α = ones(K)
γ = ones(K)
a = 0.1
b = 0.1
μ_0 = zeros(K)
Σ_0 = Matrix{Float64}(I, K, K)
hpp = HPP(α, γ, a, b, μ_0, Σ_0)
# should recover values of A, C, R close to ground truth
exp_np = vb_m(y, hpp, hss)[1]
end
# ╔═╡ 8a73d154-236d-4660-bb21-24681ed7d315
let
D, T = size(y)
K = size(A, 1)
# use fixed A,C,R from ground truth for the exp_np::Exp_ϕ
e_A = A
e_AᵀA = A'A
e_C = C
e_R⁻¹ = inv(R)
e_CᵀR⁻¹C = e_C'*e_R⁻¹*e_C
e_R⁻¹C = e_R⁻¹*e_C
e_CᵀR⁻¹ = e_C'*e_R⁻¹
exp_np = Exp_ϕ(e_A, e_AᵀA, e_C, e_R⁻¹, e_CᵀR⁻¹C, e_R⁻¹C, e_CᵀR⁻¹)
α = ones(K)
γ = ones(K)
a = 0.1
b = 0.1
μ_0 = zeros(K)
Σ_0 = Matrix{Float64}(I, K, K)
hpp = HPP(α, γ, a, b, μ_0, Σ_0)
# should recover very similar hss using ground-truth xs
vb_e(y, exp_np, hpp)[1]
end
# ╔═╡ fb472969-3c3c-4787-8cf1-296f2c13ddf5
let
W_A = sum(x_true[:, t-1] * x_true[:, t-1]' for t in 2:T)
W_A += μ_0*μ_0'
S_A = sum(x_true[:, t-1] * x_true[:, t]' for t in 2:T)
S_A += μ_0*x_true[:, 1]'
W_C = sum(x_true[:, t] * x_true[:, t]' for t in 1:T)
S_C = sum(x_true[:, t] * y[:, t]' for t in 1:T)
hss = HSS(W_A, S_A, W_C, S_C)
end
# ╔═╡ f871da95-6710-4c0f-a3a1-890dd59a41a1
A, C, R
# ╔═╡ 079cd7ef-632d-41d0-866d-6678808a8f4c
begin
K = size(A, 1)
D = size(y, 1)
# specify initial priors (hyper-params)
α = ones(K)
γ = ones(K)
a = 0.001
b = 0.001
hpp = HPP(α, γ, a, b, μ_0, Σ_0)
exp_f = vb_dlm(y, hpp) # no hyperparameter learning
xs, σs = vb_e(y, exp_f, hpp, true)
exp_f.A, exp_f.C, inv(exp_f.R⁻¹)
end
# ╔═╡ d60b91ea-a020-41b5-9364-787167f0bac9
let
exp_ρ, exp_log_ρ = vb_dlm(y, hpp, true, 100, 99, true)
a, b = update_ab(hpp, exp_ρ, exp_log_ρ)
a/b # ρ̄_s, which is the inverse of R's sth diagonal entry
end
# ╔═╡ 14a209dd-be4c-47f0-a343-1cfb97b7d04a
# ╠═╡ disabled = true
#=╠═╡
let
T = size(y, 2)
p1 = plot(1:T, x_true[1, :], label="True xs[1]", linewidth=2)
plot!(1:T, x_hat[1, :], label="Filtered xs[1]", linewidth=2, linestyle=:dash)
end
╠═╡ =#
# ╔═╡ 5c221210-e1df-4015-b959-6d330b47be29
# ╠═╡ disabled = true
#=╠═╡
let
T = size(y, 2)
p2 = plot(1:T, x_true[2, :], label="True xs[2]", linewidth=2)
plot!(1:T, x_hat[2, :], label="Filtered xs[2]", linewidth=2, linestyle=:dash)
end
╠═╡ =#
# ╔═╡ 7c20c3ab-b0ae-48fc-b2f0-9cde30559bf5
# ╠═╡ disabled = true
#=╠═╡
let
T = size(y, 2)
_, _, y_hat, y_cov = p_forward(y, A, C, R, μ_0, Σ_0)
y_hat = circshift(y_hat, (0, -1))
y_hat[:, T] .= NaN # Set the first column to NaN to avoid connecting the last point to the first
p1 = plot(1:T, y[1, :], label="True y[1]", linewidth=2)
plot!(1:T, y_hat[1, :], label="Filtered y[1]", linewidth=2, linestyle=:dash)
end
╠═╡ =#
# ╔═╡ e02d0dd5-6bab-4548-8bbe-d9b1759688c5
# ╠═╡ disabled = true
#=╠═╡
let
T = size(y, 2)
_, _, y_hat, y_cov = p_forward(y, A, C, R, μ_0, Σ_0)
y_hat = circshift(y_hat, (0, -1))
y_hat[:, T] .= NaN
p2 = plot(1:T, y[2, :], label="True y[2]", linewidth=2)
plot!(1:T, y_hat[2, :], label="Filtered y[2]", linewidth=2, linestyle=:dash)
end
╠═╡ =#
# ╔═╡ c417e618-41c2-454c-9b27-470988215d48
md"""
Aside, **Point-parameter** Parallel Smoother
Define, β-messages as:
$β_t(x_t) \equiv p(y_{t+1:T}|x_t)$
Then, analogous to the α-message from the Kalman Filter:
$\begin{align}
β_{t-1}(x_{t-1}) &= p(y_{t:T}|x_{t-1})\\
&= \int dx_t \ p(x_t, y_t, y_{t+1:T}|x_{t-1})\\
&= \int dx_t \ p(x_t|x_{t-1}) \ p(y_t|x_t) \ p(y_{t+1:T}|x_t)\\
&= \int dx_t \ p(x_t|x_{t-1}) \ p(y_t|x_t) \ β_t(x_t)\\