replay-rec 0.20.0__py3-none-any.whl → 0.20.0rc0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. replay/__init__.py +1 -1
  2. replay/data/dataset.py +10 -9
  3. replay/data/dataset_utils/dataset_label_encoder.py +5 -4
  4. replay/data/nn/schema.py +9 -18
  5. replay/data/nn/sequence_tokenizer.py +16 -15
  6. replay/data/nn/sequential_dataset.py +4 -4
  7. replay/data/nn/torch_sequential_dataset.py +5 -4
  8. replay/data/nn/utils.py +2 -1
  9. replay/data/schema.py +3 -12
  10. replay/experimental/__init__.py +0 -0
  11. replay/experimental/metrics/__init__.py +62 -0
  12. replay/experimental/metrics/base_metric.py +603 -0
  13. replay/experimental/metrics/coverage.py +97 -0
  14. replay/experimental/metrics/experiment.py +175 -0
  15. replay/experimental/metrics/hitrate.py +26 -0
  16. replay/experimental/metrics/map.py +30 -0
  17. replay/experimental/metrics/mrr.py +18 -0
  18. replay/experimental/metrics/ncis_precision.py +31 -0
  19. replay/experimental/metrics/ndcg.py +49 -0
  20. replay/experimental/metrics/precision.py +22 -0
  21. replay/experimental/metrics/recall.py +25 -0
  22. replay/experimental/metrics/rocauc.py +49 -0
  23. replay/experimental/metrics/surprisal.py +90 -0
  24. replay/experimental/metrics/unexpectedness.py +76 -0
  25. replay/experimental/models/__init__.py +50 -0
  26. replay/experimental/models/admm_slim.py +257 -0
  27. replay/experimental/models/base_neighbour_rec.py +200 -0
  28. replay/experimental/models/base_rec.py +1386 -0
  29. replay/experimental/models/base_torch_rec.py +234 -0
  30. replay/experimental/models/cql.py +454 -0
  31. replay/experimental/models/ddpg.py +932 -0
  32. replay/experimental/models/dt4rec/__init__.py +0 -0
  33. replay/experimental/models/dt4rec/dt4rec.py +189 -0
  34. replay/experimental/models/dt4rec/gpt1.py +401 -0
  35. replay/experimental/models/dt4rec/trainer.py +127 -0
  36. replay/experimental/models/dt4rec/utils.py +264 -0
  37. replay/experimental/models/extensions/spark_custom_models/__init__.py +0 -0
  38. replay/experimental/models/extensions/spark_custom_models/als_extension.py +792 -0
  39. replay/experimental/models/hierarchical_recommender.py +331 -0
  40. replay/experimental/models/implicit_wrap.py +131 -0
  41. replay/experimental/models/lightfm_wrap.py +303 -0
  42. replay/experimental/models/mult_vae.py +332 -0
  43. replay/experimental/models/neural_ts.py +986 -0
  44. replay/experimental/models/neuromf.py +406 -0
  45. replay/experimental/models/scala_als.py +293 -0
  46. replay/experimental/models/u_lin_ucb.py +115 -0
  47. replay/experimental/nn/data/__init__.py +1 -0
  48. replay/experimental/nn/data/schema_builder.py +102 -0
  49. replay/experimental/preprocessing/__init__.py +3 -0
  50. replay/experimental/preprocessing/data_preparator.py +839 -0
  51. replay/experimental/preprocessing/padder.py +229 -0
  52. replay/experimental/preprocessing/sequence_generator.py +208 -0
  53. replay/experimental/scenarios/__init__.py +1 -0
  54. replay/experimental/scenarios/obp_wrapper/__init__.py +8 -0
  55. replay/experimental/scenarios/obp_wrapper/obp_optuna_objective.py +74 -0
  56. replay/experimental/scenarios/obp_wrapper/replay_offline.py +261 -0
  57. replay/experimental/scenarios/obp_wrapper/utils.py +85 -0
  58. replay/experimental/scenarios/two_stages/__init__.py +0 -0
  59. replay/experimental/scenarios/two_stages/reranker.py +117 -0
  60. replay/experimental/scenarios/two_stages/two_stages_scenario.py +757 -0
  61. replay/experimental/utils/__init__.py +0 -0
  62. replay/experimental/utils/logger.py +24 -0
  63. replay/experimental/utils/model_handler.py +186 -0
  64. replay/experimental/utils/session_handler.py +44 -0
  65. replay/metrics/base_metric.py +11 -10
  66. replay/metrics/categorical_diversity.py +8 -8
  67. replay/metrics/coverage.py +4 -4
  68. replay/metrics/experiment.py +3 -3
  69. replay/metrics/hitrate.py +1 -3
  70. replay/metrics/map.py +1 -3
  71. replay/metrics/mrr.py +1 -3
  72. replay/metrics/ndcg.py +1 -2
  73. replay/metrics/novelty.py +3 -3
  74. replay/metrics/offline_metrics.py +16 -16
  75. replay/metrics/precision.py +1 -3
  76. replay/metrics/recall.py +1 -3
  77. replay/metrics/rocauc.py +1 -3
  78. replay/metrics/surprisal.py +4 -4
  79. replay/metrics/torch_metrics_builder.py +13 -12
  80. replay/metrics/unexpectedness.py +2 -2
  81. replay/models/als.py +2 -2
  82. replay/models/association_rules.py +4 -3
  83. replay/models/base_neighbour_rec.py +3 -2
  84. replay/models/base_rec.py +11 -10
  85. replay/models/cat_pop_rec.py +2 -1
  86. replay/models/extensions/ann/ann_mixin.py +2 -1
  87. replay/models/extensions/ann/index_builders/executor_hnswlib_index_builder.py +2 -1
  88. replay/models/extensions/ann/index_builders/executor_nmslib_index_builder.py +2 -1
  89. replay/models/lin_ucb.py +3 -3
  90. replay/models/nn/optimizer_utils/optimizer_factory.py +2 -2
  91. replay/models/nn/sequential/bert4rec/dataset.py +2 -2
  92. replay/models/nn/sequential/bert4rec/lightning.py +3 -3
  93. replay/models/nn/sequential/bert4rec/model.py +2 -2
  94. replay/models/nn/sequential/callbacks/prediction_callbacks.py +12 -12
  95. replay/models/nn/sequential/callbacks/validation_callback.py +9 -9
  96. replay/models/nn/sequential/compiled/base_compiled_model.py +5 -5
  97. replay/models/nn/sequential/postprocessors/_base.py +2 -3
  98. replay/models/nn/sequential/postprocessors/postprocessors.py +10 -10
  99. replay/models/nn/sequential/sasrec/lightning.py +3 -3
  100. replay/models/nn/sequential/sasrec/model.py +8 -8
  101. replay/models/slim.py +2 -2
  102. replay/models/ucb.py +2 -2
  103. replay/models/word2vec.py +3 -3
  104. replay/preprocessing/discretizer.py +8 -7
  105. replay/preprocessing/filters.py +4 -4
  106. replay/preprocessing/history_based_fp.py +6 -6
  107. replay/preprocessing/label_encoder.py +8 -7
  108. replay/scenarios/fallback.py +4 -3
  109. replay/splitters/base_splitter.py +3 -3
  110. replay/splitters/cold_user_random_splitter.py +4 -4
  111. replay/splitters/k_folds.py +4 -4
  112. replay/splitters/last_n_splitter.py +10 -10
  113. replay/splitters/new_users_splitter.py +4 -4
  114. replay/splitters/random_splitter.py +4 -4
  115. replay/splitters/ratio_splitter.py +10 -10
  116. replay/splitters/time_splitter.py +6 -6
  117. replay/splitters/two_stage_splitter.py +4 -4
  118. replay/utils/__init__.py +1 -0
  119. replay/utils/common.py +1 -1
  120. replay/utils/session_handler.py +2 -2
  121. replay/utils/spark_utils.py +6 -5
  122. replay/utils/types.py +3 -1
  123. {replay_rec-0.20.0.dist-info → replay_rec-0.20.0rc0.dist-info}/METADATA +17 -17
  124. replay_rec-0.20.0rc0.dist-info/RECORD +194 -0
  125. replay_rec-0.20.0.dist-info/RECORD +0 -139
  126. {replay_rec-0.20.0.dist-info → replay_rec-0.20.0rc0.dist-info}/WHEEL +0 -0
  127. {replay_rec-0.20.0.dist-info → replay_rec-0.20.0rc0.dist-info}/licenses/LICENSE +0 -0
  128. {replay_rec-0.20.0.dist-info → replay_rec-0.20.0rc0.dist-info}/licenses/NOTICE +0 -0
