-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathestimators.py
2403 lines (1951 loc) · 97.4 KB
/
estimators.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_ope_inputs
from ..utils import estimate_confidence_interval_by_bootstrap
from .helper import estimate_bias_in_ope
from .helper import estimate_high_probability_upper_bound_bias
@dataclass
class BaseOffPolicyEstimator(metaclass=ABCMeta):
"""Base class for OPE estimators."""
@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 ReplayMethod(BaseOffPolicyEstimator):
"""Relpay Method (RM).
Note
-------
RM estimates the policy value of evaluation policy :math:`\\pi_e` as
.. math::
\\hat{V}_{\\mathrm{RM}} (\\pi_e; \\mathcal{D}) :=
\\frac{\\mathbb{E}_{n}[\\mathbb{I} \\{ \\pi_e(x_t)=a_t \\} r_t]}{\\mathbb{E}_{n}[\\mathbb{I} \\{ \\pi_e(x_t)=a_t \\}]},
where :math:`\\mathcal{D}=\\{(x_i,a_i,r_i)\\}_{i=1}^{n}` is logged bandit data with :math:`n` observations collected by
behavior policy :math:`\\pi_b`. :math:`\\pi_e: \\mathcal{X} \\rightarrow \\mathcal{A}` is the function
representing action choices by the evaluation policy realized during offline bandit simulation.
:math:`\\mathbb{E}_{n}[\\cdot]` is the empirical average over :math:`n` observations in :math:`\\mathcal{D}`.
Parameters
----------
estimator_name: str, default='rm'.
Name of the estimator.
References
------------
Lihong Li, Wei Chu, John Langford, and Xuanhui Wang.
"Unbiased Offline Evaluation of Contextual-bandit-based News Article Recommendation Algorithms.", 2011.
"""
estimator_name: str = "rm"
def _estimate_round_rewards(
self,
reward: np.ndarray,
action: 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`.
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)
action_match = np.array(
action_dist[np.arange(action.shape[0]), action, position] == 1
)
estimated_rewards = np.zeros_like(action_match)
if action_match.sum() > 0.0:
estimated_rewards = action_match * reward / action_match.mean()
return estimated_rewards
def estimate_policy_value(
self,
reward: np.ndarray,
action: np.ndarray,
action_dist: np.ndarray,
position: Optional[np.ndarray] = None,
**kwargs,
) -> float:
"""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)`.
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
----------
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_ope_inputs(
action_dist=action_dist, position=position, action=action, reward=reward
)
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
return self._estimate_round_rewards(
reward=reward,
action=action,
position=position,
action_dist=action_dist,
).mean()
def estimate_interval(
self,
reward: np.ndarray,
action: np.ndarray,
action_dist: np.ndarray,
position: Optional[np.ndarray] = None,
alpha: float = 0.05,
n_bootstrap_samples: int = 100,
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)`.
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.)
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_ope_inputs(
action_dist=action_dist, position=position, action=action, reward=reward
)
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,
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 InverseProbabilityWeighting(BaseOffPolicyEstimator):
"""Inverse Probability Weighting (IPW) Estimator.
Note
-------
IPW estimates the policy value of evaluation policy :math:`\\pi_e` as
.. math::
\\hat{V}_{\\mathrm{IPW}} (\\pi_e; \\mathcal{D}) := \\mathbb{E}_{n} [ w(x_i,a_i) r_i],
where :math:`\\mathcal{D}=\\{(x_i,a_i,r_i)\\}_{i=1}^{n}` is logged bandit data with :math:`n` observations collected by
behavior policy :math:`\\pi_b`. :math:`w(x,a):=\\pi_e (a|x)/\\pi_b (a|x)` is the importance weight given :math:`x` and :math:`a`.
: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}(x,a) := \\min \\{ \\lambda, w(x,a) \\}`
where :math:`\\lambda (>0)` is a hyperparameter to specify a maximum allowed importance weight.
IPW re-weights the rewards by the ratio of the evaluation policy and behavior policy (importance weight).
When the behavior policy is known, IPW is unbiased and consistent for the true policy value.
However, it can have a large variance, especially when the evaluation policy significantly deviates from the behavior policy.
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='ipw'.
Name of the estimator.
References
------------
Alex Strehl, John Langford, Lihong Li, and Sham M Kakade.
"Learning from Logged Implicit Exploration Data"., 2010.
Miroslav Dudík, Dumitru Erhan, John Langford, and Lihong Li.
"Doubly Robust Policy Evaluation and Optimization.", 2014.
Yi Su, Maria Dimakopoulou, Akshay Krishnamurthy, and Miroslav Dudik.
"Doubly Robust Off-Policy Evaluation with Shrinkage.", 2020.
"""
lambda_: float = np.inf
use_estimated_pscore: bool = False
estimator_name: str = "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_b(a_i|x_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)`.
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_b(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.
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_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_b(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_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,
)
def _estimate_mse_score(
self,
reward: np.ndarray,
action: np.ndarray,
pscore: np.ndarray,
action_dist: np.ndarray,
position: Optional[np.ndarray] = None,
use_bias_upper_bound: bool = True,
delta: float = 0.05,
**kwargs,
) -> float:
"""Estimate the MSE score of a given clipping hyperparameter to conduct hyperparameter tuning.
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_b(a_i|x_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)`.
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.)
use_bias_upper_bound: bool, default=True
Whether to use a bias upper bound in hyperparameter tuning.
If False, the direct bias estimator is used to estimate the MSE. See Su et al.(2020) for details.
delta: float, default=0.05
A confidence delta to construct a high probability upper bound used in SLOPE.
Returns
----------
estimated_mse_score: float
Estimated MSE score of a given clipping hyperparameter `lambda_`.
MSE score is the sum of (high probability) upper bound of bias and the sample variance.
This is estimated using the automatic hyperparameter tuning procedure
based on Section 5 of Su et al.(2020).
"""
n = reward.shape[0]
# estimate the sample variance of IPW with clipping
sample_variance = np.var(
self._estimate_round_rewards(
reward=reward,
action=action,
pscore=pscore,
action_dist=action_dist,
position=position,
)
)
sample_variance /= n
# estimate the (high probability) upper bound of the bias of IPW with clipping
iw = action_dist[np.arange(n), action, position] / pscore
if use_bias_upper_bound:
bias_term = estimate_high_probability_upper_bound_bias(
reward=reward, iw=iw, iw_hat=np.minimum(iw, self.lambda_), delta=delta
)
else:
bias_term = estimate_bias_in_ope(
reward=reward,
iw=iw,
iw_hat=np.minimum(iw, self.lambda_),
)
estimated_mse_score = sample_variance + (bias_term**2)
return estimated_mse_score
@dataclass
class SelfNormalizedInverseProbabilityWeighting(InverseProbabilityWeighting):
"""Self-Normalized Inverse Probability Weighting (SNIPW) Estimator.
Note
-------
SNIPW estimates the policy value of evaluation policy :math:`\\pi_e` as
.. math::
\\hat{V}_{\\mathrm{SNIPW}} (\\pi_e; \\mathcal{D}) :=
\\frac{\\mathbb{E}_{n} [w(x_i,a_i) r_i]}{ \\mathbb{E}_{n} [w(x_i,a_i)]},
where :math:`\\mathcal{D}=\\{(x_i,a_i,r_i)\\}_{i=1}^{n}` is logged bandit data with :math:`n` observations collected by
behavior policy :math:`\\pi_b`. :math:`w(x,a):=\\pi_e (a|x)/\\pi_b (a|x)` is the importance weight given :math:`x` and :math:`a`.
:math:`\\mathbb{E}_{n}[\\cdot]` is the empirical average over :math:`n` observations in :math:`\\mathcal{D}`.
SNIPW normalizes the observed rewards by the self-normalized importance weihgt.
This estimator is not unbiased even when the behavior policy is known.
However, it is still consistent for the true policy value and gains some stability in OPE.
See the reference papers for more details.
Parameters
----------
use_estimated_pscore: bool, default=False.
If True, `estimated_pscore` is used, otherwise, `pscore` (the true propensity scores) is used.
estimator_name: str, default='snipw'.
Name of the estimator.
References
----------
Adith Swaminathan and Thorsten Joachims.
"The Self-normalized Estimator for Counterfactual Learning.", 2015.
Nathan Kallus and Masatoshi Uehara.
"Intrinsically Efficient, Stable, and Bounded Off-Policy Evaluation for Reinforcement Learning.", 2019.
"""
estimator_name: str = "snipw"
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_b(a_i|x_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)`.
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
return reward * iw / iw.mean()
@dataclass
class DirectMethod(BaseOffPolicyEstimator):
"""Direct Method (DM).
Note
-------
DM first trains a supervised ML model, such as ridge regression and gradient boosting,
to estimate the reward function (:math:`q(x,a) = \\mathbb{E}[r|x,a]`).
It then uses the estimated rewards to estimate the policy value as follows.
.. math::
\\hat{V}_{\\mathrm{DM}} (\\pi_e; \\mathcal{D}, \\hat{q})
&:= \\mathbb{E}_{n} \\left[ \\sum_{a \\in \\mathcal{A}} \\hat{q} (x_i,a) \\pi_e(a|x_i) \\right], \\\\
& = \\mathbb{E}_{n}[\\hat{q} (x_i,\\pi_e)],
where :math:`\\mathcal{D}=\\{(x_i,a_i,r_i)\\}_{i=1}^{n}` is logged bandit data with :math:`n` observations collected by
behavior policy :math:`\\pi_b`. :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`.
To estimate the reward function, please use `obp.ope.regression_model.RegressionModel`, which supports several fitting methods specific to OPE (such as cross-fitting).
If the regression model (:math:`\\hat{q}`) is a good approximation to the true mean reward function,
this estimator accurately estimates the policy value of the evaluation policy.
If the regression function fails to approximate the reward function well,
however, the final estimator is no longer consistent.
Parameters
----------
estimator_name: str, default='dm'.
Name of the estimator.
References
----------
Alina Beygelzimer and John Langford.
"The offset tree for learning with partial labels.", 2009.
Miroslav Dudík, Dumitru Erhan, John Langford, and Lihong Li.
"Doubly Robust Policy Evaluation and Optimization.", 2014.
"""
estimator_name: str = "dm"
def _estimate_round_rewards(
self,
action_dist: np.ndarray,
estimated_rewards_by_reg_model: np.ndarray,
position: Optional[np.ndarray] = None,
**kwargs,
) -> np.ndarray:
"""Estimate the policy value of evaluation policy.
Parameters
----------
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)
n = position.shape[0]
q_hat_at_position = estimated_rewards_by_reg_model[np.arange(n), :, position]
pi_e_at_position = action_dist[np.arange(n), :, position]
return np.average(
q_hat_at_position,
weights=pi_e_at_position,
axis=1,
)
def estimate_policy_value(
self,
action_dist: np.ndarray,
estimated_rewards_by_reg_model: np.ndarray,
position: Optional[np.ndarray] = None,
**kwargs,
) -> float:
"""Estimate the policy value of evaluation policy.
Parameters
----------
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
----------
V_hat: float
Estimated policy value of evaluation policy.
"""
check_array(
array=estimated_rewards_by_reg_model,
name="estimated_rewards_by_reg_model",
expected_dim=3,
)
check_ope_inputs(
action_dist=action_dist,
estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
position=position,
)
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
return self._estimate_round_rewards(
position=position,
estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
action_dist=action_dist,
).mean()
def estimate_interval(
self,
action_dist: np.ndarray,
estimated_rewards_by_reg_model: np.ndarray,
position: 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
----------
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.)
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=estimated_rewards_by_reg_model,
name="estimated_rewards_by_reg_model",
expected_dim=3,
)
check_ope_inputs(
action_dist=action_dist,
estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
position=position,
)
if position is None:
position = np.zeros(action_dist.shape[0], dtype=int)
estimated_round_rewards = self._estimate_round_rewards(
position=position,
estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
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 DoublyRobust(BaseOffPolicyEstimator):
"""Doubly Robust (DR) Estimator.
Note
-------
Similar to DM, DR estimates the reward function (:math:`q(x,a) = \\mathbb{E}[r|x,a]`).
It then uses the estimated rewards to estimate the policy value as follows.
.. math::
\\hat{V}_{\\mathrm{DR}} (\\pi_e; \\mathcal{D}, \\hat{q})
:= \\mathbb{E}_{n}[\\hat{q}(x_i,\\pi_e) + w(x_i,a_i) (r_i - \\hat{q}(x_i,a_i))],
where :math:`\\mathcal{D}=\\{(x_i,a_i,r_i)\\}_{i=1}^{n}` is logged bandit data with :math:`n` observations collected by
behavior policy :math:`\\pi_b`.
:math:`w(x,a):=\\pi_e (a|x)/\\pi_b (a|x)` is the importance weight given :math:`x` and :math:`a`.
: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}(x,a) := \\min \\{ \\lambda, w(x,a) \\}`
where :math:`\\lambda (>0)` is a hyperparameter to specify a maximum allowed importance weight.
To estimate the reward function, please use `obp.ope.regression_model.RegressionModel`,
which supports several fitting methods specific to OPE such as *more robust doubly robust*.
DR mimics IPW to use a weighted version of rewards, but DR also uses the estimated mean reward
function (the regression model) as a control variate to decrease the variance.
It preserves the consistency of IPW if either the importance weight or
the mean reward estimator is accurate (a property called double robustness).
Moreover, DR is semiparametric efficient when the mean reward estimator is correctly specified.
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.
DoublyRobust with a finite positive `lambda_` corresponds to DR with Pessimistic Shrinkage of Su et al.(2020)
or CAB-DR of Su et al.(2019).
use_estimated_pscore: bool, default=False.
If True, `estimated_pscore` is used, otherwise, `pscore` (the true propensity scores) is used.
estimator_name: str, default='dr'.
Name of the estimator.
References
----------
Miroslav Dudík, Dumitru Erhan, John Langford, and Lihong Li.
"Doubly Robust Policy Evaluation and Optimization.", 2014.
Mehrdad Farajtabar, Yinlam Chow, and Mohammad Ghavamzadeh.
"More Robust Doubly Robust Off-policy Evaluation.", 2018.
Yi Su, Lequn Wang, Michele Santacatterina, and Thorsten Joachims.
"CAB: Continuous Adaptive Blending Estimator for Policy Evaluation and Learning", 2019.
Yi Su, Maria Dimakopoulou, Akshay Krishnamurthy, and Miroslav Dudík.
"Doubly robust off-policy evaluation with shrinkage.", 2020.
"""
lambda_: float = np.inf
use_estimated_pscore: bool = False
estimator_name: str = "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_b(a_i|x_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)`.
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)
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_)
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,