forked from SMPyBandits/SMPyBandits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Experiments_of_statistical_tests_for_piecewise_stationary_bandit.py
2695 lines (1636 loc) · 118 KB
/
Experiments_of_statistical_tests_for_piecewise_stationary_bandit.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
# coding: utf-8
# # Table of Contents
# <p><div class="lev1 toc-item"><a href="#Requirements-and-helper-functions" data-toc-modified-id="Requirements-and-helper-functions-1"><span class="toc-item-num">1 </span>Requirements and helper functions</a></div><div class="lev2 toc-item"><a href="#Requirements" data-toc-modified-id="Requirements-11"><span class="toc-item-num">1.1 </span>Requirements</a></div><div class="lev2 toc-item"><a href="#Mathematical-notations-for-stationary-problems" data-toc-modified-id="Mathematical-notations-for-stationary-problems-12"><span class="toc-item-num">1.2 </span>Mathematical notations for stationary problems</a></div><div class="lev2 toc-item"><a href="#Generating-stationary-data" data-toc-modified-id="Generating-stationary-data-13"><span class="toc-item-num">1.3 </span>Generating stationary data</a></div><div class="lev2 toc-item"><a href="#Mathematical-notations-for-piecewise-stationary-problems" data-toc-modified-id="Mathematical-notations-for-piecewise-stationary-problems-14"><span class="toc-item-num">1.4 </span>Mathematical notations for piecewise stationary problems</a></div><div class="lev2 toc-item"><a href="#Generating-fake-piecewise-stationary-data" data-toc-modified-id="Generating-fake-piecewise-stationary-data-15"><span class="toc-item-num">1.5 </span>Generating fake piecewise stationary data</a></div><div class="lev1 toc-item"><a href="#Python-implementations-of-some-statistical-tests" data-toc-modified-id="Python-implementations-of-some-statistical-tests-2"><span class="toc-item-num">2 </span>Python implementations of some statistical tests</a></div><div class="lev2 toc-item"><a href="#Monitored" data-toc-modified-id="Monitored-21"><span class="toc-item-num">2.1 </span><code>Monitored</code></a></div><div class="lev2 toc-item"><a href="#CUSUM" data-toc-modified-id="CUSUM-22"><span class="toc-item-num">2.2 </span><code>CUSUM</code></a></div><div class="lev2 toc-item"><a href="#PHT" data-toc-modified-id="PHT-23"><span class="toc-item-num">2.3 </span><code>PHT</code></a></div><div class="lev2 toc-item"><a href="#Gaussian-GLR" data-toc-modified-id="Gaussian-GLR-24"><span class="toc-item-num">2.4 </span><code>Gaussian GLR</code></a></div><div class="lev2 toc-item"><a href="#Bernoulli-GLR" data-toc-modified-id="Bernoulli-GLR-25"><span class="toc-item-num">2.5 </span><code>Bernoulli GLR</code></a></div><div class="lev2 toc-item"><a href="#Sub-Gaussian-GLR" data-toc-modified-id="Sub-Gaussian-GLR-26"><span class="toc-item-num">2.6 </span><code>Sub-Gaussian GLR</code></a></div><div class="lev2 toc-item"><a href="#List-of-all-Python-algorithms" data-toc-modified-id="List-of-all-Python-algorithms-27"><span class="toc-item-num">2.7 </span>List of all Python algorithms</a></div><div class="lev1 toc-item"><a href="#Comparing-the-different-implementations" data-toc-modified-id="Comparing-the-different-implementations-3"><span class="toc-item-num">3 </span>Comparing the different implementations</a></div><div class="lev2 toc-item"><a href="#Generating-some-toy-data" data-toc-modified-id="Generating-some-toy-data-31"><span class="toc-item-num">3.1 </span>Generating some toy data</a></div><div class="lev2 toc-item"><a href="#Checking-time-efficiency" data-toc-modified-id="Checking-time-efficiency-32"><span class="toc-item-num">3.2 </span>Checking time efficiency</a></div><div class="lev2 toc-item"><a href="#Checking-detection-delay" data-toc-modified-id="Checking-detection-delay-33"><span class="toc-item-num">3.3 </span>Checking detection delay</a></div><div class="lev2 toc-item"><a href="#Checking-false-alarm-probabilities" data-toc-modified-id="Checking-false-alarm-probabilities-34"><span class="toc-item-num">3.4 </span>Checking false alarm probabilities</a></div><div class="lev2 toc-item"><a href="#Checking-missed-detection-probabilities" data-toc-modified-id="Checking-missed-detection-probabilities-35"><span class="toc-item-num">3.5 </span>Checking missed detection probabilities</a></div><div class="lev1 toc-item"><a href="#More-simulations-and-some-plots" data-toc-modified-id="More-simulations-and-some-plots-4"><span class="toc-item-num">4 </span>More simulations and some plots</a></div><div class="lev2 toc-item"><a href="#Run-a-check-for-a-grid-of-values" data-toc-modified-id="Run-a-check-for-a-grid-of-values-41"><span class="toc-item-num">4.1 </span>Run a check for a grid of values</a></div><div class="lev2 toc-item"><a href="#A-version-using-joblib.Parallel-to-use-multi-core-computations" data-toc-modified-id="A-version-using-joblib.Parallel-to-use-multi-core-computations-42"><span class="toc-item-num">4.2 </span>A version using <code>joblib.Parallel</code> to use multi-core computations</a></div><div class="lev2 toc-item"><a href="#Checking-on-a-small-grid-of-values" data-toc-modified-id="Checking-on-a-small-grid-of-values-43"><span class="toc-item-num">4.3 </span>Checking on a small grid of values</a></div><div class="lev2 toc-item"><a href="#Plotting-the-result-as-a-2D-image" data-toc-modified-id="Plotting-the-result-as-a-2D-image-44"><span class="toc-item-num">4.4 </span>Plotting the result as a 2D image</a></div><div class="lev3 toc-item"><a href="#First-example" data-toc-modified-id="First-example-441"><span class="toc-item-num">4.4.1 </span>First example</a></div><div class="lev4 toc-item"><a href="#For-Monitored" data-toc-modified-id="For-Monitored-4411"><span class="toc-item-num">4.4.1.1 </span>For <code>Monitored</code></a></div><div class="lev4 toc-item"><a href="#For-CUSUM" data-toc-modified-id="For-CUSUM-4412"><span class="toc-item-num">4.4.1.2 </span>For <code>CUSUM</code></a></div><div class="lev3 toc-item"><a href="#Second-example" data-toc-modified-id="Second-example-442"><span class="toc-item-num">4.4.2 </span>Second example</a></div><div class="lev4 toc-item"><a href="#For-Monitored" data-toc-modified-id="For-Monitored-4421"><span class="toc-item-num">4.4.2.1 </span>For <code>Monitored</code></a></div><div class="lev4 toc-item"><a href="#For-Monitored-for-Gaussian-data" data-toc-modified-id="For-Monitored-for-Gaussian-data-4422"><span class="toc-item-num">4.4.2.2 </span>For <code>Monitored</code> for Gaussian data</a></div><div class="lev4 toc-item"><a href="#For-CUSUM" data-toc-modified-id="For-CUSUM-4423"><span class="toc-item-num">4.4.2.3 </span>For <code>CUSUM</code></a></div><div class="lev4 toc-item"><a href="#For-PHT" data-toc-modified-id="For-PHT-4424"><span class="toc-item-num">4.4.2.4 </span>For <code>PHT</code></a></div><div class="lev4 toc-item"><a href="#For-Bernoulli-GLR" data-toc-modified-id="For-Bernoulli-GLR-4425"><span class="toc-item-num">4.4.2.5 </span>For <code>Bernoulli GLR</code></a></div><div class="lev4 toc-item"><a href="#For-Gaussian-GLR" data-toc-modified-id="For-Gaussian-GLR-4426"><span class="toc-item-num">4.4.2.6 </span>For <code>Gaussian GLR</code></a></div><div class="lev4 toc-item"><a href="#For-Sub-Gaussian-GLR" data-toc-modified-id="For-Sub-Gaussian-GLR-4427"><span class="toc-item-num">4.4.2.7 </span>For <code>Sub-Gaussian GLR</code></a></div><div class="lev1 toc-item"><a href="#Exploring-the-parameters-of-change-point-detection-algorithms:-how-to-tune-them?" data-toc-modified-id="Exploring-the-parameters-of-change-point-detection-algorithms:-how-to-tune-them?-5"><span class="toc-item-num">5 </span>Exploring the parameters of change point detection algorithms: how to tune them?</a></div><div class="lev2 toc-item"><a href="#A-simple-problem-function" data-toc-modified-id="A-simple-problem-function-51"><span class="toc-item-num">5.1 </span>A simple problem function</a></div><div class="lev2 toc-item"><a href="#A-generic-function" data-toc-modified-id="A-generic-function-52"><span class="toc-item-num">5.2 </span>A generic function</a></div><div class="lev2 toc-item"><a href="#Plotting-the-result-as-a-1D-plot" data-toc-modified-id="Plotting-the-result-as-a-1D-plot-53"><span class="toc-item-num">5.3 </span>Plotting the result as a 1D plot</a></div><div class="lev2 toc-item"><a href="#Experiments-for-Monitored" data-toc-modified-id="Experiments-for-Monitored-54"><span class="toc-item-num">5.4 </span>Experiments for <code>Monitored</code></a></div><div class="lev2 toc-item"><a href="#Experiments-for-Bernoulli-GLR" data-toc-modified-id="Experiments-for-Bernoulli-GLR-55"><span class="toc-item-num">5.5 </span>Experiments for <code>Bernoulli GLR</code></a></div><div class="lev2 toc-item"><a href="#Experiments-for-Gaussian-GLR" data-toc-modified-id="Experiments-for-Gaussian-GLR-56"><span class="toc-item-num">5.6 </span>Experiments for <code>Gaussian GLR</code></a></div><div class="lev2 toc-item"><a href="#Experiments-for-CUSUM" data-toc-modified-id="Experiments-for-CUSUM-57"><span class="toc-item-num">5.7 </span>Experiments for <code>CUSUM</code></a></div><div class="lev2 toc-item"><a href="#Experiments-for-Sub-Gaussian-GLR" data-toc-modified-id="Experiments-for-Sub-Gaussian-GLR-58"><span class="toc-item-num">5.8 </span>Experiments for <code>Sub-Gaussian GLR</code></a></div><div class="lev2 toc-item"><a href="#Other-experiments" data-toc-modified-id="Other-experiments-59"><span class="toc-item-num">5.9 </span>Other experiments</a></div><div class="lev1 toc-item"><a href="#Conclusions" data-toc-modified-id="Conclusions-6"><span class="toc-item-num">6 </span>Conclusions</a></div>
# # Requirements and helper functions
# ## Requirements
#
# This notebook requires to have [`numpy`](https://www.numpy.org/) and [`matplotlib`](https://matplotlib.org/) installed.
# One function needs a function from [`scipy.special`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.comb.html#scipy.special.comb).
# [`joblib`](https://joblib.readthedocs.io/en/latest/) is used to have parallel computations (at the end).
#
# The bottleneck performance of the main functions are very simple functions, for which we can write efficient versions using either [`numba.jit`](https://numba.pydata.org/numba-doc/latest/reference/jit-compilation.html#numba.jit) or [`cython`](https://cython.readthedocs.io/en/latest/src/quickstart/build.html#jupyter-notebook).
# In[3]:
get_ipython().system('pip3 install watermark numpy scipy matplotlib joblib numba cython')
get_ipython().run_line_magic('load_ext', 'watermark')
get_ipython().run_line_magic('watermark', '-v -m -p numpy,scipy,matplotlib,joblib,numba,cython -a "Lilian Besson and Emilie Kaufmann"')
# In[4]:
import numpy as np
# In[5]:
try:
from tqdm import tqdm_notebook as tqdm
except:
def tqdm(iterator, *args, **kwargs):
return iterator
# ## Mathematical notations for stationary problems
#
# We consider $K \geq 1$ arms, which are distributions $\nu_k$.
# We focus on Bernoulli distributions, which are characterized by their means, $\nu_k = \mathcal{B}(\mu_k)$ for $\mu_k\in[0,1]$.
# A stationary bandit problem is defined here by the vector $[\mu_1,\dots,\mu_K]$.
#
# For a fixed problem and a *horizon* $T\in\mathbb{N}$, $T\geq1$, we draw samples from the $K$ distributions to get *data*: $\forall t, r_k(t) \sim \nu_k$, ie, $\mathbb{P}(r_k(t) = 1) = \mu_k$ and $r_k(t) \in \{0,1\}$.
# ## Generating stationary data
#
# Here we give some examples of stationary problems and examples of data we can draw from them.
# In[13]:
def bernoulli_samples(means, horizon=1000):
if np.size(means) == 1:
return np.random.binomial(1, means, size=horizon)
else:
results = np.zeros((np.size(means), horizon))
for i, mean in enumerate(means):
results[i] = np.random.binomial(1, mean, size=horizon)
return results
# In[14]:
problem1 = [0.5]
bernoulli_samples(problem1, horizon=20)
# In[27]:
get_ipython().run_line_magic('timeit', 'bernoulli_samples(problem1, horizon=1000)')
# Now for Gaussian data:
# In[49]:
sigma = 0.25 # Bernoulli are 1/4-sub Gaussian too!
# In[50]:
def gaussian_samples(means, horizon=1000, sigma=sigma):
if np.size(means) == 1:
return np.random.normal(loc=means, scale=sigma, size=horizon)
else:
results = np.zeros((np.size(means), horizon))
for i, mean in enumerate(means):
results[i] = np.random.normal(loc=mean, scale=sigma, size=horizon)
return results
# In[51]:
gaussian_samples(problem1, horizon=20)
# In[52]:
get_ipython().run_line_magic('timeit', 'gaussian_samples(problem1, horizon=1000)')
# For bandit problem with $K \geq 2$ arms, the *goal* is to design an online learning algorithm that roughly do the following:
#
# - For time $t=1$ to $t=T$ (unknown horizon)
# 1. Algorithm $A$ decide to draw arm $A(t) \in\{1,\dots,K\}$,
# 2. Get the reward $r(t) = r_{A(t)}(t) \sim \nu_{A(t)}$ from the (Bernoulli) distribution of that arm,
# 3. Give this observation of reward $r(t)$ coming from arm $A(t)$ to the algorithm,
# 4. Update internal state of the algorithm
#
# An algorithm is efficient if it obtains a high (expected) sum reward, ie, $\sum_{t=1}^T r(t)$.
#
# Note that I don't focus on bandit algorithm here.
# In[9]:
problem2 = [0.1, 0.5, 0.9]
bernoulli_samples(problem2, horizon=20)
# In[10]:
problem2 = [0.1, 0.5, 0.9]
gaussian_samples(problem2, horizon=20)
# For instance on these data, the best arm is clearly the third one, with expected reward of $\mu^* = \max_k \mu_k = 0.9$.
# ## Mathematical notations for piecewise stationary problems
#
# Now we fix the horizon $T\in\mathbb{N}$, $T\geq1$ and we also consider a set of $\Upsilon_T$ *break points*, $\tau_1,\dots,\tau_{\Upsilon_T} \in\{1,\dots,T\}$. We denote $\tau_0 = 0$ and $\tau_{\Upsilon_T+1} = T$ for convenience of notations.
# We can assume that breakpoints are far "enough" from each other, for instance that there exists an integer $N\in\mathbb{N},N\geq1$ such that $\min_{i=0}^{\Upsilon_T} \tau_{i+1} - \tau_i \geq N K$. That is, on each *stationary interval*, a uniform sampling of the $K$ arms gives at least $N$ samples by arm.
#
# Now, in any stationary interval $[\tau_i + 1, \tau_{i+1}]$, the $K \geq 1$ arms are distributions $\nu_k^{(i)}$.
# We focus on Bernoulli distributions, which are characterized by their means, $\nu_k^{(i)} := \mathcal{B}(\mu_k^{(i)})$ for $\mu_k^{(i)}\in[0,1]$.
# A piecewise stationary bandit problem is defined here by the vector $[\mu_k^{(i)}]_{1\leq k \leq K, 1 \leq i \leq \Upsilon_T}$.
#
# For a fixed problem and a *horizon* $T\in\mathbb{N}$, $T\geq1$, we draw samples from the $K$ distributions to get *data*: $\forall t, r_k(t) \sim \nu_k^{(i)}$ for $i$ the unique index of stationary interval such that $t\in[\tau_i + 1, \tau_{i+1}]$.
# ## Generating fake piecewise stationary data
#
# The format to define piecewise stationary problem will be the following. It is compact but generic!
#
# The first example considers a unique arm, with 2 breakpoints uniformly spaced.
# - On the first interval, for instance from $t=1$ to $t=500$, that is $\tau_1 = 500$, $\mu_1^{(1)} = 0.1$,
# - On the second interval, for instance from $t=501$ to $t=1000$, that is $\tau_2 = 100$, $\mu_1^{(2)} = 0.5$,
# - On the third interval, for instance from $t=1001$ to $t=1500$, that $\mu_1^{(3)} = 0.9$.
# In[53]:
# With 1 arm only!
problem_piecewise_0 = lambda horizon: {
"listOfMeans": [
[0.1], # 0 to 499
[0.5], # 500 to 999
[0.8], # 1000 to 1499
],
"changePoints": [
int(0 * horizon / 1500.0),
int(500 * horizon / 1500.0),
int(1000 * horizon / 1500.0),
],
}
# In[54]:
# With 2 arms
problem_piecewise_1 = lambda horizon: {
"listOfMeans": [
[0.1, 0.2], # 0 to 399
[0.1, 0.3], # 400 to 799
[0.5, 0.3], # 800 to 1199
[0.4, 0.3], # 1200 to 1599
[0.3, 0.9], # 1600 to end
],
"changePoints": [
int(0 * horizon / 2000.0),
int(400 * horizon / 2000.0),
int(800 * horizon / 2000.0),
int(1200 * horizon / 2000.0),
int(1600 * horizon / 2000.0),
],
}
# In[55]:
# With 3 arms
problem_piecewise_2 = lambda horizon: {
"listOfMeans": [
[0.2, 0.5, 0.9], # 0 to 399
[0.2, 0.2, 0.9], # 400 to 799
[0.2, 0.2, 0.1], # 800 to 1199
[0.7, 0.2, 0.1], # 1200 to 1599
[0.7, 0.5, 0.1], # 1600 to end
],
"changePoints": [
int(0 * horizon / 2000.0),
int(400 * horizon / 2000.0),
int(800 * horizon / 2000.0),
int(1200 * horizon / 2000.0),
int(1600 * horizon / 2000.0),
],
}
# In[56]:
# With 3 arms
problem_piecewise_3 = lambda horizon: {
"listOfMeans": [
[0.4, 0.5, 0.9], # 0 to 399
[0.5, 0.4, 0.7], # 400 to 799
[0.6, 0.3, 0.5], # 800 to 1199
[0.7, 0.2, 0.3], # 1200 to 1599
[0.8, 0.1, 0.1], # 1600 to end
],
"changePoints": [
int(0 * horizon / 2000.0),
int(400 * horizon / 2000.0),
int(800 * horizon / 2000.0),
int(1200 * horizon / 2000.0),
int(1600 * horizon / 2000.0),
],
}
# Now we can write a utility function that transform this compact representation into a full list of means.
# In[57]:
def getFullHistoryOfMeans(problem, horizon=2000):
"""Return the vector of mean of the arms, for a piece-wise stationary MAB.
- It is a numpy array of shape (nbArms, horizon).
"""
pb = problem(horizon)
listOfMeans, changePoints = pb['listOfMeans'], pb['changePoints']
nbArms = len(listOfMeans[0])
if horizon is None:
horizon = np.max(changePoints)
meansOfArms = np.ones((nbArms, horizon))
for armId in range(nbArms):
nbChangePoint = 0
for t in range(horizon):
if nbChangePoint < len(changePoints) - 1 and t >= changePoints[nbChangePoint + 1]:
nbChangePoint += 1
meansOfArms[armId][t] = listOfMeans[nbChangePoint][armId]
return meansOfArms
# For examples :
# In[16]:
getFullHistoryOfMeans(problem_piecewise_0, horizon=50)
# In[17]:
getFullHistoryOfMeans(problem_piecewise_1, horizon=50)
# In[18]:
getFullHistoryOfMeans(problem_piecewise_2, horizon=50)
# In[19]:
getFullHistoryOfMeans(problem_piecewise_3, horizon=50)
# And now we need to be able to generate samples from such distributions.
# In[58]:
def piecewise_bernoulli_samples(problem, horizon=1000):
fullMeans = getFullHistoryOfMeans(problem, horizon=horizon)
nbArms, horizon = np.shape(fullMeans)
results = np.zeros((nbArms, horizon))
for i in range(nbArms):
mean_i = fullMeans[i, :]
for t in range(horizon):
mean_i_t = max(0, min(1, mean_i[t])) # crop to [0, 1] !
results[i, t] = np.random.binomial(1, mean_i_t)
return results
# In[59]:
def piecewise_gaussian_samples(problem, horizon=1000, sigma=sigma):
fullMeans = getFullHistoryOfMeans(problem, horizon=horizon)
nbArms, horizon = np.shape(fullMeans)
results = np.zeros((nbArms, horizon))
for i in range(nbArms):
mean_i = fullMeans[i, :]
for t in range(horizon):
mean_i_t = mean_i[t]
results[i, t] = np.random.normal(loc=mean_i_t, scale=sigma, size=1)
return results
# Examples:
# In[22]:
getFullHistoryOfMeans(problem_piecewise_0, horizon=100)
piecewise_bernoulli_samples(problem_piecewise_0, horizon=100)
# In[23]:
piecewise_gaussian_samples(problem_piecewise_0, horizon=100)
# We easily spot the (approximate) location of the breakpoint!
#
# Another example:
# In[24]:
piecewise_bernoulli_samples(problem_piecewise_1, horizon=100)
# In[25]:
piecewise_gaussian_samples(problem_piecewise_1, horizon=20)
# ----
# # Python implementations of some statistical tests
#
# I will implement here the following statistical tests.
# I give a link to the implementation of the correspond bandit policy in my framework [`SMPyBandits`](https://smpybandits.github.io/)
#
# - Monitored (based on a McDiarmid inequality), for Monitored-UCB or [`M-UCB`](),
# - CUSUM, for [`CUSUM-UCB`](https://smpybandits.github.io/docs/Policies.CD_UCB.html?highlight=cusum#Policies.CD_UCB.CUSUM_IndexPolicy),
# - PHT, for [`PHT-UCB`](https://smpybandits.github.io/docs/Policies.CD_UCB.html?highlight=cusum#Policies.CD_UCB.PHT_IndexPolicy),
# - Gaussian GLR, for [`GaussianGLR-UCB`](https://smpybandits.github.io/docs/Policies.CD_UCB.html?highlight=glr#Policies.CD_UCB.GaussianGLR_IndexPolicy),
# - Bernoulli GLR, for [`BernoulliGLR-UCB`](https://smpybandits.github.io/docs/Policies.CD_UCB.html?highlight=glr#Policies.CD_UCB.BernoulliGLR_IndexPolicy).
# In[60]:
class ChangePointDetector(object):
def __init__(self, **kwargs):
self._kwargs = kwargs
for key, value in kwargs.items():
setattr(self, key, value)
def __str__(self):
return f"{self.__class__.__name__}{f'({repr(self._kwargs)})' if self._kwargs else ''}"
def detect(self, all_data, t):
raise NotImplementedError
# Having classes is simply to be able to pretty print the algorithms when they have parameters:
# In[27]:
print(ChangePointDetector())
# In[28]:
print(ChangePointDetector(w=10, b=1))
# ## `Monitored`
#
# It uses a McDiarmid inequality. For a (pair) window size $w\in\mathbb{N}$ and a threshold $b\in\mathbb{R}^+$.
# At time $t$, if there is at least $w$ data in the data vector $(X_i)_i$, then let $Y$ denote the last $w$ data.
# A change is detected if
# $$ |\sum_{i=w/2+1}^{w} Y_i - \sum_{i=1}^{w/2} Y_i | > b ? $$
# In[64]:
NB_ARMS = 1
WINDOW_SIZE = 80
# In[65]:
import numba
# In[88]:
class Monitored(ChangePointDetector):
def __init__(self, window_size=WINDOW_SIZE, threshold_b=None):
super().__init__(window_size=window_size, threshold_b=threshold_b)
def __str__(self):
if self.threshold_b:
return f"Monitored($w={self.window_size:.3g}$, $b={self.threshold_b:.3g}$)"
else:
latexname = r"\sqrt{\frac{w}{2} \log(2 T^2)}"
return f"Monitored($w={self.window_size:.3g}$, $b={latexname}$)"
def detect(self, all_data, t):
r""" A change is detected for the current arm if the following test is true:
.. math:: |\sum_{i=w/2+1}^{w} Y_i - \sum_{i=1}^{w/2} Y_i | > b ?
- where :math:`Y_i` is the i-th data in the latest w data from this arm (ie, :math:`X_k(t)` for :math:`t = n_k - w + 1` to :math:`t = n_k` current number of samples from arm k).
- where :attr:`threshold_b` is the threshold b of the test, and :attr:`window_size` is the window-size w.
"""
data = all_data[:t]
# don't try to detect change if there is not enough data!
if len(data) < self.window_size:
return False
# compute parameters
horizon = len(all_data)
threshold_b = self.threshold_b
if threshold_b is None:
threshold_b = np.sqrt(self.window_size/2 * np.log(2 * NB_ARMS * horizon**2))
last_w_data = data[-self.window_size:]
sum_first_half = np.sum(last_w_data[:self.window_size//2])
sum_second_half = np.sum(last_w_data[self.window_size//2:])
return abs(sum_first_half - sum_second_half) > threshold_b
# ## `CUSUM`
#
# The two-sided CUSUM algorithm, from [Page, 1954], works like this:
#
# - For each *data* k, compute:
#
# $$
# s_k^- = (y_k - \hat{u}_0 - \varepsilon) 1(k > M),\\
# s_k^+ = (\hat{u}_0 - y_k - \varepsilon) 1(k > M),\\
# g_k^+ = \max(0, g_{k-1}^+ + s_k^+),\\
# g_k^- = \max(0, g_{k-1}^- + s_k^-).
# $$
#
# - The change is detected if $\max(g_k^+, g_k^-) > h$, where $h=$`threshold_h` is the threshold of the test,
# - And $\hat{u}_0 = \frac{1}{M} \sum_{k=1}^{M} y_k$ is the mean of the first M samples, where M is `M` the min number of observation between change points.
# In[67]:
#: Precision of the test.
EPSILON = 0.5
#: Default value of :math:`\lambda`.
LAMBDA = 1
#: Hypothesis on the speed of changes: between two change points, there is at least :math:`M * K` time steps, where K is the number of arms, and M is this constant.
MIN_NUMBER_OF_OBSERVATION_BETWEEN_CHANGE_POINT = 50
MAX_NB_RANDOM_EVENTS = 1
# In[68]:
from scipy.special import comb
# In[89]:
def compute_h__CUSUM(horizon,
verbose=False,
M=MIN_NUMBER_OF_OBSERVATION_BETWEEN_CHANGE_POINT,
max_nb_random_events=MAX_NB_RANDOM_EVENTS,
nbArms=1,
epsilon=EPSILON,
lmbda=LAMBDA,
):
r""" Compute the values :math:`C_1^+, C_1^-, C_1, C_2, h` from the formulas in Theorem 2 and Corollary 2 in the paper."""
T = int(max(1, horizon))
UpsilonT = int(max(1, max_nb_random_events))
K = int(max(1, nbArms))
C1_minus = np.log(((4 * epsilon) / (1-epsilon)**2) * comb(M, int(np.floor(2 * epsilon * M))) * (2 * epsilon)**M + 1)
C1_plus = np.log(((4 * epsilon) / (1+epsilon)**2) * comb(M, int(np.ceil(2 * epsilon * M))) * (2 * epsilon)**M + 1)
C1 = min(C1_minus, C1_plus)
if C1 == 0: C1 = 1 # FIXME
h = 1/C1 * np.log(T / UpsilonT)
return h
# In[151]:
class CUSUM(ChangePointDetector):
def __init__(self,
epsilon=EPSILON,
M=MIN_NUMBER_OF_OBSERVATION_BETWEEN_CHANGE_POINT,
threshold_h=None,
):
assert 0 < epsilon < 1, f"Error: epsilon for CUSUM must be in (0, 1) but is {epsilon}."
super().__init__(epsilon=epsilon, M=M, threshold_h=threshold_h)
def __str__(self):
if self.threshold_h:
return fr"CUSUM($\varepsilon={self.epsilon:.3g}$, $M={self.M}$, $h={self.threshold_h:.3g}$)"
else:
return fr"CUSUM($\varepsilon={self.epsilon:.3g}$, $M={self.M}$, $h=$'auto')"
def detect(self, all_data, t):
r""" Detect a change in the current arm, using the two-sided CUSUM algorithm [Page, 1954].
- For each *data* k, compute:
.. math::
s_k^- &= (y_k - \hat{u}_0 - \varepsilon) 1(k > M),\\
s_k^+ &= (\hat{u}_0 - y_k - \varepsilon) 1(k > M),\\
g_k^+ &= \max(0, g_{k-1}^+ + s_k^+),\\
g_k^- &= \max(0, g_{k-1}^- + s_k^-).
- The change is detected if :math:`\max(g_k^+, g_k^-) > h`, where :attr:`threshold_h` is the threshold of the test,
- And :math:`\hat{u}_0 = \frac{1}{M} \sum_{k=1}^{M} y_k` is the mean of the first M samples, where M is :attr:`M` the min number of observation between change points.
"""
data = all_data[:t]
# compute parameters
horizon = len(all_data)
threshold_h = self.threshold_h
if self.threshold_h is None:
threshold_h = compute_h__CUSUM(horizon, self.M, 1, epsilon=self.epsilon)
gp, gm = 0, 0
# First we use the first M samples to calculate the average :math:`\hat{u_0}`.
u0hat = np.mean(data[:self.M])
for k in range(self.M + 1, len(data)):
y_k = data[k]
sp = u0hat - y_k - self.epsilon # no need to multiply by (k > self.M)
sm = y_k - u0hat - self.epsilon # no need to multiply by (k > self.M)
gp = max(0, gp + sp)
gm = max(0, gm + sm)
if max(gp, gm) >= threshold_h:
return True
return False
# ## `PHT`
#
# The two-sided CUSUM algorithm, from [Hinkley, 1971], works like this:
#
# - For each *data* k, compute:
#
# $$
# s_k^- = y_k - \hat{y}_k - \varepsilon,\\
# s_k^+ = \hat{y}_k - y_k - \varepsilon,\\
# g_k^+ = \max(0, g_{k-1}^+ + s_k^+),\\
# g_k^- = \max(0, g_{k-1}^- + s_k^-).
# $$
#
# - The change is detected if $\max(g_k^+, g_k^-) > h$, where $h=$`threshold_h` is the threshold of the test,
# - And $\hat{y}_k = \frac{1}{k} \sum_{s=1}^{k} y_s$ is the mean of the first k samples.
# In[152]:
class PHT(ChangePointDetector):
def __init__(self,
epsilon=EPSILON,
M=MIN_NUMBER_OF_OBSERVATION_BETWEEN_CHANGE_POINT,
threshold_h=None,
):
assert 0 < epsilon < 1, f"Error: epsilon for CUSUM must be in (0, 1) but is {epsilon}."
super().__init__(epsilon=epsilon, M=M, threshold_h=threshold_h)
def __str__(self):
if self.threshold_h:
return fr"PHT($\varepsilon={self.epsilon:.3g}$, $M={self.M}$, $h={self.threshold_h:.3g}$)"
else:
return fr"PHT($\varepsilon={self.epsilon:.3g}$, $M={self.M}$, $h=$'auto')"
def detect(self, all_data, t):
r""" Detect a change in the current arm, using the two-sided PHT algorithm [Hinkley, 1971].
- For each *data* k, compute:
.. math::
s_k^- &= y_k - \hat{y}_k - \varepsilon,\\
s_k^+ &= \hat{y}_k - y_k - \varepsilon,\\
g_k^+ &= \max(0, g_{k-1}^+ + s_k^+),\\
g_k^- &= \max(0, g_{k-1}^- + s_k^-).
- The change is detected if :math:`\max(g_k^+, g_k^-) > h`, where :attr:`threshold_h` is the threshold of the test,
- And :math:`\hat{y}_k = \frac{1}{k} \sum_{s=1}^{k} y_s` is the mean of the first k samples.
"""
data = all_data[:t]
# compute parameters
horizon = len(all_data)
threshold_h = self.threshold_h
if threshold_h is None:
threshold_h = compute_h__CUSUM(horizon, self.M, 1, epsilon=self.epsilon)
gp, gm = 0, 0
y_k_hat = 0
# First we use the first M samples to calculate the average :math:`\hat{u_0}`.
for k, y_k in enumerate(data):
y_k_hat = (k * y_k_hat + y_k) / (k + 1) # XXX smart formula to update the mean!
sp = y_k_hat - y_k - self.epsilon
sm = y_k - y_k_hat - self.epsilon
gp = max(0, gp + sp)
gm = max(0, gm + sm)
if max(gp, gm) >= threshold_h:
return True
return False
# ---
# ## `Gaussian GLR`
#
# The Generalized Likelihood Ratio test (GLR) works with a one-dimensional exponential family, for which we have a function `kl` such that if $\mu_1,\mu_2$ are the means of two distributions $\nu_1,\nu_2$, then $\mathrm{KL}(\mathcal{D}(\nu_1), \mathcal{D}(\nu_1))=$ `kl` $(\mu_1,\mu_2)$.
#
# - For each *time step* $s$ between $t_0=0$ and $t$, compute:
# $$G^{\mathcal{N}_1}_{t_0:s:t} = (s-t_0+1) \mathrm{kl}(\mu_{t_0,s}, \mu_{t_0,t}) + (t-s) \mathrm{kl}(\mu_{s+1,t}, \mu_{t_0,t}).$$
#
# - The change is detected if there is a time $s$ such that $G^{\mathcal{N}_1}_{t_0:s:t} > b(t_0, s, t, \delta)$, where $b(t_0, s, t, \delta)=$ `threshold_h` is the threshold of the test,
# - And $\mu_{a,b} = \frac{1}{b-a+1} \sum_{s=a}^{b} y_s$ is the mean of the samples between $a$ and $b$.
#
# The threshold is computed as:
# $$ b(t_0, s, t, \delta):= \left(1 + \frac{1}{t - t_0 + 1}\right) 2 \log\left(\frac{2 (t - t_0) \sqrt{(t - t_0) + 2}}{\delta}\right).$$
#
# Another threshold we want to check is the following:
# $$ b(t_0, s, t, \delta):= \log\left(\frac{(s - t_0 + 1) (t - s)}{\delta}\right).$$
# In[124]:
from math import log, isinf
def compute_c__GLR_0(t0, s, t, horizon=None, delta=None):
r""" Compute the values :math:`c` from the corollary of of Theorem 2 from ["Sequential change-point detection: Laplace concentration of scan statistics and non-asymptotic delay bounds", O.-A. Maillard, 2018].
- The threshold is computed as:
.. math:: h := \left(1 + \frac{1}{t - t_0 + 1}\right) 2 \log\left(\frac{2 (t - t_0) \sqrt{(t - t_0) + 2}}{\delta}\right).
"""
if delta is None:
T = int(max(1, horizon))
delta = 1.0 / T
t_m_t0 = abs(t - t0)
c = (1 + (1 / (t_m_t0 + 1.0))) * 2 * log((2 * t_m_t0 * np.sqrt(t_m_t0 + 2)) / delta)
if c < 0 and isinf(c): c = float('+inf')
return c
# In[125]:
from math import log, isinf
def compute_c__GLR(t0, s, t, horizon=None, delta=None):
r""" Compute the values :math:`c` from the corollary of of Theorem 2 from ["Sequential change-point detection: Laplace concentration of scan statistics and non-asymptotic delay bounds", O.-A. Maillard, 2018].
- The threshold is computed as:
.. math:: h := \log\left(\frac{(s - t_0 + 1) (t - s)}{\delta}\right).
"""
if delta is None:
T = int(max(1, horizon))
delta = 1.0 / T
arg = (s - t0 + 1) * (t - s) / delta
if arg <= 0: c = float('+inf')
else: c = log(arg)
return c
# For Gaussian distributions of known variance, the Kullback-Leibler divergence is easy to compute:
#
# Kullback-Leibler divergence for Gaussian distributions of means $x$ and $y$ and variances $\sigma^2_x = \sigma^2_y$, $\nu_1 = \mathcal{N}(x, \sigma_x^2)$ and $\nu_2 = \mathcal{N}(y, \sigma_x^2)$ is:
#
# $$\mathrm{KL}(\nu_1, \nu_2) = \frac{(x - y)^2}{2 \sigma_y^2} + \frac{1}{2}\left( \frac{\sigma_x^2}{\sigma_y^2} - 1 \log\left(\frac{\sigma_x^2}{\sigma_y^2}\right) \right).$$
# In[126]:
def klGauss(x, y, sig2x=0.25):
r""" Kullback-Leibler divergence for Gaussian distributions of means ``x`` and ``y`` and variances ``sig2x`` and ``sig2y``, :math:`\nu_1 = \mathcal{N}(x, \sigma_x^2)` and :math:`\nu_2 = \mathcal{N}(y, \sigma_x^2)`:
.. math:: \mathrm{KL}(\nu_1, \nu_2) = \frac{(x - y)^2}{2 \sigma_y^2} + \frac{1}{2}\left( \frac{\sigma_x^2}{\sigma_y^2} - 1 \log\left(\frac{\sigma_x^2}{\sigma_y^2}\right) \right).
See https://en.wikipedia.org/wiki/Normal_distribution#Other_properties
- sig2y = sig2x (same variance).
"""
return (x - y) ** 2 / (2. * sig2x)
# In[127]:
class GaussianGLR(ChangePointDetector):
def __init__(self, mult_threshold_h=1, delta=None):
super().__init__(mult_threshold_h=mult_threshold_h, delta=delta)
def __str__(self):
return r"Gaussian-GLR($h_0={}$, $\delta={}$)".format(
f"{self.mult_threshold_h:.3g}" if self.mult_threshold_h is not None else 'auto',
f"{self.delta:.3g}" if self.delta is not None else 'auto',
)
def detect(self, all_data, t):
r""" Detect a change in the current arm, using the Generalized Likelihood Ratio test (GLR) and the :attr:`kl` function.
- For each *time step* :math:`s` between :math:`t_0=0` and :math:`t`, compute:
.. math::
G^{\mathcal{N}_1}_{t_0:s:t} = (s-t_0+1)(t-s) \mathrm{kl}(\mu_{s+1,t}, \mu_{t_0,s}) / (t-t_0+1).
- The change is detected if there is a time :math:`s` such that :math:`G^{\mathcal{N}_1}_{t_0:s:t} > h`, where :attr:`threshold_h` is the threshold of the test,
- And :math:`\mu_{a,b} = \frac{1}{b-a+1} \sum_{s=a}^{b} y_s` is the mean of the samples between :math:`a` and :math:`b`.
"""
data = all_data[:t]
t0 = 0
horizon = len(all_data)
# compute parameters
mean_all = np.mean(data[t0 : t+1])
mean_before = 0
mean_after = mean_all
for s in range(t0, t):
# DONE okay this is efficient we don't compute the same means too many times!
y = data[s]
mean_before = (s * mean_before + y) / (s + 1)
mean_after = ((t + 1 - s + t0) * mean_after - y) / (t - s + t0)
kl_before = klGauss(mean_before, mean_all)
kl_after = klGauss(mean_after, mean_all)
threshold_h = self.mult_threshold_h * compute_c__GLR(t0, s, t, horizon=horizon, delta=self.delta)
glr = (s - t0 + 1) * kl_before + (t - s) * kl_after
if glr >= threshold_h:
return True
return False
# ## `Bernoulli GLR`
#
# The same GLR algorithm but using the Bernoulli KL, given by:
#
# $$\mathrm{KL}(\mathcal{B}(x), \mathcal{B}(y)) = x \log(\frac{x}{y}) + (1-x) \log(\frac{1-x}{1-y}).$$
# In[257]:
import cython
get_ipython().run_line_magic('load_ext', 'cython')
# In[265]:
def klBern(x: float, y: float) -> float:
r""" Kullback-Leibler divergence for Bernoulli distributions. https://en.wikipedia.org/wiki/Bernoulli_distribution#Kullback.E2.80.93Leibler_divergence
.. math:: \mathrm{KL}(\mathcal{B}(x), \mathcal{B}(y)) = x \log(\frac{x}{y}) + (1-x) \log(\frac{1-x}{1-y})."""
x = min(max(x, 1e-6), 1 - 1e-6)
y = min(max(y, 1e-6), 1 - 1e-6)
return x * log(x / y) + (1 - x) * log((1 - x) / (1 - y))
# In[259]:
get_ipython().run_line_magic('timeit', 'klBern(np.random.random(), np.random.random())')
# In[260]:
get_ipython().run_cell_magic('cython', '--annotate', 'from libc.math cimport log\neps = 1e-6 #: Threshold value: everything in [0, 1] is truncated to [eps, 1 - eps]\n\ndef klBern_cython(float x, float y) -> float:\n r""" Kullback-Leibler divergence for Bernoulli distributions. https://en.wikipedia.org/wiki/Bernoulli_distribution#Kullback.E2.80.93Leibler_divergence\n\n .. math:: \\mathrm{KL}(\\mathcal{B}(x), \\mathcal{B}(y)) = x \\log(\\frac{x}{y}) + (1-x) \\log(\\frac{1-x}{1-y})."""\n x = min(max(x, 1e-6), 1 - 1e-6)\n y = min(max(y, 1e-6), 1 - 1e-6)\n return x * log(x / y) + (1 - x) * log((1 - x) / (1 - y))')
# In[261]:
get_ipython().run_line_magic('timeit', 'klBern_cython(np.random.random(), np.random.random())')
# Now the class, with this optimized kl function.
# In[262]:
class BernoulliGLR(ChangePointDetector):
def __init__(self, mult_threshold_h=1, delta=None):
super().__init__(mult_threshold_h=mult_threshold_h, delta=delta)
def __str__(self):
return r"Bernoulli-GLR($h_0={}$, $\delta={}$)".format(
f"{self.mult_threshold_h:.3g}" if self.mult_threshold_h is not None else 'auto',
f"{self.delta:.3g}" if self.delta is not None else 'auto',
)
def detect(self, all_data, t):
r""" Detect a change in the current arm, using the Generalized Likelihood Ratio test (GLR) and the :attr:`kl` function.
- For each *time step* :math:`s` between :math:`t_0=0` and :math:`t`, compute:
.. math::
G^{\mathcal{N}_1}_{t_0:s:t} = (s-t_0+1)(t-s) \mathrm{kl}(\mu_{s+1,t}, \mu_{t_0,s}) / (t-t_0+1).
- The change is detected if there is a time :math:`s` such that :math:`G^{\mathcal{N}_1}_{t_0:s:t} > h`, where :attr:`threshold_h` is the threshold of the test,
- And :math:`\mu_{a,b} = \frac{1}{b-a+1} \sum_{s=a}^{b} y_s` is the mean of the samples between :math:`a` and :math:`b`.
"""
data = all_data[:t]
t0 = 0
horizon = len(all_data)
# compute parameters
mean_all = np.mean(data[t0 : t+1])
mean_before = 0
mean_after = mean_all
for s in range(t0, t):
# DONE okay this is efficient we don't compute the same means too many times!
y = data[s]
mean_before = (s * mean_before + y) / (s + 1)
mean_after = ((t + 1 - s + t0) * mean_after - y) / (t - s + t0)
kl_before = klBern(mean_before, mean_all)
kl_after = klBern(mean_after, mean_all)
threshold_h = self.mult_threshold_h * compute_c__GLR(t0, s, t, horizon=horizon, delta=self.delta)
glr = (s - t0 + 1) * kl_before + (t - s) * kl_after
if glr >= threshold_h:
return True
return False
# ## `Sub-Gaussian GLR`
#
# A slightly different GLR algorithm for non-parametric sub-Gaussian distributions.
# We assume the distributions $\nu^1$ and $\nu^2$ to be $\sigma^2$-sub Gaussian, for a known value of $\sigma\in\mathbb{R}^+$, and if we consider a confidence level $\delta\in(0,1)$ (typically, it is set to $\frac{1}{T}$ if the horizon $T$ is known, or $\delta=\delta_t=\frac{1}{t^2}$ to have $\sum_{t=1}{T} \delta_t < +\infty$).
#
# Then we consider the following test: the non-parametric sub-Gaussian Generalized Likelihood Ratio test (GLR) works like this:
#
# - For each *time step* $s$ between $t_0=0$ and $t$, compute:
# $$G^{\text{sub-}\sigma}_{t_0:s:t} = |\mu_{t_0,s} - \mu_{s+1,t}|.$$
#
# - The change is detected if there is a time $s$ such that $G^{\text{sub-}\sigma}_{t_0:s:t} > b_{t_0}(s,t,\delta)$, where $b_{t_0}(s,t,\delta)$ is the threshold of the test,
# - And $\mu_{a,b} = \frac{1}{b-a+1} \sum_{s=a}^{b} y_s$ is the mean of the samples between $a$ and $b$.
#
# The threshold is computed as either the "joint" variant:
# $$b^{\text{joint}}_{t_0}(s,t,\delta) := \sigma \sqrt{ \left(\frac{1}{s-t_0+1} + \frac{1}{t-s}\right) \left(1 + \frac{1}{t-t_0+1}\right) 2 \log\left( \frac{2(t-t_0)\sqrt{t-t_0+2}}{\delta} \right)}.$$
# or the "disjoint" variant:
#
# $$b^{\text{disjoint}}_{t_0}(s,t,\delta) := \sqrt{2} \sigma \sqrt{
# \frac{1 + \frac{1}{s - t_0 + 1}}{s - t_0 + 1} \log\left( \frac{4 \sqrt{s - t_0 + 2}}{\delta}\right)
# } + \sqrt{
# \frac{1 + \frac{1}{t - s + 1}}{t - s + 1} \log\left( \frac{4 (t - t_0) \sqrt{t - s + 1}}{\delta}\right)
# }.$$
#
# In[129]:
# Default confidence level?
DELTA = 0.01
# By default, assume distributions are 0.25-sub Gaussian, like Bernoulli
# or any distributions with support on [0,1]
SIGMA = 0.25
# In[130]:
# Whether to use the joint or disjoint threshold function
JOINT = True
# In[159]:
from math import log, sqrt
def threshold_SubGaussianGLR_joint(t0, s, t, delta=DELTA, sigma=SIGMA):
return sigma * sqrt(
(1.0 / (s - t0 + 1) + 1.0/(t - s)) * (1.0 + 1.0/(t - t0+1))
* 2 * max(0, log(( 2 * (t - t0) * sqrt(t - t0 + 2)) / delta ))
)
# In[160]:
from math import log, sqrt
def threshold_SubGaussianGLR_disjoint(t0, s, t, delta=DELTA, sigma=SIGMA):
return np.sqrt(2) * sigma * (sqrt(
((1.0 + (1.0 / (s - t0 + 1))) / (s - t0 + 1)) * max(0, log( (4 * sqrt(s - t0 + 2)) / delta ))
) + sqrt(
((1.0 + (1.0 / (t - s + 1))) / (t - s + 1)) * max(0, log( (4 * (t - t0) * sqrt(t - s + 1)) / delta ))
))
# In[161]:
def threshold_SubGaussianGLR(t0, s, t, delta=DELTA, sigma=SIGMA, joint=JOINT):
if joint:
return threshold_SubGaussianGLR_joint(t0, s, t, delta, sigma=sigma)
else:
return threshold_SubGaussianGLR_disjoint(t0, s, t, delta, sigma=sigma)
# And now we can write the CD algorithm:
# In[162]:
class SubGaussianGLR(ChangePointDetector):
def __init__(self, delta=DELTA, sigma=SIGMA, joint=JOINT):
super().__init__(delta=delta, sigma=sigma, joint=joint)
def __str__(self):
return fr"SubGaussian-GLR($\delta=${self.delta:.3g}, $\sigma=${self.sigma:.3g}, {'joint' if self.joint else 'disjoint'})"
def detect(self, all_data, t):
r""" Detect a change in the current arm, using the non-parametric sub-Gaussian Generalized Likelihood Ratio test (GLR) works like this:
- For each *time step* :math:`s` between :math:`t_0=0` and :math:`t`, compute:
.. math:: G^{\text{sub-}\sigma}_{t_0:s:t} = |\mu_{t_0,s} - \mu_{s+1,t}|.
- The change is detected if there is a time :math:`s` such that :math:`G^{\text{sub-}\sigma}_{t_0:s:t} > b_{t_0}(s,t,\delta)`, where :math:`b_{t_0}(s,t,\delta)` is the threshold of the test,
The threshold is computed as:
.. math:: b_{t_0}(s,t,\delta) := \sigma \sqrt{ \left(\frac{1}{s-t_0+1} + \frac{1}{t-s}\right) \left(1 + \frac{1}{t-t_0+1}\right) 2 \log\left( \frac{2(t-t_0)\sqrt{t-t_0+2}}{\delta} \right)}.
- And :math:`\mu_{a,b} = \frac{1}{b-a+1} \sum_{s=a}^{b} y_s` is the mean of the samples between :math:`a` and :math:`b`.
"""
data = all_data[:t]
t0 = 0
horizon = len(all_data)
delta = self.delta
if delta is None:
delta = 1.0 / max(1, horizon)
mean_before = 0
mean_after = np.mean(data[t0 : t+1])
for s in range(t0, t):
# DONE okay this is efficient we don't compute the same means too many times!
y = data[s]
mean_before = (s * mean_before + y) / (s + 1)
mean_after = ((t + 1 - s + t0) * mean_after - y) / (t - s + t0)
# compute threshold
threshold = threshold_SubGaussianGLR(t0, s, t, delta=delta, sigma=self.sigma, joint=self.joint)
glr = abs(mean_before - mean_after)
if glr >= threshold:
# print(f"DEBUG: t0 = {t0}, t = {t}, s = {s}, horizon = {horizon}, delta = {delta}, threshold = {threshold} and mu(s+1, t) = {mu(s+1, t)}, and mu(t0, s) = {mu(t0, s)}, and and glr = {glr}.")
return True
return False
# ## List of all Python algorithms
# In[135]: