-
Notifications
You must be signed in to change notification settings - Fork 89
/
meta_slate.py
673 lines (574 loc) · 30.4 KB
/
meta_slate.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
# Copyright (c) Yuta Saito, Yusuke Narita, and ZOZO Technologies, Inc. All rights reserved.
# Licensed under the Apache 2.0 License.
"""Off-Policy Evaluation Class to Streamline OPE of Slate/Ranking Policies."""
from dataclasses import dataclass
from logging import getLogger
from pathlib import Path
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
import matplotlib.pyplot as plt
import numpy as np
from pandas import DataFrame
import seaborn as sns
from sklearn.utils import check_scalar
from ..types import BanditFeedback
from ..utils import check_confidence_interval_arguments
from .estimators_slate import BaseSlateOffPolicyEstimator
from .estimators_slate import SlateCascadeDoublyRobust as CascadeDR
logger = getLogger(__name__)
@dataclass
class SlateOffPolicyEvaluation:
"""Class to conduct slate/ranking OPE with multiple estimators simultaneously.
Parameters
-----------
bandit_feedback: BanditFeedback
Logged bandit data used in OPE of slate/ranking policies.
ope_estimators: List[BaseSlateOffPolicyEstimator]
List of OPE estimators used to evaluate the policy value of evaluation policy.
Estimators must follow the interface of `obp.ope.BaseSlateOffPolicyEstimator`.
Examples
----------
.. code-block:: python
# a case for implementing OPE of the uniform random policy
# using log data generated by a linear behavior policy
>>> from obp.ope import SlateOffPolicyEvaluation, SlateStandardIPS as SIPS
>>> from obp.dataset import (
logistic_reward_function,
linear_behavior_policy_logit,
SyntheticSlateBanditDataset,
)
# (1) Synthetic Data Generation
>>> dataset = SyntheticSlateBanditDataset(
n_unique_action=10,
len_list=3,
dim_context=2,
reward_type="binary",
reward_structure="cascade_additive",
click_model=None,
behavior_policy_function=behavior_policy_function,
base_reward_function=base_reward_function,
)
>>> bandit_feedback = dataset.obtain_batch_bandit_feedback(
n_rounds=1000,
return_pscore_item_position=True
)
>>> bandit_feedback.keys()
dict_keys([
'n_rounds',
'n_unique_action',
'slate_id',
'context',
'action_context',
'action',
'position',
'reward',
'expected_reward_factual',
'pscore_cascade',
'pscore',
'pscore_item_position'
])
# (2) Evaluation Policy Definition (Off-Policy Learning)
>>> random_dataset = dataset = SyntheticSlateBanditDataset(
n_unique_action=10,
len_list=3,
dim_context=2,
reward_type="binary",
reward_structure="cascade_additive",
click_model=None,
behavior_policy_function=None, # set to uniform random
base_reward_function=base_reward_function,
)
>>> random_feedback = random_dataset.obtain_batch_bandit_feedback(
n_rounds=n_rounds_test,
return_pscore_item_position=True,
)
# (3) Off-Policy Evaluation
>>> ope = SlateOffPolicyEvaluation(bandit_feedback=bandit_feedback, ope_estimators=[SIPS(len_list=3)])
>>> estimated_policy_value = ope.estimate_policy_values(
evaluation_policy_pscore=bandit_feedback["pscore"],
evaluation_policy_pscore_item_position=bandit_feedback["pscore_item_position"],
evaluation_policy_pscore_cascade=bandit_feedback["pscore_cascade"]
)
>>> estimated_policy_value
{'sips': 1.894}
"""
bandit_feedback: BanditFeedback
ope_estimators: List[BaseSlateOffPolicyEstimator]
def __post_init__(self) -> None:
"""Initialize class."""
for key_ in [
"slate_id",
"context",
"action",
"reward",
"position",
]:
if key_ not in self.bandit_feedback:
raise RuntimeError(f"Missing key of {key_} in 'bandit_feedback'.")
self.ope_estimators_ = dict()
self.use_cascade_dr = False
for estimator in self.ope_estimators:
self.ope_estimators_[estimator.estimator_name] = estimator
if isinstance(estimator, CascadeDR):
self.use_cascade_dr = True
def _create_estimator_inputs(
self,
evaluation_policy_pscore: Optional[np.ndarray] = None,
evaluation_policy_pscore_item_position: Optional[np.ndarray] = None,
evaluation_policy_pscore_cascade: Optional[np.ndarray] = None,
evaluation_policy_action_dist: Optional[np.ndarray] = None,
q_hat: Optional[np.ndarray] = None,
) -> Dict[str, np.ndarray]:
"""Create input dictionary to estimate policy value by subclasses of `BaseSlateOffPolicyEstimator`"""
if (
evaluation_policy_pscore is None
and evaluation_policy_pscore_item_position is None
and evaluation_policy_pscore_cascade is None
):
raise ValueError(
"one of `evaluation_policy_pscore`, `evaluation_policy_pscore_item_position`, or `evaluation_policy_pscore_cascade` must be given"
)
if self.use_cascade_dr and evaluation_policy_action_dist is None:
raise ValueError(
"`evaluation_policy_action_dist` must be given when using `SlateCascadeDoublyRobust`"
)
if self.use_cascade_dr and q_hat is None:
raise ValueError(
"`q_hat` must be given when using `SlateCascadeDoublyRobust`"
)
estimator_inputs = {
input_: self.bandit_feedback[input_]
for input_ in [
"slate_id",
"action",
"reward",
"position",
"pscore",
"pscore_item_position",
"pscore_cascade",
]
if input_ in self.bandit_feedback
}
estimator_inputs["evaluation_policy_pscore"] = evaluation_policy_pscore
estimator_inputs[
"evaluation_policy_pscore_item_position"
] = evaluation_policy_pscore_item_position
estimator_inputs[
"evaluation_policy_pscore_cascade"
] = evaluation_policy_pscore_cascade
estimator_inputs[
"evaluation_policy_action_dist"
] = evaluation_policy_action_dist
estimator_inputs["q_hat"] = q_hat
return estimator_inputs
def estimate_policy_values(
self,
evaluation_policy_pscore: Optional[np.ndarray] = None,
evaluation_policy_pscore_item_position: Optional[np.ndarray] = None,
evaluation_policy_pscore_cascade: Optional[np.ndarray] = None,
evaluation_policy_action_dist: Optional[np.ndarray] = None,
q_hat: Optional[np.ndarray] = None,
) -> Dict[str, float]:
"""Estimate the policy value of evaluation policy.
Parameters
------------
evaluation_policy_pscore: array-like, shape (<= n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a slate action, i.e., :math:`\\pi_e(a_i|x_i)`.
This parameter must be unique in each slate.
evaluation_policy_pscore_item_position: array-like, shape (<= n_rounds * len_list,)
Marginal probabilities of evaluation policy choosing a particular action at each position (slot),
i.e., :math:`\\pi_e(a_{i}(l) |x_i)`.
evaluation_policy_pscore_cascade: array-like, shape (n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a particular sequence of actions from the top position to the :math:`l`-th position (:math:`a_{1:l}`). This type of action choice probabilities corresponds to the cascade model.
evaluation_policy_action_dist: array-like, shape (n_rounds * len_list * n_unique_action, )
Plackett-luce style action distribution induced by evaluation policy
(action choice probabilities at each slot given previous action choices)
, i.e., :math:`\\pi_e(a_i(l) | x_i, a_i(1), \\ldots, a_i(l-1)) \\forall a_i(l) \\in \\mathcal{A}`.
Required when using `obp.ope.SlateCascadeDoublyRobust`.
q_hat: array-like (n_rounds * len_list * n_unique_actions, )
:math:`\\hat{Q}_l` for all unique actions,
i.e., :math:`\\hat{Q}_{i,l}(x_i, a_i(1), \\ldots, a_i(l-1), a_i(l)) \\forall a_i(l) \\in \\mathcal{A}`.
Required when using `obp.ope.SlateCascadeDoublyRobust`.
Returns
----------
policy_value_dict: Dict[str, float]
Dictionary containing the policy values estimated by OPE estimators.
"""
policy_value_dict = dict()
estimator_inputs = self._create_estimator_inputs(
evaluation_policy_pscore=evaluation_policy_pscore,
evaluation_policy_pscore_item_position=evaluation_policy_pscore_item_position,
evaluation_policy_pscore_cascade=evaluation_policy_pscore_cascade,
evaluation_policy_action_dist=evaluation_policy_action_dist,
q_hat=q_hat,
)
for estimator_name, estimator in self.ope_estimators_.items():
policy_value_dict[estimator_name] = estimator.estimate_policy_value(
**estimator_inputs
)
return policy_value_dict
def estimate_intervals(
self,
evaluation_policy_pscore: Optional[np.ndarray] = None,
evaluation_policy_pscore_item_position: Optional[np.ndarray] = None,
evaluation_policy_pscore_cascade: Optional[np.ndarray] = None,
evaluation_policy_action_dist: Optional[np.ndarray] = None,
q_hat: Optional[np.ndarray] = None,
alpha: float = 0.05,
n_bootstrap_samples: int = 100,
random_state: Optional[int] = None,
) -> Dict[str, Dict[str, float]]:
"""Estimate the confidence intervals of the policy values using bootstrap.
Parameters
------------
evaluation_policy_pscore: array-like, shape (<= n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a slate action, i.e., :math:`\\pi_e(a_i|x_i)`.
This parameter must be unique in each slate.
evaluation_policy_pscore_item_position: array-like, shape (<= n_rounds * len_list,)
Marginal probabilities of evaluation policy choosing a particular action at each position (slot),
i.e., :math:`\\pi_e(a_{i}(l) |x_i)`.
evaluation_policy_pscore_cascade: array-like, shape (n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a particular sequence of actions from the top position to the :math:`l`-th position (:math:`a_{1:l}`). This type of action choice probabilities corresponds to the cascade model.
evaluation_policy_action_dist: array-like, shape (n_rounds * len_list * n_unique_action, )
Plackett-luce style action distribution induced by evaluation policy
(action choice probabilities at each slot given previous action choices)
, i.e., :math:`\\pi_e(a_i(l) | x_i, a_i(1), \\ldots, a_i(l-1)) \\forall a_i(l) \\in \\mathcal{A}`.
q_hat: array-like (n_rounds * len_list * n_unique_actions, )
:math:`\\hat{Q}_l` for all unique actions,
i.e., :math:`\\hat{Q}_{i,l}(x_i, a_i(1), \\ldots, a_i(l-1), a_i(l)) \\forall a_i(l) \\in \\mathcal{A}`.
Required when using `obp.ope.SlateCascadeDoublyRobust`.
alpha: float, default=0.05
Significance level.
n_bootstrap_samples: int, default=100
Number of resampling performed in bootstrap sampling.
random_state: int, default=None
Controls the random seed in bootstrap sampling.
Returns
----------
policy_value_interval_dict: Dict[str, Dict[str, float]]
Dictionary containing confidence intervals of the estimated policy values.
"""
check_confidence_interval_arguments(
alpha=alpha,
n_bootstrap_samples=n_bootstrap_samples,
random_state=random_state,
)
policy_value_interval_dict = dict()
estimator_inputs = self._create_estimator_inputs(
evaluation_policy_pscore=evaluation_policy_pscore,
evaluation_policy_pscore_item_position=evaluation_policy_pscore_item_position,
evaluation_policy_pscore_cascade=evaluation_policy_pscore_cascade,
evaluation_policy_action_dist=evaluation_policy_action_dist,
q_hat=q_hat,
)
for estimator_name, estimator in self.ope_estimators_.items():
policy_value_interval_dict[estimator_name] = estimator.estimate_interval(
**estimator_inputs,
alpha=alpha,
n_bootstrap_samples=n_bootstrap_samples,
random_state=random_state,
)
return policy_value_interval_dict
def summarize_off_policy_estimates(
self,
evaluation_policy_pscore: Optional[np.ndarray] = None,
evaluation_policy_pscore_item_position: Optional[np.ndarray] = None,
evaluation_policy_pscore_cascade: Optional[np.ndarray] = None,
evaluation_policy_action_dist: Optional[np.ndarray] = None,
q_hat: Optional[np.ndarray] = None,
alpha: float = 0.05,
n_bootstrap_samples: int = 100,
random_state: Optional[int] = None,
) -> Tuple[DataFrame, DataFrame]:
"""Summarize the estimated policy values and their confidence intervals estimated by bootstrap.
Parameters
------------
evaluation_policy_pscore: array-like, shape (<= n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a slate action, i.e., :math:`\\pi_e(a_i|x_i)`.
This parameter must be unique in each slate.
evaluation_policy_pscore_item_position: array-like, shape (<= n_rounds * len_list,)
Marginal probabilities of evaluation policy choosing a particular action at each position (slot),
i.e., :math:`\\pi_e(a_{i}(l) |x_i)`.
evaluation_policy_pscore_cascade: array-like, shape (n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a particular sequence of actions from the top position to the :math:`l`-th position (:math:`a_{1:l}`). This type of action choice probabilities corresponds to the cascade model.
evaluation_policy_action_dist: array-like, shape (n_rounds * len_list * n_unique_action, )
Plackett-luce style action distribution induced by evaluation policy
(action choice probabilities at each slot given previous action choices)
, i.e., :math:`\\pi_e(a_i(l) | x_i, a_i(1), \\ldots, a_i(l-1)) \\forall a_i(l) \\in \\mathcal{A}`.
q_hat: array-like (n_rounds * len_list * n_unique_actions, )
:math:`\\hat{Q}_l` for all unique actions,
i.e., :math:`\\hat{Q}_{i,l}(x_i, a_i(1), \\ldots, a_i(l-1), a_i(l)) \\forall a_i(l) \\in \\mathcal{A}`.
Required when using `obp.ope.SlateCascadeDoublyRobust`.
alpha: float, default=0.05
Significance level.
n_bootstrap_samples: int, default=100
Number of resampling performed in bootstrap sampling.
random_state: int, default=None
Controls the random seed in bootstrap sampling.
Returns
----------
(policy_value_df, policy_value_interval_df): Tuple[DataFrame, DataFrame]
Policy values and their confidence intervals estimated by OPE estimators.
"""
policy_value_df = DataFrame(
self.estimate_policy_values(
evaluation_policy_pscore=evaluation_policy_pscore,
evaluation_policy_pscore_item_position=evaluation_policy_pscore_item_position,
evaluation_policy_pscore_cascade=evaluation_policy_pscore_cascade,
evaluation_policy_action_dist=evaluation_policy_action_dist,
q_hat=q_hat,
),
index=["estimated_policy_value"],
)
policy_value_interval_df = DataFrame(
self.estimate_intervals(
evaluation_policy_pscore=evaluation_policy_pscore,
evaluation_policy_pscore_item_position=evaluation_policy_pscore_item_position,
evaluation_policy_pscore_cascade=evaluation_policy_pscore_cascade,
evaluation_policy_action_dist=evaluation_policy_action_dist,
q_hat=q_hat,
alpha=alpha,
n_bootstrap_samples=n_bootstrap_samples,
random_state=random_state,
)
)
policy_value_of_behavior_policy = (
self.bandit_feedback["reward"].sum()
/ np.unique(self.bandit_feedback["slate_id"]).shape[0]
)
policy_value_df = policy_value_df.T
if policy_value_of_behavior_policy <= 0:
logger.warning(
f"Policy value of the behavior policy is {policy_value_of_behavior_policy} (<=0); relative estimated policy value is set to np.nan"
)
policy_value_df["relative_estimated_policy_value"] = np.nan
else:
policy_value_df["relative_estimated_policy_value"] = (
policy_value_df.estimated_policy_value / policy_value_of_behavior_policy
)
return policy_value_df, policy_value_interval_df.T
def visualize_off_policy_estimates(
self,
evaluation_policy_pscore: Optional[np.ndarray] = None,
evaluation_policy_pscore_item_position: Optional[np.ndarray] = None,
evaluation_policy_pscore_cascade: Optional[np.ndarray] = None,
evaluation_policy_action_dist: Optional[np.ndarray] = None,
q_hat: Optional[np.ndarray] = None,
alpha: float = 0.05,
is_relative: bool = False,
n_bootstrap_samples: int = 100,
random_state: Optional[int] = None,
fig_dir: Optional[Path] = None,
fig_name: str = "estimated_policy_value.png",
) -> None:
"""Visualize the estimated policy values.
Parameters
----------
evaluation_policy_pscore: array-like, shape (<= n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a slate action, i.e., :math:`\\pi_e(a_i|x_i)`.
This parameter must be unique in each slate.
evaluation_policy_pscore_item_position: array-like, shape (<= n_rounds * len_list,)
Marginal probabilities of evaluation policy choosing a particular action at each position (slot),
i.e., :math:`\\pi_e(a_{i}(l) |x_i)`.
evaluation_policy_pscore_cascade: array-like, shape (n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a particular sequence of actions from the top position to the :math:`l`-th position (:math:`a_{1:l}`). This type of action choice probabilities corresponds to the cascade model.
evaluation_policy_action_dist: array-like, shape (n_rounds * len_list * n_unique_action, )
Plackett-luce style action distribution induced by evaluation policy
(action choice probabilities at each slot given previous action choices)
, i.e., :math:`\\pi_e(a_i(l) | x_i, a_i(1), \\ldots, a_i(l-1)) \\forall a_i(l) \\in \\mathcal{A}`.
q_hat: array-like (n_rounds * len_list * n_unique_actions, )
:math:`\\hat{Q}_l` for all unique actions,
i.e., :math:`\\hat{Q}_{i,l}(x_i, a_i(1), \\ldots, a_i(l-1), a_i(l)) \\forall a_i(l) \\in \\mathcal{A}`.
Required when using `obp.ope.SlateCascadeDoublyRobust`.
alpha: float, default=0.05
Significance level.
n_bootstrap_samples: int, default=100
Number of resampling performed in bootstrap sampling.
random_state: int, default=None
Controls the random seed in bootstrap sampling.
is_relative: bool, default=False,
If True, the method visualizes the estimated policy values of evaluation policy
relative to the ground-truth policy value of behavior policy.
fig_dir: Path, default=None
Path to store the bar figure.
If None, the figure will not be saved.
fig_name: str, default="estimated_policy_value.png"
Name of the bar figure.
"""
if fig_dir is not None:
assert isinstance(fig_dir, Path), "`fig_dir` must be a Path"
if fig_name is not None:
assert isinstance(fig_name, str), "`fig_dir` must be a string"
_, estimated_interval_a = self.summarize_off_policy_estimates(
evaluation_policy_pscore=evaluation_policy_pscore,
evaluation_policy_pscore_item_position=evaluation_policy_pscore_item_position,
evaluation_policy_pscore_cascade=evaluation_policy_pscore_cascade,
evaluation_policy_action_dist=evaluation_policy_action_dist,
q_hat=q_hat,
alpha=alpha,
n_bootstrap_samples=n_bootstrap_samples,
random_state=random_state,
)
estimated_interval_a["errbar_length"] = (
estimated_interval_a.drop("mean", axis=1).diff(axis=1).iloc[:, -1].abs()
)
if is_relative:
estimated_interval_a /= (
self.bandit_feedback["reward"].sum()
/ np.unique(self.bandit_feedback["slate_id"]).shape[0]
)
plt.style.use("ggplot")
fig, ax = plt.subplots(figsize=(8, 6))
sns.barplot(
data=estimated_interval_a[["mean"]].reset_index(),
x="index",
y="mean",
ax=ax,
ci=None,
)
plt.xlabel("OPE Estimators", fontsize=25)
plt.ylabel(
f"Estimated Policy Value (± {np.int32(100*(1 - alpha))}% CI)", fontsize=20
)
plt.yticks(fontsize=15)
plt.xticks(fontsize=25 - 2 * len(self.ope_estimators))
ax.errorbar(
np.arange(estimated_interval_a.shape[0]),
estimated_interval_a["mean"],
yerr=estimated_interval_a["errbar_length"],
fmt="o",
color="black",
)
if fig_dir:
fig.savefig(str(fig_dir / fig_name))
def evaluate_performance_of_estimators(
self,
ground_truth_policy_value: float,
evaluation_policy_pscore: Optional[np.ndarray] = None,
evaluation_policy_pscore_item_position: Optional[np.ndarray] = None,
evaluation_policy_pscore_cascade: Optional[np.ndarray] = None,
evaluation_policy_action_dist: Optional[np.ndarray] = None,
q_hat: Optional[np.ndarray] = None,
metric: str = "se",
) -> Dict[str, float]:
"""Evaluate the accuracy of OPE estimators.
Note
------
Evaluate the estimation performance of OPE estimators with relative estimation error (relative-EE) or squared error (SE):
.. math ::
\\text{Relative-EE} (\\hat{V}; \\mathcal{D}) = \\left| \\frac{\\hat{V}(\\pi; \\mathcal{D}) - V(\\pi)}{V(\\pi)} \\right|,
.. math ::
\\text{SE} (\\hat{V}; \\mathcal{D}) = \\left(\\hat{V}(\\pi; \\mathcal{D}) - V(\\pi) \\right)^2,
where :math:`V({\\pi})` is the ground-truth policy value of the evalation policy :math:`\\pi_e` (often estimated using on-policy estimation).
:math:`\\hat{V}(\\pi; \\mathcal{D})` is the policy value estimated by an OPE estimator :math:`\\hat{V}` and logged bandit feedback :math:`\\mathcal{D}`.
Parameters
----------
ground_truth_policy_value: float
Ground_truth policy value of evaluation policy, i.e., :math:`V(\\pi)`.
With Open Bandit Dataset, we use an on-policy estimate of the policy value as its ground-truth.
evaluation_policy_pscore: array-like, shape (<= n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a slate action, i.e., :math:`\\pi_e(a_i|x_i)`.
This parameter must be unique in each slate.
evaluation_policy_pscore_item_position: array-like, shape (<= n_rounds * len_list,)
Marginal probabilities of evaluation policy choosing a particular action at each position (slot),
i.e., :math:`\\pi_e(a_{i}(l) |x_i)`.
evaluation_policy_pscore_cascade: array-like, shape (n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a particular sequence of actions from the top position to the :math:`l`-th position (:math:`a_{1:l}`). This type of action choice probabilities corresponds to the cascade model.
evaluation_policy_action_dist: array-like, shape (n_rounds * len_list * n_unique_action, )
Plackett-luce style action distribution induced by evaluation policy
(action choice probabilities at each slot given previous action choices)
, i.e., :math:`\\pi_e(a_i(l) | x_i, a_i(1), \\ldots, a_i(l-1)) \\forall a_i(l) \\in \\mathcal{A}`.
q_hat: array-like (n_rounds * len_list * n_unique_actions, )
:math:`\\hat{Q}_l` for all unique actions,
i.e., :math:`\\hat{Q}_{i,l}(x_i, a_i(1), \\ldots, a_i(l-1), a_i(l)) \\forall a_i(l) \\in \\mathcal{A}`.
Required when using `obp.ope.SlateCascadeDoublyRobust`.
metric: str, default="se"
Evaluation metric used to evaluate and compare the estimation performance of OPE estimators.
Must be either "relative-ee" or "se".
Returns
----------
eval_metric_ope_dict: Dict[str, float]
Dictionary containing the value of evaluation metric for the estimation performance of OPE estimators.
"""
check_scalar(ground_truth_policy_value, "ground_truth_policy_value", float)
if metric not in ["relative-ee", "se"]:
raise ValueError(
f"`metric` must be either 'relative-ee' or 'se', but {metric} is given"
)
if metric == "relative-ee" and ground_truth_policy_value == 0.0:
raise ValueError(
"`ground_truth_policy_value` must be non-zero when metric is relative-ee"
)
eval_metric_ope_dict = dict()
estimator_inputs = self._create_estimator_inputs(
evaluation_policy_pscore=evaluation_policy_pscore,
evaluation_policy_pscore_item_position=evaluation_policy_pscore_item_position,
evaluation_policy_pscore_cascade=evaluation_policy_pscore_cascade,
evaluation_policy_action_dist=evaluation_policy_action_dist,
q_hat=q_hat,
)
for estimator_name, estimator in self.ope_estimators_.items():
estimated_policy_value = estimator.estimate_policy_value(**estimator_inputs)
if metric == "relative-ee":
relative_ee_ = estimated_policy_value - ground_truth_policy_value
relative_ee_ /= ground_truth_policy_value
eval_metric_ope_dict[estimator_name] = np.abs(relative_ee_)
elif metric == "se":
se_ = (estimated_policy_value - ground_truth_policy_value) ** 2
eval_metric_ope_dict[estimator_name] = se_
return eval_metric_ope_dict
def summarize_estimators_comparison(
self,
ground_truth_policy_value: float,
evaluation_policy_pscore: Optional[np.ndarray] = None,
evaluation_policy_pscore_item_position: Optional[np.ndarray] = None,
evaluation_policy_pscore_cascade: Optional[np.ndarray] = None,
evaluation_policy_action_dist: Optional[np.ndarray] = None,
q_hat: Optional[np.ndarray] = None,
metric: str = "se",
) -> DataFrame:
"""Summarize the performance comparison among OPE estimators.
Parameters
----------
ground_truth_policy_value: float
Ground_truth policy value of evaluation policy, i.e., :math:`V(\\pi)`.
With Open Bandit Dataset, we use an on-policy estimate of the policy value as ground-truth.
evaluation_policy_pscore: array-like, shape (<= n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a slate action, i.e., :math:`\\pi_e(a_i|x_i)`.
This parameter must be unique in each slate.
evaluation_policy_pscore_item_position: array-like, shape (<= n_rounds * len_list,)
Marginal probabilities of evaluation policy choosing a particular action at each position (slot),
i.e., :math:`\\pi_e(a_{i}(l) |x_i)`.
evaluation_policy_pscore_cascade: array-like, shape (n_rounds * len_list,)
Joint probabilities of evaluation policy choosing a particular sequence of actions from the top position to the :math:`l`-th position (:math:`a_{1:l}`). This type of action choice probabilities corresponds to the cascade model.
evaluation_policy_action_dist: array-like, shape (n_rounds * len_list * n_unique_action, )
Plackett-luce style action distribution induced by evaluation policy
(action choice probabilities at each slot given previous action choices)
, i.e., :math:`\\pi_e(a_i(l) | x_i, a_i(1), \\ldots, a_i(l-1)) \\forall a_i(l) \\in \\mathcal{A}`.
q_hat: array-like (n_rounds * len_list * n_unique_actions, )
:math:`\\hat{Q}_l` for all unique actions,
i.e., :math:`\\hat{Q}_{i,l}(x_i, a_i(1), \\ldots, a_i(l-1), a_i(l)) \\forall a_i(l) \\in \\mathcal{A}`.
Required when using `obp.ope.SlateCascadeDoublyRobust`.
metric: str, default="se"
Evaluation metric used to evaluate and compare the estimation performance of OPE estimators.
Must be either "relative-ee" or "se".
Returns
----------
eval_metric_ope_df: DataFrame
Results of performance comparison among OPE estimators.
"""
eval_metric_ope_df = DataFrame(
self.evaluate_performance_of_estimators(
ground_truth_policy_value=ground_truth_policy_value,
evaluation_policy_pscore=evaluation_policy_pscore,
evaluation_policy_pscore_item_position=evaluation_policy_pscore_item_position,
evaluation_policy_pscore_cascade=evaluation_policy_pscore_cascade,
evaluation_policy_action_dist=evaluation_policy_action_dist,
q_hat=q_hat,
metric=metric,
),
index=[metric],
)
return eval_metric_ope_df.T