forked from st-tech/zr-obp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
synthetic_slate.py
1550 lines (1378 loc) · 68.8 KB
/
synthetic_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
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.
"""Class for Generating Synthetic Logged Bandit Data for Slate/Ranking Policies."""
from dataclasses import dataclass
from itertools import permutations
from itertools import product
from typing import Callable
from typing import Optional
from typing import Tuple
from typing import Union
import numpy as np
from scipy.special import logit
from scipy.special import perm
from scipy.stats import truncnorm
from sklearn.utils import check_random_state
from sklearn.utils import check_scalar
from tqdm import tqdm
from ..types import BanditFeedback
from ..utils import check_array
from ..utils import sigmoid
from ..utils import softmax
from .base import BaseBanditDataset
@dataclass
class SyntheticSlateBanditDataset(BaseBanditDataset):
"""Class for synthesizing slate bandit dataset.
Note
-----
By calling the `obtain_batch_bandit_feedback` method several times,
we can resample logged bandit data from the same data generating distribution.
This can be used to estimate confidence intervals of the performances of Slate OPE estimators.
Parameters
-----------
n_unique_action: int (>= len_list)
Number of unique actions.
len_list: int (> 1)
Length of a list/ranking of actions, slate size.
dim_context: int, default=1
Number of dimensions of context vectors.
reward_type: str, default='binary'
Type of reward variable, which must be either 'binary' or 'continuous'.
When 'binary', rewards are sampled from the Bernoulli distribution.
When 'continuous', rewards are sampled from the truncated Normal distribution with `scale=1`.
The mean parameter of the reward distribution is determined by the `reward_function`.
reward_structure: str, default='cascade_additive'
Specify which reward structure to use to define the expected rewards. Must be one of the following.
- 'cascade_additive'
- 'cascade_decay'
- 'independent'
- 'standard_additive'
- 'standard_decay'
The expected reward function is defined as follows (:math:`f` is a base reward function of each item-position, :math:`g` is a transform function, and :math:`h` is a decay function):
'cascade_additive': :math:`q_k(x, a) = g(g^{-1}(f(x, a(k))) + \\sum_{j < k} W(a(k), a(j)))`.
'cascade_decay': :math:`q_k(x, a) = g(g^{-1}(f(x, a(k))) - \\sum_{j < k} g^{-1}(f(x, a(j))) / h(|k-j|))`.
'independent': :math:`q_k(x, a) = f(x, a(k))`
'standard_additive': :math:`q_k(x, a) = g(g^{-1}(f(x, a(k))) + \\sum_{j \\neq k} W(a(k), a(j)))`.
'standard_decay': :math:`q_k(x, a) = g(g^{-1}(f(x, a(k))) - \\sum_{j \\neq k} g^{-1}(f(x, a(j))) / h(|k-j|))`.
When `reward_type` is 'continuous', transform function is the identity function.
When `reward_type` is 'binary', transform function is the logit function.
See the experiment section of Kiyohara et al.(2022) for details.
decay_function: str, default='exponential'
Specify the decay function used to define the expected reward, which must be one of 'exponential' or 'inverse'.
Decay function is used when `reward_structure`='cascade_decay' or `reward_structure`='standard_decay'.
Discount rate is defined as follows (:math:`k` and :math:`j` are positions of the two slots).
'exponential': :math:`h(|k-j|) = \\exp(-|k-j|)`.
'inverse': :math:`h(|k-j|) = \\frac{1}{|k-j|+1})`.
See the experiment section of Kiyohara et al.(2022) for details.
click_model: str, default=None
Specify the click model used to define the expected reward, which must be one of None, 'pbm', or 'cascade'.
When None, no click model is applied when defining the expected reward for each slot in a ranking.
When 'pbm', the expected reward will be modifed based on the position-based model.
When 'cascade', the expected reward will be modifed based on the cascade model.
Note that these click models are not applicable to 'continuous' rewards.
eta: float, default=1.0
A hyperparameter to define the click model to generate the data.
When click_model='pbm', `eta` defines the examination probabilities of the position-based model.
For example, when `eta`=0.5, the examination probability at position `k` is :math:`\\theta (k) = (1/k)^{0.5}`.
When click_model='cascade', `eta` defines the position-dependent attractiveness parameters of the dependent click model (an extension of the cascade model).
For example, when `eta`=0.5, the position-dependent attractiveness parameter at position `k` is :math:`\\alpha (k) = (1/k)^{0.5}`.
When `eta` is very large, the click model induced is close to the vanilla cascade model.
base_reward_function: Callable[[np.ndarray, np.ndarray], np.ndarray], default=None
Function defining the expected reward function for each given action-context pair,
i.e., :math:`q: \\mathcal{X} \\times \\mathcal{A} \\rightarrow \\mathbb{R}`.
If None, context **independent** expected rewards will be
sampled from the uniform distribution automatically.
behavior_policy_function: Callable[[np.ndarray, np.ndarray], np.ndarray], default=None
Function generating logit values for each action in the action space,
i.e., :math:`\\f: \\mathcal{X} \\rightarrow \\mathbb{R}^{\\mathcal{A}}`.
If None, context **independent** uniform distribution will be used (uniform behavior policy).
is_factorizable: bool
Whether to use factorizable evaluation policy (which choose slot actions independently).
Note that a factorizable policy can choose the same action more than twice in a slate.
In contrast, a non-factorizable policy chooses a slate action without any duplicates among slots.
When `n_unique_action` and `len_list` are large, a factorizable policy should be used due to computation time.
random_state: int, default=12345
Controls the random seed in sampling synthetic slate bandit dataset.
dataset_name: str, default='synthetic_slate_bandit_dataset'
Name of the dataset.
----------
.. code-block:: python
>>> from obp.dataset import (
logistic_reward_function,
linear_behavior_policy_logit,
SyntheticSlateBanditDataset,
)
# generate synthetic contextual bandit feedback with 10 actions.
>>> dataset = SyntheticSlateBanditDataset(
n_unique_action=10,
dim_context=5,
len_list=3,
base_reward_function=logistic_reward_function,
behavior_policy_function=linear_behavior_policy_logit,
reward_type='binary',
reward_structure='cascade_additive',
click_model='cascade',
random_state=12345
)
>>> bandit_feedback = dataset.obtain_batch_bandit_feedback(
n_rounds=5, return_pscore_item_position=True
)
>>> bandit_feedback
{
'n_rounds': 5,
'n_unique_action': 10,
'slate_id': array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]),
'context': array([[-0.20470766, 0.47894334, -0.51943872, -0.5557303 , 1.96578057],
[ 1.39340583, 0.09290788, 0.28174615, 0.76902257, 1.24643474],
[ 1.00718936, -1.29622111, 0.27499163, 0.22891288, 1.35291684],
[ 0.88642934, -2.00163731, -0.37184254, 1.66902531, -0.43856974],
[-0.53974145, 0.47698501, 3.24894392, -1.02122752, -0.5770873 ]]),
'action_context': array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]]),
'action': array([8, 6, 5, 4, 7, 0, 1, 3, 5, 4, 6, 1, 4, 1, 7]),
'position': array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]),
'reward': array([1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0]),
'expected_reward_factual': array([0.5 , 0.73105858, 0.5 , 0.88079708, 0.88079708,
0.88079708, 0.5 , 0.73105858, 0.5 , 0.5 ,
0.26894142, 0.5 , 0.73105858, 0.73105858, 0.5 ]),
'pscore_cascade': array([0.05982646, 0.00895036, 0.00127176, 0.10339675, 0.00625482,
0.00072447, 0.14110696, 0.01868618, 0.00284884, 0.10339675,
0.01622041, 0.00302774, 0.10339675, 0.01627253, 0.00116824]),
'pscore': array([0.00127176, 0.00127176, 0.00127176, 0.00072447, 0.00072447,
0.00072447, 0.00284884, 0.00284884, 0.00284884, 0.00302774,
0.00302774, 0.00302774, 0.00116824, 0.00116824, 0.00116824]),
'pscore_item_position': array([0.19068462, 0.40385939, 0.33855573, 0.31231088, 0.40385939,
0.2969341 , 0.40489767, 0.31220474, 0.3388982 , 0.31231088,
0.33855573, 0.40489767, 0.31231088, 0.40489767, 0.33855573])
}
References
------------
Shuai Li, Yasin Abbasi-Yadkori, Branislav Kveton, S. Muthukrishnan, Vishwa Vinay, Zheng Wen.
"Offline Evaluation of Ranking Policies with Click Models.", 2018.
James McInerney, Brian Brost, Praveen Chandar, Rishabh Mehrotra, and Benjamin Carterette.
"Counterfactual Evaluation of Slate Recommendations with Sequential Reward Interactions.", 2020.
Haruka Kiyohara, Yuta Saito, Tatsuya Matsuhiro, Yusuke Narita, Nobuyuki Shimizu, Yasuo Yamamoto.
"Doubly Robust Off-Policy Evaluation for Ranking Policies under the Cascade Behavior Model.", 2022.
"""
n_unique_action: int
len_list: int
dim_context: int = 1
reward_type: str = "binary"
reward_structure: str = "cascade_additive"
decay_function: str = "exponential"
click_model: Optional[str] = None
eta: float = 1.0
base_reward_function: Optional[
Callable[
[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray], np.ndarray
]
] = None
behavior_policy_function: Optional[
Callable[[np.ndarray, np.ndarray], np.ndarray]
] = None
is_factorizable: bool = False
random_state: int = 12345
dataset_name: str = "synthetic_slate_bandit_dataset"
def __post_init__(self) -> None:
"""Initialize Class."""
check_scalar(self.n_unique_action, "n_unique_action", int, min_val=2)
if self.is_factorizable:
max_len_list = None
else:
max_len_list = self.n_unique_action
check_scalar(self.len_list, "len_list", int, min_val=2, max_val=max_len_list)
check_scalar(self.dim_context, "dim_context", int, min_val=1)
self.random_ = check_random_state(self.random_state)
if self.reward_type not in [
"binary",
"continuous",
]:
raise ValueError(
f"`reward_type` must be either 'binary' or 'continuous', but {self.reward_type} is given."
)
if self.reward_structure not in [
"cascade_additive",
"cascade_decay",
"independent",
"standard_additive",
"standard_decay",
]:
raise ValueError(
f"`reward_structure` must be one of 'cascade_additive', 'cascade_decay', 'independent', 'standard_additive', or 'standard_decay', but {self.reward_structure} is given."
)
if self.decay_function not in ["exponential", "inverse"]:
raise ValueError(
f"`decay_function` must be either 'exponential' or 'inverse', but {self.decay_function} is given"
)
if self.click_model not in ["cascade", "pbm", None]:
raise ValueError(
f"`click_model` must be one of 'cascade', 'pbm', or None, but {self.click_model} is given."
)
# set exam_weight (slot-level examination probability).
# When click_model is 'pbm', exam_weight is :math:`(1 / k)^{\\eta}`, where :math:`k` is the position.
if self.click_model == "pbm":
check_scalar(self.eta, name="eta", target_type=float, min_val=0.0)
self.exam_weight = (1.0 / np.arange(1, self.len_list + 1)) ** self.eta
self.attractiveness = np.ones(self.len_list, dtype=float)
elif self.click_model == "cascade":
check_scalar(self.eta, name="eta", target_type=float, min_val=0.0)
self.attractiveness = (1.0 / np.arange(1, self.len_list + 1)) ** self.eta
self.exam_weight = np.ones(self.len_list, dtype=float)
else:
self.attractiveness = np.ones(self.len_list, dtype=float)
self.exam_weight = np.ones(self.len_list, dtype=float)
if self.click_model is not None and self.reward_type == "continuous":
raise ValueError(
"continuous rewards cannot be used when `click_model` is given"
)
if self.base_reward_function is not None:
self.reward_function = action_interaction_reward_function
if self.reward_structure in ["cascade_additive", "standard_additive"]:
# generate additive action interaction weight matrix of (n_unique_action, n_unique_action)
self.action_interaction_weight_matrix = generate_symmetric_matrix(
n_unique_action=self.n_unique_action, random_state=self.random_state
)
else:
# set decay function
if self.decay_function == "exponential":
self.decay_function = exponential_decay_function
else: # "inverse"
self.decay_function = inverse_decay_function
# generate decay action interaction weight matrix of (len_list, len_list)
if self.reward_structure == "standard_decay":
self.action_interaction_weight_matrix = (
self.obtain_standard_decay_action_interaction_weight_matrix(
self.len_list
)
)
elif self.reward_structure == "cascade_decay":
self.action_interaction_weight_matrix = (
self.obtain_cascade_decay_action_interaction_weight_matrix(
self.len_list
)
)
else:
self.action_interaction_weight_matrix = np.zeros(
(self.len_list, self.len_list)
)
if self.behavior_policy_function is None:
self.uniform_behavior_policy = (
np.ones(self.n_unique_action) / self.n_unique_action
)
if self.reward_type == "continuous":
self.reward_min = 0
self.reward_max = 1e10
self.reward_std = 1.0
# one-hot encoding characterizing each action
self.action_context = np.eye(self.n_unique_action, dtype=int)
def obtain_standard_decay_action_interaction_weight_matrix(
self,
len_list,
) -> np.ndarray:
"""Obtain an action interaction weight matrix for standard decay reward structure (symmetric matrix)"""
action_interaction_weight_matrix = np.identity(len_list)
for pos_ in np.arange(len_list):
action_interaction_weight_matrix[:, pos_] = -self.decay_function(
np.abs(np.arange(len_list) - pos_)
)
action_interaction_weight_matrix[pos_, pos_] = 0
return action_interaction_weight_matrix
def obtain_cascade_decay_action_interaction_weight_matrix(
self,
len_list,
) -> np.ndarray:
"""Obtain an action interaction weight matrix for cascade decay reward structure (upper triangular matrix)"""
action_interaction_weight_matrix = np.identity(len_list)
for pos_ in np.arange(len_list):
action_interaction_weight_matrix[:, pos_] = -self.decay_function(
np.abs(np.arange(len_list) - pos_)
)
for pos_2 in np.arange(len_list):
if pos_ <= pos_2:
action_interaction_weight_matrix[pos_2, pos_] = 0
return action_interaction_weight_matrix
def _calc_pscore_given_policy_logit(
self, all_slate_actions: np.ndarray, policy_logit_i_: np.ndarray
) -> np.ndarray:
"""Calculate the propensity score of all possible slate actions given a particular policy_logit.
Parameters
------------
all_slate_actions: array-like, (n_action, len_list)
All possible slate actions.
policy_logit_i_: array-like, (n_unique_action, )
Logit values given context (:math:`x`), which defines the distribution over actions of the policy.
Returns
------------
pscores: array-like, (n_action, )
Propensity scores of all slate actions.
"""
n_actions = len(all_slate_actions)
unique_action_set_2d = np.tile(np.arange(self.n_unique_action), (n_actions, 1))
pscores = np.ones(n_actions)
for pos_ in np.arange(self.len_list):
action_index = np.where(
unique_action_set_2d == all_slate_actions[:, pos_][:, np.newaxis]
)[1]
pscores *= softmax(policy_logit_i_[unique_action_set_2d])[
np.arange(n_actions), action_index
]
# delete actions
if pos_ + 1 != self.len_list:
mask = np.ones((n_actions, self.n_unique_action - pos_))
mask[np.arange(n_actions), action_index] = 0
unique_action_set_2d = unique_action_set_2d[mask.astype(bool)].reshape(
(-1, self.n_unique_action - pos_ - 1)
)
return pscores
def _calc_pscore_given_policy_softmax(
self, all_slate_actions: np.ndarray, policy_softmax_i_: np.ndarray
) -> np.ndarray:
"""Calculate the propensity score of all possible slate actions given a particular policy_softmax.
Parameters
------------
all_slate_actions: array-like, (n_action, len_list)
All possible slate actions.
policy_softmax_i_: array-like, (n_unique_action, )
Policy softmax values given context (:math:`x`).
Returns
------------
pscores: array-like, (n_action, )
Propensity scores of all slate actions.
"""
n_actions = len(all_slate_actions)
unique_action_set_2d = np.tile(np.arange(self.n_unique_action), (n_actions, 1))
pscores = np.ones(n_actions)
for pos_ in np.arange(self.len_list):
action_index = np.where(
unique_action_set_2d == all_slate_actions[:, pos_][:, np.newaxis]
)[1]
score_ = policy_softmax_i_[unique_action_set_2d]
pscores *= np.divide(score_, score_.sum(axis=1, keepdims=True))[
np.arange(n_actions), action_index
]
# delete actions
if pos_ + 1 != self.len_list:
mask = np.ones((n_actions, self.n_unique_action - pos_))
mask[np.arange(n_actions), action_index] = 0
unique_action_set_2d = unique_action_set_2d[mask.astype(bool)].reshape(
(-1, self.n_unique_action - pos_ - 1)
)
return pscores
def obtain_pscore_given_evaluation_policy_logit(
self,
action: np.ndarray,
evaluation_policy_logit_: np.ndarray,
return_pscore_item_position: bool = True,
clip_logit_value: Optional[float] = None,
):
"""Calculate the propensity score given particular logit values to define the evaluation policy.
Parameters
------------
action: array-like, (n_rounds * len_list, )
Action chosen by the behavior policy.
evaluation_policy_logit_: array-like, (n_rounds, n_unique_action)
Logit values to define the evaluation policy.
return_pscore_item_position: bool, default=True
Whether to compute `pscore_item_position` and include it in the logged data.
When `n_actions` and `len_list` are large, `return_pscore_item_position`=True can lead to a long computation time.
clip_logit_value: Optional[float], default=None
A float parameter used to clip logit values (<= `700.`).
When None, clipping is not applied to softmax values when obtaining `pscore_item_position`.
When a float value is given, logit values are clipped when calculating softmax values.
When `n_actions` and `len_list` are large, `clip_logit_value`=None can lead to a long computation time.
"""
check_array(array=action, name="action", expected_dim=1)
check_array(
array=evaluation_policy_logit_,
name="evaluation_policy_logit_",
expected_dim=2,
)
if (
len(action) / self.len_list != len(evaluation_policy_logit_)
or evaluation_policy_logit_.shape[1] != self.n_unique_action
):
raise ValueError(
"the shape of `action` and `evaluation_policy_logit_` must be (n_rounds * len_list, )"
"and (n_rounds, n_unique_action) respectively"
)
n_rounds = action.reshape((-1, self.len_list)).shape[0]
pscore_cascade = np.zeros(n_rounds * self.len_list)
pscore = np.zeros(n_rounds * self.len_list)
if return_pscore_item_position:
pscore_item_position = np.zeros(n_rounds * self.len_list)
if not self.is_factorizable:
enumerated_slate_actions = [
_
for _ in permutations(
np.arange(self.n_unique_action), self.len_list
)
]
enumerated_slate_actions = np.array(enumerated_slate_actions)
else:
pscore_item_position = None
if return_pscore_item_position and clip_logit_value is not None:
check_scalar(
clip_logit_value,
name="clip_logit_value",
target_type=(float),
max_val=700.0,
)
evaluation_policy_softmax_ = np.exp(
np.minimum(evaluation_policy_logit_, clip_logit_value)
)
for i in tqdm(
np.arange(n_rounds),
desc="[obtain_pscore_given_evaluation_policy_logit]",
total=n_rounds,
):
unique_action_set = np.arange(self.n_unique_action)
score_ = softmax(evaluation_policy_logit_[i : i + 1])[0]
pscore_i = 1.0
for pos_ in np.arange(self.len_list):
action_ = action[i * self.len_list + pos_]
action_index_ = np.where(unique_action_set == action_)[0][0]
# calculate joint pscore
pscore_i *= score_[action_index_]
pscore_cascade[i * self.len_list + pos_] = pscore_i
# update the pscore given the remaining items for nonfactorizable policy
if not self.is_factorizable and pos_ != self.len_list - 1:
unique_action_set = np.delete(
unique_action_set, unique_action_set == action_
)
score_ = softmax(
evaluation_policy_logit_[i : i + 1, unique_action_set]
)[0]
# calculate pscore_item_position
if return_pscore_item_position:
if pos_ == 0:
pscore_item_pos_i_l = pscore_i
elif self.is_factorizable:
pscore_item_pos_i_l = score_[action_index_]
else:
if isinstance(clip_logit_value, float):
pscores = self._calc_pscore_given_policy_softmax(
all_slate_actions=enumerated_slate_actions,
policy_softmax_i_=evaluation_policy_softmax_[i],
)
else:
pscores = self._calc_pscore_given_policy_logit(
all_slate_actions=enumerated_slate_actions,
policy_logit_i_=evaluation_policy_logit_[i],
)
pscore_item_pos_i_l = pscores[
enumerated_slate_actions[:, pos_] == action_
].sum()
pscore_item_position[i * self.len_list + pos_] = pscore_item_pos_i_l
# impute joint pscore
start_idx = i * self.len_list
end_idx = start_idx + self.len_list
pscore[start_idx:end_idx] = pscore_i
return pscore, pscore_item_position, pscore_cascade
def sample_action_and_obtain_pscore(
self,
behavior_policy_logit_: np.ndarray,
n_rounds: int,
return_pscore_item_position: bool = True,
clip_logit_value: Optional[float] = None,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, Optional[np.ndarray]]:
"""Sample action and obtain the three variants of the propensity scores.
Parameters
------------
behavior_policy_logit_: array-like, shape (n_rounds, n_actions)
Logit values given context (:math:`x`).
n_rounds: int
Data size of synthetic logged data.
return_pscore_item_position: bool, default=True
Whether to compute `pscore_item_position` and include it in the logged data.
When `n_actions` and `len_list` are large, `return_pscore_item_position`=True can lead to a long computation time.
clip_logit_value: Optional[float], default=None
A float parameter used to clip logit values (<= `700.`).
When None, clipping is not applied to softmax values when obtaining `pscore_item_position`.
When a float value is given, logit values are clipped when calculating softmax values.
When `n_actions` and `len_list` are large, `clip_logit_value`=None can lead to a long computation time.
Returns
----------
action: array-like, shape (n_rounds * len_list)
Actions sampled by the behavior policy.
Actions sampled within slate `i` is stored in `action[`i` * `len_list`: (`i + 1`) * `len_list`]`.
pscore: array-like, shape (n_unique_action * len_list)
Probabilities of choosing the slate actions given context (:math:`x`),
i.e., :math:`\\pi(a_{i,1}, a_{i,2}, \\ldots, a_{i,L} | x_{i} )`.
pscore_item_position: array-like, shape (n_unique_action * len_list)
Probabilities of choosing the action of the :math:`l`-th slot given context (:math:`x`),
i.e., :math:`\\pi(a_{i,l} | x_{i} )`.
pscore_cascade: array-like, shape (n_unique_action * len_list)
Probabilities of choosing the actions of the top :math:`l` slots given context (:math:`x`),
i.e., :math:`\\pi(a_{i,1}, a_{i,2}, \\ldots, a_{i,l} | x_{i} )`.
"""
action = np.zeros(n_rounds * self.len_list, dtype=int)
pscore_cascade = np.zeros(n_rounds * self.len_list)
pscore = np.zeros(n_rounds * self.len_list)
if return_pscore_item_position:
pscore_item_position = np.zeros(n_rounds * self.len_list)
if not self.is_factorizable and self.behavior_policy_function is not None:
enumerated_slate_actions = [
_
for _ in permutations(
np.arange(self.n_unique_action), self.len_list
)
]
enumerated_slate_actions = np.array(enumerated_slate_actions)
else:
pscore_item_position = None
if return_pscore_item_position and clip_logit_value is not None:
check_scalar(
clip_logit_value,
name="clip_logit_value",
target_type=(float),
max_val=700.0,
)
behavior_policy_softmax_ = np.exp(
np.minimum(behavior_policy_logit_, clip_logit_value)
)
for i in tqdm(
np.arange(n_rounds),
desc="[sample_action_and_obtain_pscore]",
total=n_rounds,
):
unique_action_set = np.arange(self.n_unique_action)
score_ = softmax(behavior_policy_logit_[i : i + 1, unique_action_set])[0]
pscore_i = 1.0
for pos_ in np.arange(self.len_list):
sampled_action = self.random_.choice(
unique_action_set, p=score_, replace=False
)
action[i * self.len_list + pos_] = sampled_action
sampled_action_index = np.where(unique_action_set == sampled_action)[0][
0
]
# calculate joint pscore
pscore_i *= score_[sampled_action_index]
pscore_cascade[i * self.len_list + pos_] = pscore_i
# update the pscore given the remaining items for nonfactorizable behavior policy
if not self.is_factorizable and pos_ != self.len_list - 1:
unique_action_set = np.delete(
unique_action_set, unique_action_set == sampled_action
)
score_ = softmax(
behavior_policy_logit_[i : i + 1, unique_action_set]
)[0]
# calculate pscore_item_position
if return_pscore_item_position:
if self.behavior_policy_function is None: # uniform random
pscore_item_pos_i_l = 1 / self.n_unique_action
elif self.is_factorizable:
pscore_item_pos_i_l = score_[sampled_action_index]
elif pos_ == 0:
pscore_item_pos_i_l = pscore_i
else:
if isinstance(clip_logit_value, float):
pscores = self._calc_pscore_given_policy_softmax(
all_slate_actions=enumerated_slate_actions,
policy_softmax_i_=behavior_policy_softmax_[i],
)
else:
pscores = self._calc_pscore_given_policy_logit(
all_slate_actions=enumerated_slate_actions,
policy_logit_i_=behavior_policy_logit_[i],
)
pscore_item_pos_i_l = pscores[
enumerated_slate_actions[:, pos_] == sampled_action
].sum()
pscore_item_position[i * self.len_list + pos_] = pscore_item_pos_i_l
# impute joint pscore
start_idx = i * self.len_list
end_idx = start_idx + self.len_list
pscore[start_idx:end_idx] = pscore_i
return action, pscore_cascade, pscore, pscore_item_position
def sample_contextfree_expected_reward(
self, random_state: Optional[int] = None
) -> np.ndarray:
"""Define context independent expected rewards for each action and slot.
Parameters
-----------
random_state: int, default=None
Controls the random seed in sampling dataset.
"""
random_ = check_random_state(random_state)
return random_.uniform(size=(self.n_unique_action, self.len_list))
def sample_reward_given_expected_reward(
self, expected_reward_factual: np.ndarray
) -> np.ndarray:
"""Sample reward variables given actions observed at each slot.
Parameters
------------
expected_reward_factual: array-like, shape (n_rounds, len_list)
Expected rewards given observed actions and contexts.
Returns
----------
reward: array-like, shape (n_rounds, len_list)
Sampled rewards.
"""
expected_reward_factual *= self.exam_weight
if self.reward_type == "binary":
sampled_reward_list = list()
discount_factors = np.ones(expected_reward_factual.shape[0])
sampled_rewards_at_position = np.zeros(expected_reward_factual.shape[0])
for pos_ in np.arange(self.len_list):
discount_factors *= sampled_rewards_at_position * self.attractiveness[
pos_
] + (1 - sampled_rewards_at_position)
expected_reward_factual_at_position = (
discount_factors * expected_reward_factual[:, pos_]
)
sampled_rewards_at_position = self.random_.binomial(
n=1, p=expected_reward_factual_at_position
)
sampled_reward_list.append(sampled_rewards_at_position)
reward = np.array(sampled_reward_list).T
elif self.reward_type == "continuous":
reward = np.zeros(expected_reward_factual.shape)
for pos_ in np.arange(self.len_list):
mean = expected_reward_factual[:, pos_]
a = (self.reward_min - mean) / self.reward_std
b = (self.reward_max - mean) / self.reward_std
reward[:, pos_] = truncnorm.rvs(
a=a,
b=b,
loc=mean,
scale=self.reward_std,
random_state=self.random_state,
)
else:
raise NotImplementedError
# return: array-like, shape (n_rounds, len_list)
return reward
def obtain_batch_bandit_feedback(
self,
n_rounds: int,
return_pscore_item_position: bool = True,
clip_logit_value: Optional[float] = None,
) -> BanditFeedback:
"""Obtain batch logged bandit data.
Parameters
----------
n_rounds: int
Data size of the synthetic logged bandit data.
return_pscore_item_position: bool, default=True
Whether to compute `pscore_item_position` and include it in the logged data.
When `n_unique_action` and `len_list` are large, this should be set to False due to computation time.
clip_logit_value: Optional[float], default=None
A float parameter to clip logit values.
When None, we calculate softmax values without clipping to obtain `pscore_item_position`.
When a float value is given, we clip logit values to calculate softmax values to obtain `pscore_item_position`.
When `n_actions` and `len_list` are large, `clip_logit_value`=None can lead to a long computation time.
Returns
---------
bandit_feedback: BanditFeedback
Synthesized slate logged bandit dataset.
"""
check_scalar(n_rounds, "n_rounds", int, min_val=1)
context = self.random_.normal(size=(n_rounds, self.dim_context))
# sample actions for each round based on the behavior policy
if self.behavior_policy_function is None:
behavior_policy_logit_ = np.tile(
self.uniform_behavior_policy, (n_rounds, 1)
)
else:
behavior_policy_logit_ = self.behavior_policy_function(
context=context,
action_context=self.action_context,
random_state=self.random_state,
)
# check the shape of behavior_policy_logit_
if not (
isinstance(behavior_policy_logit_, np.ndarray)
and behavior_policy_logit_.shape == (n_rounds, self.n_unique_action)
):
raise ValueError("`behavior_policy_logit_` has an invalid shape")
# sample actions and calculate the three variants of the propensity scores
(
action,
pscore_cascade,
pscore,
pscore_item_position,
) = self.sample_action_and_obtain_pscore(
behavior_policy_logit_=behavior_policy_logit_,
n_rounds=n_rounds,
return_pscore_item_position=return_pscore_item_position,
clip_logit_value=clip_logit_value,
)
# sample expected reward factual
if self.base_reward_function is None:
expected_reward = self.sample_contextfree_expected_reward(
random_state=self.random_state
)
expected_reward_tile = np.tile(expected_reward, (n_rounds, 1, 1))
# action_2d: array-like, shape (n_rounds, len_list)
action_2d = action.reshape((n_rounds, self.len_list))
# expected_reward_factual: array-like, shape (n_rounds, len_list)
expected_reward_factual = np.array(
[
expected_reward_tile[np.arange(n_rounds), action_2d[:, pos_], pos_]
for pos_ in np.arange(self.len_list)
]
).T
else:
expected_reward_factual = self.reward_function(
context=context,
action_context=self.action_context,
action=action,
action_interaction_weight_matrix=self.action_interaction_weight_matrix,
base_reward_function=self.base_reward_function,
reward_type=self.reward_type,
reward_structure=self.reward_structure,
len_list=self.len_list,
random_state=self.random_state,
)
# check the shape of expected_reward_factual
if not (
isinstance(expected_reward_factual, np.ndarray)
and expected_reward_factual.shape == (n_rounds, self.len_list)
):
raise ValueError("`expected_reward_factual` has an invalid shape")
# sample reward
reward = self.sample_reward_given_expected_reward(
expected_reward_factual=expected_reward_factual
)
return dict(
n_rounds=n_rounds,
n_unique_action=self.n_unique_action,
slate_id=np.repeat(np.arange(n_rounds), self.len_list),
context=context,
action_context=self.action_context,
action=action,
position=np.tile(np.arange(self.len_list), n_rounds),
reward=reward.reshape(action.shape[0]),
expected_reward_factual=expected_reward_factual.reshape(action.shape[0]),
pscore_cascade=pscore_cascade,
pscore=pscore,
pscore_item_position=pscore_item_position,
)
def calc_on_policy_policy_value(
self, reward: np.ndarray, slate_id: np.ndarray
) -> float:
"""Calculate the policy value of given reward and slate_id.
Parameters
-----------
reward: array-like, shape (<= n_rounds * len_list,)
Slot-level rewards, i.e., :math:`r_{i}(l)`.
slate_id: array-like, shape (<= n_rounds * len_list,)
Slate index.
Returns
----------
policy_value: float
The on-policy policy value estimate of the behavior policy.
"""
check_array(array=slate_id, name="slate_id", expected_dim=1)
check_array(array=reward, name="reward", expected_dim=1)
if reward.shape[0] != slate_id.shape[0]:
raise ValueError(
"Expected `reward.shape[0] == slate_id.shape[0]`, but found it False"
)
return reward.sum() / np.unique(slate_id).shape[0]
def calc_ground_truth_policy_value(
self,
context: np.ndarray,
evaluation_policy_logit_: np.ndarray,
):
"""Calculate the ground-truth policy value of given evaluation policy logit and contexts.
Parameters
-----------
context: array-like, shape (n_rounds, dim_context)
Context vectors characterizing each data (such as user information).
evaluation_policy_logit_: array-like, shape (n_rounds, n_unique_action)
Logit values to define the evaluation policy.
"""
check_array(array=context, name="context", expected_dim=2)
check_array(
array=evaluation_policy_logit_,
name="evaluation_policy_logit_",
expected_dim=2,
)
if evaluation_policy_logit_.shape[1] != self.n_unique_action:
raise ValueError(
"Expected `evaluation_policy_logit_.shape[1] != self.n_unique_action`,"
"but found it False"
)
if context.shape[1] != self.dim_context:
raise ValueError(
"Expected `context.shape[1] == self.dim_context`, but found it False"
)
if evaluation_policy_logit_.shape[0] != context.shape[0]:
raise ValueError(
"Expected `evaluation_policy_logit_.shape[0] == context.shape[0]`,"
"but found it False"
)
if self.is_factorizable:
enumerated_slate_actions = [
_
for _ in product(np.arange(self.n_unique_action), repeat=self.len_list)
]
else:
enumerated_slate_actions = [
_ for _ in permutations(np.arange(self.n_unique_action), self.len_list)
]
enumerated_slate_actions = np.array(enumerated_slate_actions).astype("int8")
n_slate_actions = len(enumerated_slate_actions)
n_rounds = len(evaluation_policy_logit_)
pscores = []
n_enumerated_slate_actions = len(enumerated_slate_actions)
if self.is_factorizable:
for action_list in tqdm(
enumerated_slate_actions,
desc="[calc_ground_truth_policy_value (pscore)]",
total=n_enumerated_slate_actions,
):
pscores.append(
softmax(evaluation_policy_logit_)[:, action_list].prod(1)
)
pscores = np.array(pscores).T
else:
for i in tqdm(
np.arange(n_rounds),
desc="[calc_ground_truth_policy_value (pscore)]",
total=n_rounds,
):
pscores.append(
self._calc_pscore_given_policy_logit(
all_slate_actions=enumerated_slate_actions,
policy_logit_i_=evaluation_policy_logit_[i],
)
)
pscores = np.array(pscores)
# calculate expected slate-level reward for each combinatorial set of items (i.e., slate actions)
if self.base_reward_function is None:
expected_slot_reward = self.sample_contextfree_expected_reward(
random_state=self.random_state
)
expected_slot_reward_tile = np.tile(
expected_slot_reward, (n_rounds * n_slate_actions, 1, 1)
)
expected_slate_rewards = np.array(
[
expected_slot_reward_tile[
np.arange(n_slate_actions) % n_slate_actions,
np.array(enumerated_slate_actions)[:, pos_],
pos_,
]
for pos_ in np.arange(self.len_list)
]
).T
policy_value = (pscores * expected_slate_rewards.sum(axis=1)).sum()
else:
n_batch = (
n_rounds * n_enumerated_slate_actions * self.len_list - 1
) // 10**7 + 1
batch_size = (n_rounds - 1) // n_batch + 1
n_batch = (n_rounds - 1) // batch_size + 1
policy_value = 0.0
for batch_idx in tqdm(
np.arange(n_batch),
desc=f"[calc_ground_truth_policy_value (expected reward), batch_size={batch_size}]",
total=n_batch,
):
context_ = context[
batch_idx * batch_size : (batch_idx + 1) * batch_size
]
pscores_ = pscores[
batch_idx * batch_size : (batch_idx + 1) * batch_size
]
expected_slate_rewards_ = self.reward_function(
context=context_,
action_context=self.action_context,
action=enumerated_slate_actions.flatten(),
action_interaction_weight_matrix=self.action_interaction_weight_matrix,
base_reward_function=self.base_reward_function,
reward_type=self.reward_type,
reward_structure=self.reward_structure,
len_list=self.len_list,
is_enumerated=True,
random_state=self.random_state,
)
# click models based on expected reward
expected_slate_rewards_ *= self.exam_weight
if self.reward_type == "binary":