replay-rec 0.21.0__py3-none-any.whl → 0.21.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 (61) hide show
  1. replay/__init__.py +1 -1
  2. replay/experimental/__init__.py +0 -0
  3. replay/experimental/metrics/__init__.py +62 -0
  4. replay/experimental/metrics/base_metric.py +603 -0
  5. replay/experimental/metrics/coverage.py +97 -0
  6. replay/experimental/metrics/experiment.py +175 -0
  7. replay/experimental/metrics/hitrate.py +26 -0
  8. replay/experimental/metrics/map.py +30 -0
  9. replay/experimental/metrics/mrr.py +18 -0
  10. replay/experimental/metrics/ncis_precision.py +31 -0
  11. replay/experimental/metrics/ndcg.py +49 -0
  12. replay/experimental/metrics/precision.py +22 -0
  13. replay/experimental/metrics/recall.py +25 -0
  14. replay/experimental/metrics/rocauc.py +49 -0
  15. replay/experimental/metrics/surprisal.py +90 -0
  16. replay/experimental/metrics/unexpectedness.py +76 -0
  17. replay/experimental/models/__init__.py +50 -0
  18. replay/experimental/models/admm_slim.py +257 -0
  19. replay/experimental/models/base_neighbour_rec.py +200 -0
  20. replay/experimental/models/base_rec.py +1386 -0
  21. replay/experimental/models/base_torch_rec.py +234 -0
  22. replay/experimental/models/cql.py +454 -0
  23. replay/experimental/models/ddpg.py +932 -0
  24. replay/experimental/models/dt4rec/__init__.py +0 -0
  25. replay/experimental/models/dt4rec/dt4rec.py +189 -0
  26. replay/experimental/models/dt4rec/gpt1.py +401 -0
  27. replay/experimental/models/dt4rec/trainer.py +127 -0
  28. replay/experimental/models/dt4rec/utils.py +264 -0
  29. replay/experimental/models/extensions/spark_custom_models/__init__.py +0 -0
  30. replay/experimental/models/extensions/spark_custom_models/als_extension.py +792 -0
  31. replay/experimental/models/hierarchical_recommender.py +331 -0
  32. replay/experimental/models/implicit_wrap.py +131 -0
  33. replay/experimental/models/lightfm_wrap.py +303 -0
  34. replay/experimental/models/mult_vae.py +332 -0
  35. replay/experimental/models/neural_ts.py +986 -0
  36. replay/experimental/models/neuromf.py +406 -0
  37. replay/experimental/models/scala_als.py +293 -0
  38. replay/experimental/models/u_lin_ucb.py +115 -0
  39. replay/experimental/nn/data/__init__.py +1 -0
  40. replay/experimental/nn/data/schema_builder.py +102 -0
  41. replay/experimental/preprocessing/__init__.py +3 -0
  42. replay/experimental/preprocessing/data_preparator.py +839 -0
  43. replay/experimental/preprocessing/padder.py +229 -0
  44. replay/experimental/preprocessing/sequence_generator.py +208 -0
  45. replay/experimental/scenarios/__init__.py +1 -0
  46. replay/experimental/scenarios/obp_wrapper/__init__.py +8 -0
  47. replay/experimental/scenarios/obp_wrapper/obp_optuna_objective.py +74 -0
  48. replay/experimental/scenarios/obp_wrapper/replay_offline.py +261 -0
  49. replay/experimental/scenarios/obp_wrapper/utils.py +85 -0
  50. replay/experimental/scenarios/two_stages/__init__.py +0 -0
  51. replay/experimental/scenarios/two_stages/reranker.py +117 -0
  52. replay/experimental/scenarios/two_stages/two_stages_scenario.py +757 -0
  53. replay/experimental/utils/__init__.py +0 -0
  54. replay/experimental/utils/logger.py +24 -0
  55. replay/experimental/utils/model_handler.py +186 -0
  56. replay/experimental/utils/session_handler.py +44 -0
  57. {replay_rec-0.21.0.dist-info → replay_rec-0.21.0rc0.dist-info}/METADATA +11 -17
  58. {replay_rec-0.21.0.dist-info → replay_rec-0.21.0rc0.dist-info}/RECORD +61 -6
  59. {replay_rec-0.21.0.dist-info → replay_rec-0.21.0rc0.dist-info}/WHEEL +0 -0
  60. {replay_rec-0.21.0.dist-info → replay_rec-0.21.0rc0.dist-info}/licenses/LICENSE +0 -0
  61. {replay_rec-0.21.0.dist-info → replay_rec-0.21.0rc0.dist-info}/licenses/NOTICE +0 -0
replay/__init__.py CHANGED
@@ -4,4 +4,4 @@
4
4
  # functionality removed in Python 3.12 is used in downstream packages (like lightfm)
5
5
  import setuptools as _
6
6
 
7
- __version__ = "0.21.0"
7
+ __version__ = "0.21.0.preview"
File without changes
@@ -0,0 +1,62 @@
1
+ """
2
+ Most metrics require dataframe with recommendations
3
+ and dataframe with ground truth values —
4
+ which objects each user interacted with.
5
+
6
+ - recommendations (Union[pandas.DataFrame, spark.DataFrame]):
7
+ predictions of a recommender system,
8
+ DataFrame with columns ``[user_id, item_id, relevance]``
9
+ - ground_truth (Union[pandas.DataFrame, spark.DataFrame]):
10
+ test data, DataFrame with columns
11
+ ``[user_id, item_id, timestamp, relevance]``
12
+
13
+ Metric is calculated for all users, presented in ``ground_truth``
14
+ for accurate metric calculation in case when the recommender system generated
15
+ recommendation not for all users. It is assumed, that all users,
16
+ we want to calculate metric for, have positive interactions.
17
+
18
+ But if we have users, who observed the recommendations, but have not responded,
19
+ those users will be ignored and metric will be overestimated.
20
+ For such case we propose additional optional parameter ``ground_truth_users``,
21
+ the dataframe with all users, which should be considered during the metric calculation.
22
+
23
+ - ground_truth_users (Optional[Union[pandas.DataFrame, spark.DataFrame]]):
24
+ full list of users to calculate metric for, DataFrame with ``user_id`` column
25
+
26
+ Every metric is calculated using top ``K`` items for each user.
27
+ It is also possible to calculate metrics
28
+ using multiple values for ``K`` simultaneously.
29
+ In this case the result will be a dictionary and not a number.
30
+
31
+ Make sure your recommendations do not contain user-item duplicates
32
+ as duplicates could lead to the wrong calculation results.
33
+
34
+ - k (Union[Iterable[int], int]):
35
+ a single number or a list, specifying the
36
+ truncation length for recommendation list for each user
37
+
38
+ By default, metrics are averaged by users,
39
+ but you can alternatively use method ``metric.median``.
40
+ Also, you can get the lower bound
41
+ of ``conf_interval`` for a given ``alpha``.
42
+
43
+ Diversity metrics require extra parameters on initialization stage,
44
+ but do not use ``ground_truth`` parameter.
45
+
46
+ For each metric, a formula for its calculation is given, because this is
47
+ important for the correct comparison of algorithms, as mentioned in our
48
+ `article <https://arxiv.org/abs/2206.12858>`_.
49
+ """
50
+
51
+ from replay.experimental.metrics.base_metric import Metric, NCISMetric
52
+ from replay.experimental.metrics.coverage import Coverage
53
+ from replay.experimental.metrics.hitrate import HitRate
54
+ from replay.experimental.metrics.map import MAP
55
+ from replay.experimental.metrics.mrr import MRR
56
+ from replay.experimental.metrics.ncis_precision import NCISPrecision
57
+ from replay.experimental.metrics.ndcg import NDCG
58
+ from replay.experimental.metrics.precision import Precision
59
+ from replay.experimental.metrics.recall import Recall
60
+ from replay.experimental.metrics.rocauc import RocAuc
61
+ from replay.experimental.metrics.surprisal import Surprisal
62
+ from replay.experimental.metrics.unexpectedness import Unexpectedness
@@ -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
+ )