@@ -0,0 +1,603 @@
1
+ """
2
+ Base classes for quality and diversity metrics.
3
+ """
4
+
5
+ import logging
6
+ from abc import ABC, abstractmethod
7
+ from typing import Optional, Union
8
+
9
+ import pandas as pd
10
+ from scipy.stats import norm
11
+
12
+ from replay.utils import PYSPARK_AVAILABLE, DataFrameLike, IntOrList, NumType, PandasDataFrame, SparkDataFrame
13
+ from replay.utils.session_handler import State
14
+ from replay.utils.spark_utils import convert2spark, get_top_k_recs
15
+
16
+ if PYSPARK_AVAILABLE:
17
+ from pyspark.sql import (
18
+ Column,
19
+ Window,
20
+ functions as sf,
21
+ types as st,
22
+ )
23
+ from pyspark.sql.column import _to_java_column, _to_seq
24
+ from pyspark.sql.types import DataType
25
+
26
+
27
+ def fill_na_with_empty_array(df: SparkDataFrame, col_name: str, element_type: DataType) -> SparkDataFrame:
28
+ """
29
+ Fill empty values in array column with empty array of `element_type` values.
30
+ :param df: dataframe with `col_name` column of ArrayType(`element_type`)
31
+ :param col_name: name of a column to fill missing values
32
+ :param element_type: DataType of an array element
33
+ :return: df with `col_name` na values filled with empty arrays
34
+ """
35
+ return df.withColumn(
36
+ col_name,
37
+ sf.coalesce(
38
+ col_name,
39
+ sf.array().cast(st.ArrayType(element_type)),
40
+ ),
41
+ )
42
+
43
+
44
+ def preprocess_gt(
45
+ ground_truth: DataFrameLike,
46
+ ground_truth_users: Optional[DataFrameLike] = None,
47
+ ) -> SparkDataFrame:
48
+ """
49
+ Preprocess `ground_truth` data before metric calculation
50
+ :param ground_truth: spark dataframe with columns ``[user_idx, item_idx, relevance]``
51
+ :param ground_truth_users: spark dataframe with column ``[user_idx]``
52
+ :return: spark dataframe with columns ``[user_idx, ground_truth]``
53
+ """
54
+ ground_truth = convert2spark(ground_truth)
55
+ ground_truth_users = convert2spark(ground_truth_users)
56
+
57
+ true_items_by_users = ground_truth.groupby("user_idx").agg(sf.collect_set("item_idx").alias("ground_truth"))
58
+ if ground_truth_users is not None:
59
+ true_items_by_users = true_items_by_users.join(ground_truth_users, on="user_idx", how="right")
60
+ true_items_by_users = fill_na_with_empty_array(
61
+ true_items_by_users,
62
+ "ground_truth",
63
+ ground_truth.schema["item_idx"].dataType,
64
+ )
65
+
66
+ return true_items_by_users
67
+
68
+
69
+ def drop_duplicates(recommendations: DataFrameLike) -> SparkDataFrame:
70
+ """
71
+ Filter duplicated predictions by choosing the most relevant
72
+ """
73
+ return (
74
+ recommendations.withColumn(
75
+ "_num",
76
+ sf.row_number().over(Window.partitionBy("user_idx", "item_idx").orderBy(sf.col("relevance").desc())),
77
+ )
78
+ .where(sf.col("_num") == 1)
79
+ .drop("_num")
80
+ )
81
+
82
+
83
+ def filter_sort(recommendations: SparkDataFrame, extra_column: Optional[str] = None) -> SparkDataFrame:
84
+ """
85
+ Filters duplicated predictions by choosing items with the highest relevance,
86
+ Sorts items in predictions by its relevance,
87
+ If `extra_column` is not None return DataFrame with extra_column e.g. item weight.
88
+
89
+ :param recommendations: recommendation list
90
+ :param extra_column: column in recommendations
91
+ which will be return besides ``[user_idx, item_idx]``
92
+ :return: ``[user_idx, item_idx]`` if extra_column = None
93
+ or ``[user_idx, item_idx, extra_column]`` if extra_column exists.
94
+ """
95
+ item_type = recommendations.schema["item_idx"].dataType
96
+ extra_column_type = recommendations.schema[extra_column].dataType if extra_column else None
97
+
98
+ recommendations = drop_duplicates(recommendations)
99
+
100
+ recommendations = (
101
+ recommendations.groupby("user_idx")
102
+ .agg(
103
+ sf.collect_list(sf.struct(*[c for c in ["relevance", "item_idx", extra_column] if c is not None])).alias(
104
+ "pred_list"
105
+ )
106
+ )
107
+ .withColumn("pred_list", sf.reverse(sf.array_sort("pred_list")))
108
+ )
109
+
110
+ selection = ["user_idx", sf.col("pred_list.item_idx").cast(st.ArrayType(item_type, True)).alias("pred")]
111
+ if extra_column:
112
+ selection.append(
113
+ sf.col(f"pred_list.{extra_column}").cast(st.ArrayType(extra_column_type, True)).alias(extra_column)
114
+ )
115
+
116
+ recommendations = recommendations.select(*selection)
117
+
118
+ return recommendations
119
+
120
+
121
+ def get_enriched_recommendations(
122
+ recommendations: DataFrameLike,
123
+ ground_truth: DataFrameLike,
124
+ max_k: int,
125
+ ground_truth_users: Optional[DataFrameLike] = None,
126
+ ) -> SparkDataFrame:
127
+ """
128
+ Leave max_k recommendations for each user,
129
+ merge recommendations and ground truth into a single DataFrame
130
+ and aggregate items into lists so that each user has only one record.
131
+
132
+ :param recommendations: recommendation list
133
+ :param ground_truth: test data
134
+ :param max_k: maximal k value to calculate the metric for.
135
+ `max_k` most relevant predictions are left for each user
136
+ :param ground_truth_users: list of users to consider in metric calculation.
137
+ if None, only the users from ground_truth are considered.
138
+ :return: ``[user_idx, pred, ground_truth]``
139
+ """
140
+ recommendations = convert2spark(recommendations)
141
+ # if there are duplicates in recommendations,
142
+ # we will leave fewer than k recommendations after sort_udf
143
+ recommendations = get_top_k_recs(recommendations, k=max_k)
144
+
145
+ true_items_by_users = preprocess_gt(ground_truth, ground_truth_users)
146
+ joined = filter_sort(recommendations).join(true_items_by_users, how="right", on=["user_idx"])
147
+
148
+ return fill_na_with_empty_array(joined, "pred", recommendations.schema["item_idx"].dataType)
149
+
150
+
151
+ def process_k(func):
152
+ """Decorator that converts k to list and unpacks result"""
153
+
154
+ def wrap(self, recs: SparkDataFrame, k: IntOrList, *args):
155
+ k_list = [k] if isinstance(k, int) else k
156
+
157
+ res = func(self, recs, k_list, *args)
158
+
159
+ if isinstance(k, int):
160
+ return res[k]
161
+ return res
162
+
163
+ return wrap
164
+
165
+
166
+ class Metric(ABC):
167
+ """Base metric class"""
168
+
169
+ _logger: Optional[logging.Logger] = None
170
+ _scala_udf_name: Optional[str] = None
171
+
172
+ def __init__(self, use_scala_udf: bool = False) -> None:
173
+ self._use_scala_udf = use_scala_udf
174
+
175
+ @property
176
+ def logger(self) -> logging.Logger:
177
+ """
178
+ :returns: get library logger
179
+ """
180
+ if self._logger is None:
181
+ self._logger = logging.getLogger("replay")
182
+ return self._logger
183
+
184
+ @property
185
+ def scala_udf_name(self) -> str:
186
+ """Returns UDF name from `org.apache.spark.replay.utils.ScalaPySparkUDFs`"""
187
+ if self._scala_udf_name:
188
+ return self._scala_udf_name
189
+ else:
190
+ msg = f"Scala UDF not implemented for {type(self).__name__} class!"
191
+ raise NotImplementedError(msg)
192
+
193
+ def __str__(self):
194
+ return type(self).__name__
195
+
196
+ def __call__(
197
+ self,
198
+ recommendations: DataFrameLike,
199
+ ground_truth: DataFrameLike,
200
+ k: IntOrList,
201
+ ground_truth_users: Optional[DataFrameLike] = None,
202
+ ) -> Union[dict[int, NumType], NumType]:
203
+ """
204
+ :param recommendations: model predictions in a
205
+ DataFrame ``[user_idx, item_idx, relevance]``
206
+ :param ground_truth: test data
207
+ ``[user_idx, item_idx, timestamp, relevance]``
208
+ :param k: depth cut-off. Truncates recommendation lists to top-k items.
209
+ :param ground_truth_users: list of users to consider in metric calculation.
210
+ if None, only the users from ground_truth are considered.
211
+ :return: metric value
212
+ """
213
+ recs = get_enriched_recommendations(
214
+ recommendations,
215
+ ground_truth,
216
+ max_k=k if isinstance(k, int) else max(k),
217
+ ground_truth_users=ground_truth_users,
218
+ )
219
+ return self._mean(recs, k)
220
+
221
+ @process_k
222
+ def _conf_interval(self, recs: SparkDataFrame, k_list: list, alpha: float):
223
+ res = {}
224
+ quantile = norm.ppf((1 + alpha) / 2)
225
+ for k in k_list:
226
+ distribution = self._get_metric_distribution(recs, k)
227
+ value = (
228
+ distribution.agg(
229
+ sf.stddev("value").alias("std"),
230
+ sf.count("value").alias("count"),
231
+ )
232
+ .select(
233
+ sf.when(
234
+ sf.isnan(sf.col("std")) | sf.col("std").isNull(),
235
+ sf.lit(0.0),
236
+ )
237
+ .otherwise(sf.col("std"))
238
+ .cast("float")
239
+ .alias("std"),
240
+ "count",
241
+ )
242
+ .first()
243
+ )
244
+ res[k] = quantile * value["std"] / (value["count"] ** 0.5)
245
+ return res
246
+
247
+ @process_k
248
+ def _median(self, recs: SparkDataFrame, k_list: list):
249
+ res = {}
250
+ for k in k_list:
251
+ distribution = self._get_metric_distribution(recs, k)
252
+ value = distribution.agg(sf.expr("percentile_approx(value, 0.5)").alias("value")).first()["value"]
253
+ res[k] = value
254
+ return res
255
+
256
+ @process_k
257
+ def _mean(self, recs: SparkDataFrame, k_list: list):
258
+ res = {}
259
+ for k in k_list:
260
+ distribution = self._get_metric_distribution(recs, k)
261
+ value = distribution.agg(sf.avg("value").alias("value")).first()["value"]
262
+ res[k] = value
263
+ return res
264
+
265
+ def _get_metric_distribution(self, recs: SparkDataFrame, k: int) -> SparkDataFrame:
266
+ """
267
+ :param recs: recommendations
268
+ :param k: depth cut-off
269
+ :return: metric distribution for different cut-offs and users
270
+ """
271
+ if self._use_scala_udf:
272
+ metric_value_col = self.get_scala_udf(self.scala_udf_name, [sf.lit(k).alias("k"), *recs.columns[1:]]).alias(
273
+ "value"
274
+ )
275
+ return recs.select("user_idx", metric_value_col)
276
+
277
+ cur_class = self.__class__
278
+ distribution = recs.rdd.flatMap(lambda x: [(x[0], float(cur_class._get_metric_value_by_user(k, *x[1:])))]).toDF(
279
+ f"user_idx {recs.schema['user_idx'].dataType.typeName()}, value double"
280
+ )
281
+ return distribution
282
+
283
+ @staticmethod
284
+ @abstractmethod
285
+ def _get_metric_value_by_user(k, pred, ground_truth) -> float:
286
+ """
287
+ Metric calculation for one user.
288
+
289
+ :param k: depth cut-off
290
+ :param pred: recommendations
291
+ :param ground_truth: test data
292
+ :return: metric value for current user
293
+ """
294
+
295
+ def user_distribution(
296
+ self,
297
+ log: DataFrameLike,
298
+ recommendations: DataFrameLike,
299
+ ground_truth: DataFrameLike,
300
+ k: IntOrList,
301
+ ground_truth_users: Optional[DataFrameLike] = None,
302
+ ) -> PandasDataFrame:
303
+ """
304
+ Get mean value of metric for all users with the same number of ratings.
305
+
306
+ :param log: history DataFrame to calculate number of ratings per user
307
+ :param recommendations: prediction DataFrame
308
+ :param ground_truth: test data
309
+ :param k: depth cut-off
310
+ :param ground_truth_users: list of users to consider in metric calculation.
311
+ if None, only the users from ground_truth are considered.
312
+ :return: pandas DataFrame
313
+ """
314
+ log = convert2spark(log)
315
+ count = log.groupBy("user_idx").count()
316
+ if hasattr(self, "_get_enriched_recommendations"):
317
+ recs = self._get_enriched_recommendations(
318
+ recommendations,
319
+ ground_truth,
320
+ max_k=k if isinstance(k, int) else max(k),
321
+ ground_truth_users=ground_truth_users,
322
+ )
323
+ else:
324
+ recs = get_enriched_recommendations(
325
+ recommendations,
326
+ ground_truth,
327
+ max_k=k if isinstance(k, int) else max(k),
328
+ ground_truth_users=ground_truth_users,
329
+ )
330
+ k_list = [k] if isinstance(k, int) else k
331
+ res = PandasDataFrame()
332
+ for cut_off in k_list:
333
+ dist = self._get_metric_distribution(recs, cut_off)
334
+ val = count.join(dist, on="user_idx", how="right").fillna(0, subset="count")
335
+ val = (
336
+ val.groupBy("count")
337
+ .agg(sf.avg("value").alias("value"))
338
+ .orderBy(["count"])
339
+ .select("count", "value")
340
+ .toPandas()
341
+ )
342
+ res = pd.concat([res, val], ignore_index=True)
343
+ return res
344
+
345
+ @staticmethod
346
+ def get_scala_udf(udf_name: str, params: list) -> Column:
347
+ """
348
+ Returns expression of calling scala UDF as column
349
+
350
+ :param udf_name: UDF name from `org.apache.spark.replay.utils.ScalaPySparkUDFs`
351
+ :param params: list of UDF params in right order
352
+ :return: column expression
353
+ """
354
+ sc = State().session.sparkContext
355
+ scala_udf = getattr(sc._jvm.org.apache.spark.replay.utils.ScalaPySparkUDFs, udf_name)()
356
+ return Column(scala_udf.apply(_to_seq(sc, params, _to_java_column)))
357
+
358
+
359
+ class RecOnlyMetric(Metric):
360
+ """Base class for metrics that do not need holdout data"""
361
+
362
+ @abstractmethod
363
+ def __init__(self, log: DataFrameLike, *args, **kwargs):
364
+ pass
365
+
366
+ @abstractmethod
367
+ def _get_enriched_recommendations(
368
+ self,
369
+ recommendations: DataFrameLike,
370
+ ground_truth: Optional[DataFrameLike],
371
+ max_k: int,
372
+ ground_truth_users: Optional[DataFrameLike] = None,
373
+ ) -> SparkDataFrame:
374
+ pass
375
+
376
+ def __call__(
377
+ self,
378
+ recommendations: DataFrameLike,
379
+ k: IntOrList,
380
+ ground_truth_users: Optional[DataFrameLike] = None,
381
+ ) -> Union[dict[int, NumType], NumType]:
382
+ """
383
+ :param recommendations: predictions of a model,
384
+ DataFrame ``[user_idx, item_idx, relevance]``
385
+ :param k: depth cut-off
386
+ :param ground_truth_users: list of users to consider in metric calculation.
387
+ if None, only the users from ground_truth are considered.
388
+ :return: metric value
389
+ """
390
+ recs = self._get_enriched_recommendations(
391
+ recommendations,
392
+ None,
393
+ max_k=k if isinstance(k, int) else max(k),
394
+ ground_truth_users=ground_truth_users,
395
+ )
396
+ return self._mean(recs, k)
397
+
398
+ @staticmethod
399
+ @abstractmethod
400
+ def _get_metric_value_by_user(k, *args) -> float:
401
+ """
402
+ Metric calculation for one user.
403
+
404
+ :param k: depth cut-off
405
+ :param *args: extra parameters, returned by
406
+ '''self._get_enriched_recommendations''' method
407
+ :return: metric value for current user
408
+ """
409
+
410
+
411
+ class NCISMetric(Metric):
412
+ """
413
+ RePlay implements Normalized Capped Importance Sampling for metric calculation with ``NCISMetric`` class.
414
+ This method is mostly applied to RL-based recommendation systems to perform counterfactual evaluation, but could be
415
+ used for any kind of recommender systems. See an article
416
+ `Offline A/B testing for Recommender Systems <http://arxiv.org/abs/1801.07030>` for details.
417
+
418
+ *Reward* (metric value for a user-item pair) is weighed by
419
+ the ratio of *current policy score* (current relevance) on *previous policy score* (historical relevance).
420
+
421
+ The *weight* is clipped by the *threshold* and put into interval :math:`[\\frac{1}{threshold}, threshold]`.
422
+ Activation function (e.g. softmax, sigmoid) could be applied to the scores before weights calculation.
423
+
424
+ Normalization weight for recommended item is calculated as follows:
425
+
426
+ .. math::
427
+ w_{ui} = \\frac{f(\\pi^t_ui, pi^t_u)}{f(\\pi^p_ui, pi^p_u)}
428
+
429
+ Where:
430
+
431
+ :math:`\\pi^t_{ui}` - current policy value (predicted relevance) of the user-item interaction
432
+
433
+ :math:`\\pi^p_{ui}` - previous policy value (historical relevance) of the user-item interaction.
434
+ Only values for user-item pairs present in current recommendations are used for calculation.
435
+
436
+ :math:`\\pi_u` - all predicted /historical policy values for selected user :math:`u`
437
+
438
+ :math:`f(\\pi_{ui}, \\pi_u)` - activation function applied to policy values (optional)
439
+
440
+ :math:`w_{ui}` - weight of user-item interaction for normalized metric calculation before clipping
441
+
442
+
443
+ Calculated weights are clipped as follows:
444
+
445
+ .. math::
446
+ \\hat{w_{ui}} = min(max(\\frac{1}{threshold}, w_{ui}), threshold)
447
+
448
+ Normalization metric value for a user is calculated as follows:
449
+
450
+ .. math::
451
+ R_u = \\frac{r_{ui} \\hat{w_{ui}}}{\\sum_{i}\\hat{w_{ui}}}
452
+
453
+ Where:
454
+
455
+ :math:`r_ui` - metric value (reward) for user-item interaction
456
+
457
+ :math:`R_u` - metric value (reward) for user :math:`u`
458
+
459
+ Weight calculation is implemented in ``_get_enriched_recommendations`` method.
460
+ """
461
+
462
+ def __init__(
463
+ self,
464
+ prev_policy_weights: DataFrameLike,
465
+ threshold: float = 10.0,
466
+ activation: Optional[str] = None,
467
+ use_scala_udf: bool = False,
468
+ ):
469
+ """
470
+ :param prev_policy_weights: historical item of user-item relevance (previous policy values)
471
+ :threshold: capping threshold, applied after activation,
472
+ relevance values are cropped to interval [1/`threshold`, `threshold`]
473
+ :activation: activation function, applied over relevance values.
474
+ "logit"/"sigmoid", "softmax" or None
475
+ """
476
+ self._use_scala_udf = use_scala_udf
477
+ self.prev_policy_weights = convert2spark(prev_policy_weights).withColumnRenamed("relevance", "prev_relevance")
478
+ self.threshold = threshold
479
+ if activation is None or activation in ("logit", "sigmoid", "softmax"):
480
+ self.activation = activation
481
+ if activation == "softmax":
482
+ self.logger.info(
483
+ "For accurate softmax calculation pass only one `k` value in the NCISMetric metrics `call`"
484
+ )
485
+ else:
486
+ msg = f"Unexpected `activation` - {activation}"
487
+ raise ValueError(msg)
488
+ if threshold <= 0:
489
+ msg = "Threshold should be positive real number"
490
+ raise ValueError(msg)
491
+
492
+ @staticmethod
493
+ def _softmax_by_user(df: SparkDataFrame, col_name: str) -> SparkDataFrame:
494
+ """
495
+ Subtract minimal value (relevance) by user from `col_name`
496
+ and apply softmax by user to `col_name`.
497
+ """
498
+ return (
499
+ df.withColumn(
500
+ "_min_rel_user",
501
+ sf.min(col_name).over(Window.partitionBy("user_idx")),
502
+ )
503
+ .withColumn(col_name, sf.exp(sf.col(col_name) - sf.col("_min_rel_user")))
504
+ .withColumn(
505
+ col_name,
506
+ sf.col(col_name) / sf.sum(col_name).over(Window.partitionBy("user_idx")),
507
+ )
508
+ .drop("_min_rel_user")
509
+ )
510
+
511
+ @staticmethod
512
+ def _sigmoid(df: SparkDataFrame, col_name: str) -> SparkDataFrame:
513
+ """
514
+ Apply sigmoid/logistic function to column `col_name`
515
+ """
516
+ return df.withColumn(col_name, sf.lit(1.0) / (sf.lit(1.0) + sf.exp(-sf.col(col_name))))
517
+
518
+ @staticmethod
519
+ def _weigh_and_clip(
520
+ df: SparkDataFrame,
521
+ threshold: float,
522
+ target_policy_col: str = "relevance",
523
+ prev_policy_col: str = "prev_relevance",
524
+ ):
525
+ """
526
+ Clip weights to fit into interval [1/threshold, threshold].
527
+ """
528
+ lower, upper = 1 / threshold, threshold
529
+ return (
530
+ df.withColumn(
531
+ "weight_unbounded",
532
+ sf.col(target_policy_col) / sf.col(prev_policy_col),
533
+ )
534
+ .withColumn(
535
+ "weight",
536
+ sf.when(sf.col(prev_policy_col) == sf.lit(0.0), sf.lit(upper))
537
+ .when(sf.col("weight_unbounded") < sf.lit(lower), sf.lit(lower))
538
+ .when(sf.col("weight_unbounded") > sf.lit(upper), sf.lit(upper))
539
+ .otherwise(sf.col("weight_unbounded")),
540
+ )
541
+ .select("user_idx", "item_idx", "relevance", "weight")
542
+ )
543
+
544
+ def _reweighing(self, recommendations):
545
+ if self.activation == "softmax":
546
+ recommendations = self._softmax_by_user(recommendations, col_name="prev_relevance")
547
+ recommendations = self._softmax_by_user(recommendations, col_name="relevance")
548
+ elif self.activation in ["logit", "sigmoid"]:
549
+ recommendations = self._sigmoid(recommendations, col_name="prev_relevance")
550
+ recommendations = self._sigmoid(recommendations, col_name="relevance")
551
+
552
+ return self._weigh_and_clip(recommendations, self.threshold)
553
+
554
+ def _get_enriched_recommendations(
555
+ self,
556
+ recommendations: DataFrameLike,
557
+ ground_truth: DataFrameLike,
558
+ max_k: int,
559
+ ground_truth_users: Optional[DataFrameLike] = None,
560
+ ) -> SparkDataFrame:
561
+ """
562
+ Merge recommendations and ground truth into a single DataFrame
563
+ and aggregate items into lists so that each user has only one record.
564
+
565
+ :param recommendations: recommendation list
566
+ :param ground_truth: test data
567
+ :param max_k: maximal k value to calculate the metric for.
568
+ `max_k` most relevant predictions are left for each user
569
+ :param ground_truth_users: list of users to consider in metric calculation.
570
+ if None, only the users from ground_truth are considered.
571
+ :return: ``[user_idx, pred, ground_truth]``
572
+ """
573
+ recommendations = convert2spark(recommendations)
574
+ ground_truth = convert2spark(ground_truth)
575
+ ground_truth_users = convert2spark(ground_truth_users)
576
+
577
+ true_items_by_users = ground_truth.groupby("user_idx").agg(sf.collect_set("item_idx").alias("ground_truth"))
578
+
579
+ group_on = ["item_idx"]
580
+ if "user_idx" in self.prev_policy_weights.columns:
581
+ group_on.append("user_idx")
582
+ recommendations = get_top_k_recs(recommendations, k=max_k)
583
+
584
+ recommendations = recommendations.join(self.prev_policy_weights, on=group_on, how="left").na.fill(
585
+ 0.0, subset=["prev_relevance"]
586
+ )
587
+
588
+ recommendations = self._reweighing(recommendations)
589
+
590
+ weight_type = recommendations.schema["weight"].dataType
591
+ item_type = ground_truth.schema["item_idx"].dataType
592
+
593
+ recommendations = filter_sort(recommendations, "weight")
594
+
595
+ if ground_truth_users is not None:
596
+ true_items_by_users = true_items_by_users.join(ground_truth_users, on="user_idx", how="right")
597
+
598
+ recommendations = recommendations.join(true_items_by_users, how="right", on=["user_idx"])
599
+ return fill_na_with_empty_array(
600
+ fill_na_with_empty_array(recommendations, "pred", item_type),
601
+ "weight",
602
+ weight_type,
603
+ )
@@ -0,0 +1,97 @@
1
+ from typing import Optional, Union
2
+
3
+ from replay.utils import PYSPARK_AVAILABLE, DataFrameLike, IntOrList, NumType, SparkDataFrame
4
+ from replay.utils.spark_utils import convert2spark
5
+
6
+ from .base_metric import RecOnlyMetric, process_k
7
+
8
+ if PYSPARK_AVAILABLE:
9
+ from pyspark.sql import (
10
+ Window,
11
+ functions as sf,
12
+ )
13
+
14
+
15
+ class Coverage(RecOnlyMetric):
16
+ """
17
+ Metric calculation is as follows:
18
+
19
+ * take ``K`` recommendations with the biggest ``relevance`` for each ``user_id``
20
+ * count the number of distinct ``item_id`` in these recommendations
21
+ * divide it by the number of items in the whole data set
22
+
23
+ """
24
+
25
+ def __init__(self, log: DataFrameLike):
26
+ """
27
+ :param log: pandas or Spark DataFrame
28
+ It is important for ``log`` to contain all available items.
29
+ """
30
+ self.items = convert2spark(log).select("item_idx").distinct()
31
+ self.item_count = self.items.count()
32
+
33
+ @staticmethod
34
+ def _get_metric_value_by_user(k, *args):
35
+ # not averaged by users
36
+ pass
37
+
38
+ def _get_enriched_recommendations(
39
+ self,
40
+ recommendations: DataFrameLike,
41
+ ground_truth: DataFrameLike, # noqa: ARG002
42
+ max_k: int, # noqa: ARG002
43
+ ground_truth_users: Optional[DataFrameLike] = None,
44
+ ) -> SparkDataFrame:
45
+ recommendations = convert2spark(recommendations)
46
+ if ground_truth_users is not None:
47
+ ground_truth_users = convert2spark(ground_truth_users)
48
+ return recommendations.join(ground_truth_users, on="user_idx", how="inner")
49
+ return recommendations
50
+
51
+ def _conf_interval(
52
+ self,
53
+ recs: DataFrameLike, # noqa: ARG002
54
+ k_list: IntOrList,
55
+ alpha: float = 0.95, # noqa: ARG002
56
+ ) -> Union[dict[int, float], float]:
57
+ if isinstance(k_list, int):
58
+ return 0.0
59
+ return dict.fromkeys(k_list, 0.0)
60
+
61
+ def _median(
62
+ self,
63
+ recs: DataFrameLike,
64
+ k_list: IntOrList,
65
+ ) -> Union[dict[int, NumType], NumType]:
66
+ return self._mean(recs, k_list)
67
+
68
+ @process_k
69
+ def _mean(
70
+ self,
71
+ recs: SparkDataFrame,
72
+ k_list: list,
73
+ ) -> Union[dict[int, NumType], NumType]:
74
+ unknown_item_count = recs.select("item_idx").distinct().exceptAll(self.items).count()
75
+ if unknown_item_count > 0:
76
+ self.logger.warning(
77
+ "Recommendations contain items that were not present in the log. "
78
+ r"The resulting metric value can be more than 1.0 ¯\_(ツ)_/¯"
79
+ )
80
+
81
+ best_positions = (
82
+ recs.withColumn(
83
+ "row_num",
84
+ sf.row_number().over(Window.partitionBy("user_idx").orderBy(sf.desc("relevance"))),
85
+ )
86
+ .select("item_idx", "row_num")
87
+ .groupBy("item_idx")
88
+ .agg(sf.min("row_num").alias("best_position"))
89
+ .cache()
90
+ )
91
+
92
+ res = {}
93
+ for current_k in k_list:
94
+ res[current_k] = best_positions.filter(sf.col("best_position") <= current_k).count() / self.item_count
95
+
96
+ best_positions.unpersist()
97
+ return res