-
Notifications
You must be signed in to change notification settings - Fork 88
/
estimators_multi.py
1806 lines (1478 loc) · 76.4 KB
/
estimators_multi.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
# Copyright (c) Yuta Saito, Yusuke Narita, and ZOZO Technologies, Inc. All rights reserved.
# Licensed under the Apache 2.0 License.
"""Off-Policy Estimators."""
from abc import ABCMeta
from abc import abstractmethod
from dataclasses import dataclass
from typing import Dict
from typing import Optional
import numpy as np
from sklearn.utils import check_scalar
from ..utils import check_array
from ..utils import check_multi_loggers_ope_inputs
from ..utils import estimate_confidence_interval_by_bootstrap
@dataclass
class BaseMultiLoggersOffPolicyEstimator(metaclass=ABCMeta):
"""Base class for OPE estimators for multiple loggers."""
@abstractmethod
def _estimate_round_rewards(self) -> np.ndarray:
"""Estimate round-wise (or sample-wise) rewards."""
raise NotImplementedError
@abstractmethod
def estimate_policy_value(self) -> float:
"""Estimate the policy value of evaluation policy."""
raise NotImplementedError
@abstractmethod
def estimate_interval(self) -> Dict[str, float]:
"""Estimate the confidence interval of the policy value using bootstrap."""
raise NotImplementedError
@dataclass
class MultiLoggersNaiveInverseProbabilityWeighting(BaseMultiLoggersOffPolicyEstimator):
"""Multi-Loggers Inverse Probability Weighting (Multi-IPW) Estimator.
Note
-------
This estimator is called Naive IPS in Agarwal et al.(2018) and Averaged IS in Kallus et al.(2021).
Multi-IPW estimates the policy value of evaluation policy :math:`\\pi_e`
using logged data collected by multiple logging/behavior policies as
.. math::
\\hat{V}_{\\mathrm{Multi-IPW}} (\\pi_e; \\mathcal{D}) := \\mathbb{E}_{n} [ w_{k_i}(x_i,a_i) r_i],
where :math:`\\mathcal{D}_k=\\{(x_i,a_i,r_i)\\}_{i=1}^{n_k}` is logged bandit data with :math:`n_k` observations collected by
the k-th behavior policy :math:`\\pi_k`. :math:`w_k(x,a):=\\pi_e (a|x)/\\pi_k (a|x)` is the importance weight given :math:`x` and :math:`a` computed for the k-th behavior policy.
We can represent the whole logged bandit data as :math:`\\mathcal{D}=\\{(k_i,x_i,a_i,r_i)\\}_{i=1}^{n}` where :math:`k_i` is the index to indicate the logging/behavior policy that generates i-th data, i.e., :math:`\\pi_{k_i}`.
Note that :math:`n := \\sum_{k=1}^K` is the total number of logged bandit data.
:math:`\\mathbb{E}_{n}[\\cdot]` is the empirical average over :math:`n` observations in :math:`\\mathcal{D}`.
When the clipping is applied, a large importance weight is clipped as :math:`\\hat{w}_k(x,a) := \\min \\{ \\lambda, w_k(x,a) \\}`, where :math:`\\lambda (>0)` is a hyperparameter to specify a maximum allowed importance weight.
Multi-IPW applies the standard IPW to each stratum and takes the weighted average of the K datasets.
Parameters
------------
lambda_: float, default=np.inf
A maximum possible value of the importance weight.
When a positive finite value is given, importance weights larger than `lambda_` will be clipped.
use_estimated_pscore: bool, default=False.
If True, `estimated_pscore` is used, otherwise, `pscore` (the true propensity scores) is used.
estimator_name: str, default='multi_ipw'.
Name of the estimator.
References
------------
Aman Agarwal, Soumya Basu, Tobias Schnabel, and Thorsten Joachims.
"Effective Evaluation using Logged Bandit Feedback from Multiple Loggers.", 2018.
Nathan Kallus, Yuta Saito, and Masatoshi Uehara.
"Optimal Off-Policy Evaluation from Multiple Logging Policies.", 2021.
"""
lambda_: float = np.inf
use_estimated_pscore: bool = False
estimator_name: str = "multi_ipw"
def __post_init__(self) -> None:
"""Initialize Class."""
check_scalar(
self.lambda_,
name="lambda_",
target_type=(int, float),
min_val=0.0,
)
if self.lambda_ != self.lambda_:
raise ValueError("`lambda_` must not be nan")
if not isinstance(self.use_estimated_pscore, bool):
raise TypeError(
f"`use_estimated_pscore` must be a bool, but {type(self.use_estimated_pscore)} is given"
)
def _estimate_round_rewards(
self,
reward: np.ndarray,
action: np.ndarray,
pscore: np.ndarray,
action_dist: np.ndarray,
position: Optional[np.ndarray] = None,
**kwargs,
) -> np.ndarray:
"""Estimate round-wise (or sample-wise) rewards.
Parameters
----------
reward: array-like, shape (n_rounds,)
Rewards observed for each data in logged bandit data, i.e., :math:`r_i`.
action: array-like, shape (n_rounds,)
Actions sampled by the logging/behavior policy for each data in logged bandit data, i.e., :math:`a_i`.
pscore: array-like, shape (n_rounds,)
Action choice probabilities of the logging/behavior policy (propensity scores), i.e., :math:`\\pi_k(a_i|x_i)`.
If `use_estimated_pscore` is False, `pscore` must be given.
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.
position: array-like, shape (n_rounds,), default=None
Indices to differentiate positions in a recommendation interface where the actions are presented.
If None, the effect of position on the reward will be ignored.
(If only a single action is chosen for each data, you can just ignore this argument.)
Returns
----------
estimated_rewards: array-like, shape (n_rounds,)
Estimated rewards for each observation.
"""
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
iw = action_dist[np.arange(action.shape[0]), action, position] / pscore
# weight clipping
if isinstance(iw, np.ndarray):
iw = np.minimum(iw, self.lambda_)
return reward * iw
def estimate_policy_value(
self,
reward: np.ndarray,
action: np.ndarray,
action_dist: np.ndarray,
pscore: Optional[np.ndarray] = None,
position: Optional[np.ndarray] = None,
estimated_pscore: Optional[np.ndarray] = None,
**kwargs,
) -> np.ndarray:
"""Estimate the policy value of evaluation policy.
Parameters
----------
reward: array-like, shape (n_rounds,)
Rewards observed for each data in logged bandit data, i.e., :math:`r_i`.
action: array-like, shape (n_rounds,)
Actions sampled by the logging/behavior policy for each data in logged bandit data, i.e., :math:`a_i`.
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.
pscore: array-like, shape (n_rounds,), default=None
Action choice probabilities of the logging/behavior policy (propensity scores), i.e., :math:`\\pi_k(a_i|x_i)`.
If `use_estimated_pscore` is False, `pscore` must be given.
position: array-like, shape (n_rounds,), default=None
Indices to differentiate positions in a recommendation interface where the actions are presented.
If None, the effect of position on the reward will be ignored.
(If only a single action is chosen for each data, you can just ignore this argument.)
estimated_pscore: array-like, shape (n_rounds,), default=None
Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_k(a_i|x_i)`.
If `self.use_estimated_pscore` is True, `estimated_pscore` must be given.
Returns
----------
V_hat: float
Estimated policy value of evaluation policy.
"""
check_array(array=reward, name="reward", expected_dim=1)
check_array(array=action, name="action", expected_dim=1)
if self.use_estimated_pscore:
check_array(array=estimated_pscore, name="estimated_pscore", expected_dim=1)
pscore_ = estimated_pscore
else:
check_array(array=pscore, name="pscore", expected_dim=1)
pscore_ = pscore
check_multi_loggers_ope_inputs(
action_dist=action_dist,
position=position,
action=action,
reward=reward,
pscore=pscore_,
)
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
return self._estimate_round_rewards(
reward=reward,
action=action,
position=position,
pscore=pscore_,
action_dist=action_dist,
).mean()
def estimate_interval(
self,
reward: np.ndarray,
action: np.ndarray,
action_dist: np.ndarray,
pscore: Optional[np.ndarray] = None,
position: Optional[np.ndarray] = None,
estimated_pscore: Optional[np.ndarray] = None,
alpha: float = 0.05,
n_bootstrap_samples: int = 10000,
random_state: Optional[int] = None,
**kwargs,
) -> Dict[str, float]:
"""Estimate the confidence interval of the policy value using bootstrap.
Parameters
----------
reward: array-like, shape (n_rounds,)
Rewards observed for each data in logged bandit data, i.e., :math:`r_i`.
action: array-like, shape (n_rounds,)
Actions sampled by the logging/behavior policy for each data in logged bandit data, i.e., :math:`a_i`.
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.
pscore: array-like, shape (n_rounds,), default=None
Action choice probabilities of the logging/behavior policy (propensity scores), i.e., :math:`\\pi_k(a_i|x_i)`.
If `use_estimated_pscore` is False, `pscore` must be given.
position: array-like, shape (n_rounds,), default=None
Indices to differentiate positions in a recommendation interface where the actions are presented.
If None, the effect of position on the reward will be ignored.
(If only a single action is chosen for each data, you can just ignore this argument.)
estimated_pscore: array-like, shape (n_rounds,), default=None
Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_b(a_i|x_i)`.
If `self.use_estimated_pscore` is True, `estimated_pscore` must be given.
alpha: float, default=0.05
Significance level.
n_bootstrap_samples: int, default=10000
Number of resampling performed in bootstrap sampling.
random_state: int, default=None
Controls the random seed in bootstrap sampling.
Returns
----------
estimated_confidence_interval: Dict[str, float]
Dictionary storing the estimated mean and upper-lower confidence bounds.
"""
check_array(array=reward, name="reward", expected_dim=1)
check_array(array=action, name="action", expected_dim=1)
if self.use_estimated_pscore:
check_array(array=estimated_pscore, name="estimated_pscore", expected_dim=1)
pscore_ = estimated_pscore
else:
check_array(array=pscore, name="pscore", expected_dim=1)
pscore_ = pscore
check_multi_loggers_ope_inputs(
action_dist=action_dist,
position=position,
action=action,
reward=reward,
pscore=pscore_,
)
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
estimated_round_rewards = self._estimate_round_rewards(
reward=reward,
action=action,
position=position,
pscore=pscore_,
action_dist=action_dist,
)
return estimate_confidence_interval_by_bootstrap(
samples=estimated_round_rewards,
alpha=alpha,
n_bootstrap_samples=n_bootstrap_samples,
random_state=random_state,
)
@dataclass
class MultiLoggersBalancedInverseProbabilityWeighting(
BaseMultiLoggersOffPolicyEstimator
):
"""Multi-Loggers Balanced Inverse Probability Weighting (Multi-Bal-IPW) Estimator.
Note
-------
This estimator is called Balanced IPS in Agarwal et al.(2018) and Standard IS in Kallus et al.(2021).
Note that this estimator is different from `obp.ope.BalancedInverseProbabilityWeighting`, which is for the standard OPE setting.
Multi-Bal-IPW estimates the policy value of evaluation policy :math:`\\pi_e`
using logged data collected by multiple logging/behavior policies as
.. math::
\\hat{V}_{\\mathrm{Multi-Bal-IPW}} (\\pi_e; \\mathcal{D}) := \\mathbb{E}_{n} [ w_{avg}(x_i,a_i) r_i],
where :math:`\\mathcal{D}_k=\\{(x_i,a_i,r_i)\\}_{i=1}^{n_k}` is logged bandit data with :math:`n_k` observations collected by
the k-th behavior policy :math:`\\pi_k`.
:math:`w_{avg}(x,a):=\\pi_e (a|x)/\\pi_{avg} (a|x)` is the importance weight given :math:`x` and :math:`a` computed for the *average* behavior policy, which is defined as :math:`\\pi_{avg}(a|x) := \\sum_{k=1}^K \\rho_k \\pi_k(a|x)`.
We can represent the whole logged bandit data as :math:`\\mathcal{D}=\\{(k_i,x_i,a_i,r_i)\\}_{i=1}^{n}` where :math:`k_i` is the index to indicate the logging/behavior policy that generates i-th data, i.e., :math:`\\pi_{k_i}`.
Note that :math:`n := \\sum_{k=1}^K` is the total number of logged bandit data, and :math:`\\rho_k := n_k / n` is the dataset proportions.
:math:`\\mathbb{E}_{n}[\\cdot]` is the empirical average over :math:`n` observations in :math:`\\mathcal{D}`.
When the clipping is applied, a large importance weight is clipped as :math:`\\hat{w}_{avg}(x,a) := \\min \\{ \\lambda, w_{avg}(x,a) \\}`, where :math:`\\lambda (>0)` is a hyperparameter to specify a maximum allowed importance weight.
Multi-Bal-IPW applies the standard IPW based on the averaged logging/behavior policy :math:`\\pi_{avg}`.
Parameters
------------
lambda_: float, default=np.inf
A maximum possible value of the importance weight.
When a positive finite value is given, importance weights larger than `lambda_` will be clipped.
use_estimated_pscore: bool, default=False.
If True, `estimated_pscore` is used, otherwise, `pscore` (the true propensity scores) is used.
estimator_name: str, default='multi_bal_ipw'.
Name of the estimator.
References
------------
Aman Agarwal, Soumya Basu, Tobias Schnabel, and Thorsten Joachims.
"Effective Evaluation using Logged Bandit Feedback from Multiple Loggers.", 2018.
Nathan Kallus, Yuta Saito, and Masatoshi Uehara.
"Optimal Off-Policy Evaluation from Multiple Logging Policies.", 2021.
"""
lambda_: float = np.inf
use_estimated_pscore: bool = False
estimator_name: str = "multi_bal_ipw"
def __post_init__(self) -> None:
"""Initialize Class."""
check_scalar(
self.lambda_,
name="lambda_",
target_type=(int, float),
min_val=0.0,
)
if self.lambda_ != self.lambda_:
raise ValueError("`lambda_` must not be nan")
if not isinstance(self.use_estimated_pscore, bool):
raise TypeError(
f"`use_estimated_pscore` must be a bool, but {type(self.use_estimated_pscore)} is given"
)
def _estimate_round_rewards(
self,
reward: np.ndarray,
action: np.ndarray,
pscore_avg: np.ndarray,
action_dist: np.ndarray,
position: Optional[np.ndarray] = None,
**kwargs,
) -> np.ndarray:
"""Estimate round-wise (or sample-wise) rewards.
Parameters
----------
reward: array-like, shape (n_rounds,)
Rewards observed for each data in logged bandit data, i.e., :math:`r_i`.
action: array-like, shape (n_rounds,)
Actions sampled by the logging/behavior policy for each data in logged bandit data, i.e., :math:`a_i`.
pscore_avg: array-like, shape (n_rounds,)
Action choice probabilities of the average logging/behavior policy, i.e., :math:`\\pi_{avg}(a_i|x_i)`.
If `use_estimated_pscore` is False, `pscore_avg` must be given.
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.
position: array-like, shape (n_rounds,), default=None
Indices to differentiate positions in a recommendation interface where the actions are presented.
If None, the effect of position on the reward will be ignored.
(If only a single action is chosen for each data, you can just ignore this argument.)
Returns
----------
estimated_rewards: array-like, shape (n_rounds,)
Estimated rewards for each observation.
"""
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
iw_avg = action_dist[np.arange(action.shape[0]), action, position] / pscore_avg
# weight clipping
if isinstance(iw_avg, np.ndarray):
iw_avg = np.minimum(iw_avg, self.lambda_)
return reward * iw_avg
def estimate_policy_value(
self,
reward: np.ndarray,
action: np.ndarray,
action_dist: np.ndarray,
pscore_avg: Optional[np.ndarray] = None,
position: Optional[np.ndarray] = None,
estimated_pscore_avg: Optional[np.ndarray] = None,
**kwargs,
) -> np.ndarray:
"""Estimate the policy value of evaluation policy.
Parameters
----------
reward: array-like, shape (n_rounds,)
Rewards observed for each data in logged bandit data, i.e., :math:`r_i`.
action: array-like, shape (n_rounds,)
Actions sampled by the logging/behavior policy for each data in logged bandit data, i.e., :math:`a_i`.
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.
pscore_avg: array-like, shape (n_rounds,), default=None
Action choice probabilities of the logging/behavior policy (propensity scores), i.e., :math:`\\pi_{avg}(a_i|x_i)`.
If `use_estimated_pscore` is False, `pscore_avg` must be given.
position: array-like, shape (n_rounds,), default=None
Indices to differentiate positions in a recommendation interface where the actions are presented.
If None, the effect of position on the reward will be ignored.
(If only a single action is chosen for each data, you can just ignore this argument.)
estimated_pscore_avg: array-like, shape (n_rounds,), default=None
Estimated average logging/behavior policy, i.e., :math:`\\hat{\\pi}_{avg}(a_i|x_i)`.
If `self.use_estimated_pscore` is True, `estimated_pscore` must be given.
Returns
----------
V_hat: float
Estimated policy value of evaluation policy.
"""
check_array(array=reward, name="reward", expected_dim=1)
check_array(array=action, name="action", expected_dim=1)
if self.use_estimated_pscore:
check_array(
array=estimated_pscore_avg, name="estimated_pscore_avg", expected_dim=1
)
pscore_ = estimated_pscore_avg
else:
check_array(array=pscore_avg, name="pscore_avg", expected_dim=1)
pscore_ = pscore_avg
check_multi_loggers_ope_inputs(
action_dist=action_dist,
position=position,
action=action,
reward=reward,
pscore=pscore_,
)
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
return self._estimate_round_rewards(
reward=reward,
action=action,
position=position,
pscore_avg=pscore_,
action_dist=action_dist,
).mean()
def estimate_interval(
self,
reward: np.ndarray,
action: np.ndarray,
action_dist: np.ndarray,
pscore_avg: Optional[np.ndarray] = None,
position: Optional[np.ndarray] = None,
estimated_pscore_avg: Optional[np.ndarray] = None,
alpha: float = 0.05,
n_bootstrap_samples: int = 10000,
random_state: Optional[int] = None,
**kwargs,
) -> Dict[str, float]:
"""Estimate the confidence interval of the policy value using bootstrap.
Parameters
----------
reward: array-like, shape (n_rounds,)
Rewards observed for each data in logged bandit data, i.e., :math:`r_i`.
action: array-like, shape (n_rounds,)
Actions sampled by the logging/behavior policy for each data in logged bandit data, i.e., :math:`a_i`.
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.
pscore_avg: array-like, shape (n_rounds,), default=None
Action choice probabilities of the average logging/behavior policy (propensity scores), i.e., :math:`\\pi_{avg}(a_i|x_i)`.
If `use_estimated_pscore` is False, `pscore_avg` must be given.
position: array-like, shape (n_rounds,), default=None
Indices to differentiate positions in a recommendation interface where the actions are presented.
If None, the effect of position on the reward will be ignored.
(If only a single action is chosen for each data, you can just ignore this argument.)
estimated_pscore: array-like, shape (n_rounds,), default=None
Estimated logging/behavior policy, i.e., :math:`\\hat{\\pi}_b(a_i|x_i)`.
If `self.use_estimated_pscore` is True, `estimated_pscore` must be given.
alpha: float, default=0.05
Significance level.
n_bootstrap_samples: int, default=10000
Number of resampling performed in bootstrap sampling.
random_state: int, default=None
Controls the random seed in bootstrap sampling.
Returns
----------
estimated_confidence_interval: Dict[str, float]
Dictionary storing the estimated mean and upper-lower confidence bounds.
"""
check_array(array=reward, name="reward", expected_dim=1)
check_array(array=action, name="action", expected_dim=1)
if self.use_estimated_pscore:
check_array(
array=estimated_pscore_avg, name="estimated_pscore_avg", expected_dim=1
)
pscore_ = estimated_pscore_avg
else:
check_array(array=pscore_avg, name="pscore_avg", expected_dim=1)
pscore_ = pscore_avg
check_multi_loggers_ope_inputs(
action_dist=action_dist,
position=position,
action=action,
reward=reward,
pscore=pscore_,
)
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
estimated_round_rewards = self._estimate_round_rewards(
reward=reward,
action=action,
position=position,
pscore=pscore_,
action_dist=action_dist,
)
return estimate_confidence_interval_by_bootstrap(
samples=estimated_round_rewards,
alpha=alpha,
n_bootstrap_samples=n_bootstrap_samples,
random_state=random_state,
)
@dataclass
class MultiLoggersWeightedInverseProbabilityWeighting(
MultiLoggersNaiveInverseProbabilityWeighting
):
"""Multi-Loggers Weighted Inverse Probability Weighting (Multi-Weighted-IPW) Estimator.
Note
-------
This estimator is called Weighted IPS in Agarwal et al.(2018) and Precision Weighted IS in Kallus et al.(2021).
Multi-Weighted-IPW estimates the policy value of evaluation policy :math:`\\pi_e`
using logged data collected by multiple logging/behavior policies as
.. math::
\\hat{V}_{\\mathrm{Multi-Weighted-IPW}} (\\pi_e; \\mathcal{D})
:= \\sum_{k=1}^K \\M^*_k \\mathbb{E}_{n_k} [ w_k(x_i,a_i) r_i],
where :math:`\\mathcal{D}_k=\\{(x_i,a_i,r_i)\\}_{i=1}^{n_k}` is logged bandit data with :math:`n_k` observations collected by
the k-th behavior policy :math:`\\pi_k`. :math:`w_k(x,a):=\\pi_e (a|x)/\\pi_k (a|x)` is the importance weight given :math:`x` and :math:`a` computed for the k-th behavior policy.
We can represent the whole logged bandit data as :math:`\\mathcal{D}=\\{(k_i,x_i,a_i,r_i)\\}_{i=1}^{n}` where :math:`k_i` is the index to indicate the logging/behavior policy that generates i-th data, i.e., :math:`\\pi_{k_i}`.
Note that :math:`n := \\sum_{k=1}^K` is the total number of logged bandit data, and :math:`\\rho_k := n_k / n` is the dataset proportions.
:math:`\\mathbb{E}_{n}[\\cdot]` is the empirical average over :math:`n` observations in :math:`\\mathcal{D}`.
When the clipping is applied, a large importance weight is clipped as :math:`\\hat{w}_k(x,a) := \\min \\{ \\lambda, w_k(x,a) \\}`, where :math:`\\lambda (>0)` is a hyperparameter to specify a maximum allowed importance weight.
Multi-Weighted-IPW prioritizes the strata generated by the logging/behavior policies similar to the evaluation policy.
The weight for the k-th logging/behavior policy :math:`\\M^*_k` is defined based on
the divergence between the evaluation policy :math:`\\pi_e` and :math:`\\pi_k`.
Parameters
------------
lambda_: float, default=np.inf
A maximum possible value of the importance weight.
When a positive finite value is given, importance weights larger than `lambda_` will be clipped.
use_estimated_pscore: bool, default=False.
If True, `estimated_pscore` is used, otherwise, `pscore` (the true propensity scores) is used.
estimator_name: str, default='multi_weighted_ipw'.
Name of the estimator.
References
------------
Aman Agarwal, Soumya Basu, Tobias Schnabel, and Thorsten Joachims.
"Effective Evaluation using Logged Bandit Feedback from Multiple Loggers.", 2018.
Nathan Kallus, Yuta Saito, and Masatoshi Uehara.
"Optimal Off-Policy Evaluation from Multiple Logging Policies.", 2021.
"""
estimator_name: str = "multi_weighted_ipw"
def _estimate_round_rewards(
self,
reward: np.ndarray,
action: np.ndarray,
pscore: np.ndarray,
stratum_idx: np.ndarray,
action_dist: np.ndarray,
position: Optional[np.ndarray] = None,
**kwargs,
) -> np.ndarray:
"""Estimate round-wise (or sample-wise) rewards.
Parameters
----------
reward: array-like, shape (n_rounds,)
Rewards observed for each data in logged bandit data, i.e., :math:`r_i`.
action: array-like, shape (n_rounds,)
Actions sampled by the logging/behavior policy for each data in logged bandit data, i.e., :math:`a_i`.
pscore: array-like, shape (n_rounds,)
Action choice probabilities of the logging/behavior policy (propensity scores), i.e., :math:`\\pi_k(a_i|x_i)`.
If `use_estimated_pscore` is False, `pscore` must be given.
stratum_idx: array-like, shape (n_rounds,)
Indices to differentiate the logging/behavior policy that generate each data, i.e., :math:`k`.
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.
position: array-like, shape (n_rounds,), default=None
Indices to differentiate positions in a recommendation interface where the actions are presented.
If None, the effect of position on the reward will be ignored.
(If only a single action is chosen for each data, you can just ignore this argument.)
Returns
----------
estimated_rewards: array-like, shape (n_rounds,)
Estimated rewards for each observation.
"""
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
n = action.shape[0]
iw = action_dist[np.arange(n), action, position] / pscore
# weight clipping
if isinstance(iw, np.ndarray):
iw = np.minimum(iw, self.lambda_)
unique_stratum_idx, n_data_strata = np.unique(stratum_idx, return_counts=True)
var_k = np.zeros(unique_stratum_idx.shape[0])
for k in unique_stratum_idx:
idx_ = stratum_idx == k
var_k[k] = np.var(reward[idx_] * iw[idx_])
weight_k = n / (var_k * np.sum(n_data_strata / var_k))
return reward * iw * weight_k[stratum_idx]
def estimate_policy_value(
self,
reward: np.ndarray,
action: np.ndarray,
action_dist: np.ndarray,
stratum_idx: np.ndarray,
pscore: Optional[np.ndarray] = None,
position: Optional[np.ndarray] = None,
estimated_pscore: Optional[np.ndarray] = None,
**kwargs,
) -> np.ndarray:
"""Estimate the policy value of evaluation policy.
Parameters
----------
reward: array-like, shape (n_rounds,)
Rewards observed for each data in logged bandit data, i.e., :math:`r_i`.
action: array-like, shape (n_rounds,)
Actions sampled by the logging/behavior policy for each data in logged bandit data, i.e., :math:`a_i`.
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.
stratum_idx: array-like, shape (n_rounds,)
Indices to differentiate the logging/behavior policy that generate each data, i.e., :math:`k`.
pscore: array-like, shape (n_rounds,), default=None
Action choice probabilities of the logging/behavior policy (propensity scores), i.e., :math:`\\pi_k(a_i|x_i)`.
If `use_estimated_pscore` is False, `pscore` must be given.
position: array-like, shape (n_rounds,), default=None
Indices to differentiate positions in a recommendation interface where the actions are presented.
If None, the effect of position on the reward will be ignored.
(If only a single action is chosen for each data, you can just ignore this argument.)
estimated_pscore: array-like, shape (n_rounds,), default=None
Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_k(a_i|x_i)`.
If `self.use_estimated_pscore` is True, `estimated_pscore` must be given.
Returns
----------
V_hat: float
Estimated policy value of evaluation policy.
"""
check_array(array=reward, name="reward", expected_dim=1)
check_array(array=action, name="action", expected_dim=1)
check_array(array=stratum_idx, name="stratum_idx", expected_dim=1)
if self.use_estimated_pscore:
check_array(array=estimated_pscore, name="estimated_pscore", expected_dim=1)
pscore_ = estimated_pscore
else:
check_array(array=pscore, name="pscore", expected_dim=1)
pscore_ = pscore
check_multi_loggers_ope_inputs(
action_dist=action_dist,
position=position,
action=action,
reward=reward,
stratum_idx=stratum_idx,
pscore=pscore_,
)
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
return self._estimate_round_rewards(
reward=reward,
action=action,
position=position,
pscore=pscore_,
stratum_idx=stratum_idx,
action_dist=action_dist,
).mean()
def estimate_interval(
self,
reward: np.ndarray,
action: np.ndarray,
stratum_idx: np.ndarray,
action_dist: np.ndarray,
pscore: Optional[np.ndarray] = None,
position: Optional[np.ndarray] = None,
estimated_pscore: Optional[np.ndarray] = None,
alpha: float = 0.05,
n_bootstrap_samples: int = 10000,
random_state: Optional[int] = None,
**kwargs,
) -> Dict[str, float]:
"""Estimate the confidence interval of the policy value using bootstrap.
Parameters
----------
reward: array-like, shape (n_rounds,)
Rewards observed for each data in logged bandit data, i.e., :math:`r_i`.
action: array-like, shape (n_rounds,)
Actions sampled by the logging/behavior policy for each data in logged bandit data, i.e., :math:`a_i`.
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.
stratum_idx: array-like, shape (n_rounds,)
Indices to differentiate the logging/behavior policy that generate each data, i.e., :math:`k_i`.
pscore: array-like, shape (n_rounds,), default=None
Action choice probabilities of the logging/behavior policy (propensity scores), i.e., :math:`\\pi_k(a_i|x_i)`.
If `use_estimated_pscore` is False, `pscore` must be given.
position: array-like, shape (n_rounds,), default=None
Indices to differentiate positions in a recommendation interface where the actions are presented.
If None, the effect of position on the reward will be ignored.
(If only a single action is chosen for each data, you can just ignore this argument.)
estimated_pscore: array-like, shape (n_rounds,), default=None
Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_b(a_i|x_i)`.
If `self.use_estimated_pscore` is True, `estimated_pscore` must be given.
alpha: float, default=0.05
Significance level.
n_bootstrap_samples: int, default=10000
Number of resampling performed in bootstrap sampling.
random_state: int, default=None
Controls the random seed in bootstrap sampling.
Returns
----------
estimated_confidence_interval: Dict[str, float]
Dictionary storing the estimated mean and upper-lower confidence bounds.
"""
check_array(array=reward, name="reward", expected_dim=1)
check_array(array=action, name="action", expected_dim=1)
check_array(array=stratum_idx, name="stratum_idx", expected_dim=1)
if self.use_estimated_pscore:
check_array(array=estimated_pscore, name="estimated_pscore", expected_dim=1)
pscore_ = estimated_pscore
else:
check_array(array=pscore, name="pscore", expected_dim=1)
pscore_ = pscore
check_multi_loggers_ope_inputs(
action_dist=action_dist,
position=position,
action=action,
reward=reward,
stratum_idx=stratum_idx,
pscore=pscore_,
)
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
estimated_round_rewards = self._estimate_round_rewards(
reward=reward,
action=action,
position=position,
stratum_idx=stratum_idx,
pscore=pscore_,
action_dist=action_dist,
)
return estimate_confidence_interval_by_bootstrap(
samples=estimated_round_rewards,
alpha=alpha,
n_bootstrap_samples=n_bootstrap_samples,
random_state=random_state,
)
@dataclass
class MultiLoggersNaiveDoublyRobust(BaseMultiLoggersOffPolicyEstimator):
"""Multi-Loggers Naive Doubly Robust (Multi-Naive-DR) Estimator.
Note
-------
This estimator is called Average DR in Kallus et al.(2021).
Multi-Naive-DR estimates the policy value of evaluation policy :math:`\\pi_e`
using logged data collected by multiple logging/behavior policies as
.. math::
\\hat{V}_{\\mathrm{Multi-Naive-DR}} (\\pi_e; \\mathcal{D}, \\hat{q})
:= \\mathbb{E}_{n} [\\hat{q}(x_i,\\pi_e) + w_{k_i}(x_i,a_i) (r_i - \\hat{q}(x_i,a_i))],
where :math:`\\mathcal{D}_k=\\{(x_i,a_i,r_i)\\}_{i=1}^{n_k}` is logged bandit data with :math:`n_k` observations collected by
the k-th behavior policy :math:`\\pi_k`. :math:`w_k(x,a):=\\pi_e (a|x)/\\pi_k (a|x)` is the importance weight given :math:`x` and :math:`a` computed for the k-th behavior policy.
We can represent the whole logged bandit data as :math:`\\mathcal{D}=\\{(k_i,x_i,a_i,r_i)\\}_{i=1}^{n}` where :math:`k_i` is the index to indicate the logging/behavior policy that generates i-th data, i.e., :math:`\\pi_{k_i}`.
Note that :math:`n := \\sum_{k=1}^K` is the total number of logged bandit data.
:math:`\\mathbb{E}_{n}[\\cdot]` is the empirical average over :math:`n` observations in :math:`\\mathcal{D}`.
:math:`\\hat{q} (x,a)` is the estimated expected reward given :math:`x` and :math:`a`.
:math:`\\hat{q} (x_i,\\pi):= \\mathbb{E}_{a \\sim \\pi(a|x)}[\\hat{q}(x,a)]` is the expectation of the estimated reward function over :math:`\\pi`.
When the clipping is applied, a large importance weight is clipped as :math:`\\hat{w}_k(x,a) := \\min \\{ \\lambda, w_k(x,a) \\}`, where :math:`\\lambda (>0)` is a hyperparameter to specify a maximum allowed importance weight.
Multi-Naive-DR applies the standard DR to each stratum and takes the weighted average of the K datasets.
Parameters
------------
lambda_: float, default=np.inf
A maximum possible value of the importance weight.
When a positive finite value is given, importance weights larger than `lambda_` will be clipped.
use_estimated_pscore: bool, default=False.
If True, `estimated_pscore` is used, otherwise, `pscore` (the true propensity scores) is used.
estimator_name: str, default='multi_dr'.
Name of the estimator.
References
------------
Aman Agarwal, Soumya Basu, Tobias Schnabel, and Thorsten Joachims.
"Effective Evaluation using Logged Bandit Feedback from Multiple Loggers.", 2018.
Nathan Kallus, Yuta Saito, and Masatoshi Uehara.
"Optimal Off-Policy Evaluation from Multiple Logging Policies.", 2021.
"""
lambda_: float = np.inf
use_estimated_pscore: bool = False
estimator_name: str = "multi_dr"
def __post_init__(self) -> None:
"""Initialize Class."""
check_scalar(
self.lambda_,
name="lambda_",
target_type=(int, float),
min_val=0.0,
)
if self.lambda_ != self.lambda_:
raise ValueError("`lambda_` must not be nan")
if not isinstance(self.use_estimated_pscore, bool):
raise TypeError(
f"`use_estimated_pscore` must be a bool, but {type(self.use_estimated_pscore)} is given"
)
def _estimate_round_rewards(
self,
reward: np.ndarray,
action: np.ndarray,
pscore: np.ndarray,
action_dist: np.ndarray,
estimated_rewards_by_reg_model: np.ndarray,
position: Optional[np.ndarray] = None,
**kwargs,
) -> np.ndarray:
"""Estimate round-wise (or sample-wise) rewards.
Parameters
----------
reward: array-like, shape (n_rounds,)
Rewards observed for each data in logged bandit data, i.e., :math:`r_i`.
action: array-like, shape (n_rounds,)
Actions sampled by the logging/behavior policy for each data in logged bandit data, i.e., :math:`a_i`.
pscore: array-like, shape (n_rounds,)
Action choice probabilities of the logging/behavior policy (propensity scores), i.e., :math:`\\pi_k(a_i|x_i)`.
If `use_estimated_pscore` is False, `pscore` must be given.
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.
estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list)
Estimated expected rewards given context, action, and position, i.e., :math:`\\hat{q}(x_i,a_i)`.
position: array-like, shape (n_rounds,), default=None
Indices to differentiate positions in a recommendation interface where the actions are presented.
If None, the effect of position on the reward will be ignored.
(If only a single action is chosen for each data, you can just ignore this argument.)
Returns
----------
estimated_rewards: array-like, shape (n_rounds,)
Estimated rewards for each observation.
"""
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
iw = action_dist[np.arange(action.shape[0]), action, position] / pscore
# weight clipping
if isinstance(iw, np.ndarray):
iw = np.minimum(iw, self.lambda_)
n = action.shape[0]
q_hat_at_position = estimated_rewards_by_reg_model[np.arange(n), :, position]
q_hat_factual = estimated_rewards_by_reg_model[np.arange(n), action, position]
pi_e_at_position = action_dist[np.arange(n), :, position]
estimated_rewards = np.average(
q_hat_at_position,
weights=pi_e_at_position,
axis=1,
)
estimated_rewards += iw * (reward - q_hat_factual)
return estimated_rewards
def estimate_policy_value(
self,
reward: np.ndarray,
action: np.ndarray,
action_dist: np.ndarray,