recsyslearn 3.0.0__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.
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ __author__ = "Giulio Davide Carparelli"
4
+ __email__ = "giulio.davide.97@gmail.com"
5
+ __version__ = "3.0.0"
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from .metrics import NDCG, AccuracyMetric
4
+
5
+ __all__ = ["NDCG", "AccuracyMetric"]
@@ -0,0 +1,109 @@
1
+ import warnings
2
+ from abc import ABC
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+ from recsyslearn.errors.errors import RecListTooShortException
8
+ from recsyslearn.utils import check_columns_exist
9
+
10
+
11
+ class AccuracyMetric(ABC):
12
+ def __init__(self) -> None:
13
+ return
14
+
15
+
16
+ class NDCG(AccuracyMetric):
17
+
18
+ """
19
+ NDCG evaluator for recommender systems.
20
+ """
21
+
22
+ @classmethod
23
+ def __dcg(cls, scores: pd.DataFrame) -> float:
24
+ return np.sum(
25
+ np.divide(
26
+ np.power(2, scores) - 1,
27
+ np.log(np.arange(scores.shape[0], dtype=np.float32) + 2),
28
+ ),
29
+ dtype=np.float32,
30
+ )
31
+
32
+ @classmethod
33
+ def __ndcg(
34
+ cls,
35
+ ranked_list: pd.DataFrame,
36
+ pos_items: pd.DataFrame,
37
+ relevance: pd.DataFrame = None,
38
+ at: int = None,
39
+ ) -> float:
40
+ if relevance is None:
41
+ relevance = np.ones_like(pos_items, dtype=np.int32)
42
+ assert len(relevance) == pos_items.shape[0]
43
+
44
+ it2rel = {it: r for it, r in zip(pos_items, relevance)}
45
+
46
+ rank_scores = np.asarray(
47
+ [it2rel.get(it, 0.0) for it in ranked_list[:at]], dtype=np.float32
48
+ )
49
+ ideal_dcg = cls.__dcg(np.sort(relevance)[::-1][:at])
50
+ rank_dcg = cls.__dcg(rank_scores)
51
+
52
+ if rank_dcg == 0:
53
+ return 0
54
+
55
+ ndcg_ = rank_dcg / ideal_dcg
56
+
57
+ return ndcg_
58
+
59
+ @classmethod
60
+ def evaluate(
61
+ cls, top_n: pd.DataFrame, pos_items: pd.DataFrame, ats: tuple = (5, 10)
62
+ ) -> pd.Series:
63
+ """Compute the NDCG@k of a model by using its recommendation list.
64
+ Returns the NDCG averaged over users.
65
+
66
+ :param top_n: Top N recommendations' lists for every user. Columns: ['user', 'item', 'rank'].
67
+ :type top_n: pd.DataFrame
68
+ :param pos_items: Relevant items per user. Columns: ['user', 'pos_items'].
69
+ :type pos_items: pd.DataFrame
70
+ :param ats: The tuple of values at which to evaluate NDCG@k.
71
+ :type ats: tuple, default (5, 10)
72
+ :raises ColumnsNotExistException: If top_n does not contain columns ('user', 'item', 'rank') or pos_items does not contain columns ('user', 'pos_items').
73
+ :raises RecListTooShortException: If the top_n list does not contain enough items.
74
+ :return: The NDCG@n averaged over users, in the form ('NDCG@k_0', ..., 'NDCG@k_n')
75
+ :rtype: pd.Series
76
+ """
77
+
78
+ check_columns_exist(top_n, ["user", "item", "rank"])
79
+ check_columns_exist(pos_items, ["user", "pos_items"])
80
+
81
+ min_calculable_at = top_n.groupby("user").size().min()
82
+ calculable_ats = [k for k in ats if k <= min_calculable_at]
83
+
84
+ if len(calculable_ats) == 0:
85
+ raise RecListTooShortException(ats)
86
+
87
+ if len(calculable_ats) != len(ats):
88
+ non_calulable_ats = list(set(calculable_ats) - set(ats))
89
+ warnings.warn(non_calulable_ats.join(" ") + " ats won't be calculated")
90
+
91
+ top_n = top_n[["user", "item", "rank"]]
92
+ top_n = (
93
+ top_n[["user", "item"]]
94
+ .groupby("user")["item"]
95
+ .apply(np.asarray)
96
+ .reset_index()
97
+ )
98
+ full_df = top_n.merge(pos_items, on="user")
99
+
100
+ for k in calculable_ats:
101
+ full_df.loc[:, f"NDCG@{k}"] = full_df.apply(
102
+ lambda x: cls.__ndcg(x["item"][:k], x["pos_items"], at=k), axis=1
103
+ )
104
+
105
+ cols_to_be_returned = [
106
+ col for col in full_df.columns if col not in ["item", "pos_items"]
107
+ ]
108
+
109
+ return full_df.loc[:, cols_to_be_returned]
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from .metrics import BeyondAccuracyMetric, Coverage, Novelty
4
+
5
+ __all__ = ["Coverage", "Novelty", "BeyondAccuracyMetric"]
@@ -0,0 +1,75 @@
1
+ from abc import ABC
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ from recsyslearn.utils import check_columns_exist
7
+
8
+
9
+ class BeyondAccuracyMetric(ABC):
10
+
11
+ """
12
+ Abstract Class for Metrics.
13
+ """
14
+
15
+ def __init__(self) -> None:
16
+ return
17
+
18
+
19
+ class Coverage(BeyondAccuracyMetric):
20
+
21
+ """
22
+ Coverage evaluator for recommender systems.
23
+ Used formula can be found here https://doi.org/10.1007/s13735-018-0154-2
24
+ """
25
+
26
+ @classmethod
27
+ def evaluate(cls, top_n: pd.DataFrame, items: list) -> float:
28
+ """
29
+ Compute the coverage of a model by using its recommendation list.
30
+
31
+ :param top_n: Top-N recommendations' lists for every user with items or users already segmented.
32
+ :type top_n: pd.DataFrame
33
+ :param items: List of items in the dataset.
34
+ :type items: list or array-like
35
+ :raises ColumnsNotExistException: If top_n not in the form ('user', 'item', 'rank', 'group').
36
+ :return: The computed coverage.
37
+ :rtype: float
38
+ """
39
+
40
+ check_columns_exist(top_n, ["user", "item", "rank"])
41
+ return len(top_n.item.unique().tolist()) / len(items)
42
+
43
+
44
+ class Novelty(BeyondAccuracyMetric):
45
+
46
+ """
47
+ Novelty evaluator for recommender systems.
48
+ Used formula can be found here https://doi.org/10.1007/s13735-018-0154-2
49
+ where popularity is defined in terms of the segmentation of the item groups
50
+ (e.g. short head -> 3, mid tail -> 2, long tail -> 1)
51
+ or in terms of percentage of user-item interactions.
52
+ """
53
+
54
+ @classmethod
55
+ def evaluate(cls, top_n: pd.DataFrame, popularity_definition="group") -> float:
56
+ """
57
+ Compute the novelty of a model by using its recommendation list and the segmented item groups.
58
+
59
+ :param top_n: Top-N recommendations' lists for every user with items or users already segmented.
60
+ :type top_n: pd.DataFrame
61
+ :param popularity_definition: Either 'group' or 'percentage', to choose whether popularity is computed in terms of
62
+ segmenting items/users according to the distribution of user-item interactions
63
+ or if it is defined as the percentage of user-item interactions.
64
+ :type popularity_definition: str
65
+ :raises ColumnsNotExistException: If top_n not in the form ('user', 'item', 'rank', popularity_definition).
66
+ :return: The computed novelty.
67
+ :rtype: float
68
+ """
69
+
70
+ check_columns_exist(top_n, ["user", "item", "rank", popularity_definition])
71
+ top_n[popularity_definition] = pd.to_numeric(top_n[popularity_definition])
72
+ top_n = top_n.groupby("user")[popularity_definition].apply(
73
+ lambda x: np.mean(-np.log2(x.astype(float)))
74
+ )
75
+ return top_n.mean()
@@ -0,0 +1,19 @@
1
+ from __future__ import annotations
2
+
3
+ from .segmentations import (
4
+ ActivitySegmentation,
5
+ DiscreteFeatureSegmentation,
6
+ InteractionSegmentation,
7
+ PopularityPercentage,
8
+ Segmentation,
9
+ )
10
+ from .utils import find_relevant_items
11
+
12
+ __all__ = [
13
+ "Segmentation",
14
+ "ActivitySegmentation",
15
+ "DiscreteFeatureSegmentation",
16
+ "InteractionSegmentation",
17
+ "PopularityPercentage",
18
+ "find_relevant_items",
19
+ ]
@@ -0,0 +1,235 @@
1
+ from abc import ABC
2
+ from collections import Counter
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+ from recsyslearn.errors.errors import (
8
+ InvalidGroupException,
9
+ InvalidValueException,
10
+ SegmentationNotSupportedException,
11
+ WrongProportionsException,
12
+ )
13
+
14
+
15
+ class Segmentation(ABC):
16
+
17
+ """
18
+ Abstract class for different group segmentations.
19
+ """
20
+
21
+ def __init__(self) -> None:
22
+ super().__init__()
23
+
24
+
25
+ class InteractionSegmentation(Segmentation):
26
+
27
+ """
28
+ Segmentation of items based on the number of cumulative interaction they have.
29
+ """
30
+
31
+ @classmethod
32
+ def segment(
33
+ cls,
34
+ dataset: pd.DataFrame,
35
+ proportions=None,
36
+ min_interaction: int = 0,
37
+ group="item",
38
+ ) -> pd.DataFrame:
39
+ """
40
+ Segmentation of items based on their cumulative interactions with different users.
41
+
42
+ :param dataset: The complete dataset.
43
+ :type dataset: pd.DataFrame
44
+ :param proportions: The proportion of interactions wanted for every group.
45
+ :type proportions: list, default [0.8, 0.2]
46
+ :param min_interaction: The minimum number of interaction allowed for items. Items below this threshold will be removed.
47
+ :type min_interaction: int, default 0
48
+ :param group: The group which has to be segmented based on their number of interaction.
49
+ :type group: str, default 'item'
50
+ :raises SegmentationNotSupportedException: If len(proportions) not in (1, 2, 3).
51
+ :raises WrongProportionsException: If sum(proportions) is not 1, which means it doesn't cover all the items/users.
52
+ :raises InvalidGroupException: If group is not equal to 'user' or 'item'.
53
+ :return: DataFrame with items and belonging group.
54
+ :rtype: pd.DataFrame
55
+ """
56
+
57
+ if proportions is None:
58
+ proportions = [0.8, 0.2]
59
+
60
+ if len(proportions) == 1:
61
+ return dataset
62
+
63
+ if len(proportions) not in (2, 3):
64
+ raise SegmentationNotSupportedException(
65
+ "Number of supported group is between 1 and 3."
66
+ )
67
+
68
+ if np.sum(proportions * 10) / 10 != 1:
69
+ raise WrongProportionsException()
70
+
71
+ if group not in ["user", "item"]:
72
+ raise InvalidGroupException(group)
73
+
74
+ item_groups = (
75
+ dataset.groupby(group)
76
+ .size()
77
+ .reset_index(name="count")
78
+ .sort_values("count", ascending=False)
79
+ )
80
+
81
+ tmp = item_groups[item_groups["count"] > min_interaction]
82
+ n_int = tmp["count"].sum()
83
+
84
+ short_thr = np.rint(proportions[0] * n_int)
85
+ mid_thr = np.rint(proportions[1] * n_int) + short_thr
86
+ tmp.loc[:, "cumulative_sum"] = tmp["count"].cumsum()
87
+
88
+ short_head = tmp.loc[tmp["cumulative_sum"].lt(short_thr), group]
89
+ mid_tail = tmp.loc[
90
+ tmp["cumulative_sum"].lt(mid_thr) & ~tmp[group].isin(short_head), group
91
+ ]
92
+ conditions = [
93
+ item_groups[group].isin(short_head),
94
+ item_groups[group].isin(mid_tail),
95
+ ]
96
+ choices = (1, 2)
97
+ default = len(proportions)
98
+ item_groups.loc[:, "group"] = np.select(conditions, choices, default=default)
99
+ return item_groups[[group, "group"]].astype({f"{group}": str, "group": str})
100
+
101
+
102
+ class PopularityPercentage(Segmentation):
103
+
104
+ """
105
+ Calculate item or user popularity based on the percentage of interaction they have.
106
+ """
107
+
108
+ @classmethod
109
+ def segment(cls, dataset: pd.DataFrame, group: str = "item") -> pd.DataFrame:
110
+ """
111
+ Calculate item or user popularity based on the percentage of interaction they have.
112
+
113
+ :param dataset: The complete dataset.
114
+ :type dataset: pd.DataFrame
115
+ :param group: Whether to calculate the popularity of users or items.
116
+ :type group: str, default 'item'
117
+ :return: DataFrame with items/user and corresponding popularity.
118
+ :rtype: pd.DataFrame
119
+ """
120
+
121
+ item_interactions = dataset[group].values
122
+ total_interactions = len(item_interactions)
123
+ inter_counter = Counter(item_interactions)
124
+ inter_counter = {
125
+ item: counts / total_interactions for item, counts in inter_counter.items()
126
+ }
127
+
128
+ popularity_dataframe = pd.DataFrame.from_dict(
129
+ inter_counter, orient="index"
130
+ ).reset_index()
131
+ popularity_dataframe.columns = [group, "percentage"]
132
+
133
+ return popularity_dataframe
134
+
135
+
136
+ class ActivitySegmentation(Segmentation):
137
+
138
+ """
139
+ Segmentation of users based on their number of interaction.
140
+ """
141
+
142
+ @classmethod
143
+ def segment(
144
+ cls, dataset: pd.DataFrame, proportions=None, min_interaction: int = 0
145
+ ) -> pd.DataFrame:
146
+ """
147
+ Segmentation of users based on their interactions with different items.
148
+
149
+ :param dataset: The complete dataset.
150
+ :type dataset: pd.DataFrame
151
+ :param proportions: The proportion of interactions wanted for every group.
152
+ :type proportions: list, default [0.8, 0.2]
153
+ :param min_interaction: The minimum number of interaction allowed per user. Users below this threshold will be removed.
154
+ :type min_interaction: int, default 0
155
+ :raises SegmentationNotSupportedException: If len(proportion) not in (1, 2, 3).
156
+ :raises WrongProportionsException: If sum(proportion) is not 1, which means it doesn't cover all the items/users.
157
+ :return: DataFrame with users and belonging group.
158
+ :rtype: pd.DataFrame
159
+ """
160
+
161
+ if proportions is None:
162
+ proportions = [0.1, 0.9]
163
+
164
+ if len(proportions) == 1:
165
+ return dataset
166
+
167
+ if len(proportions) not in (2, 3):
168
+ raise SegmentationNotSupportedException(
169
+ "Number of supported group is between 1 and 3."
170
+ )
171
+
172
+ if np.sum(proportions * 10) / 10 != 1:
173
+ raise WrongProportionsException()
174
+
175
+ user_groups = dataset.groupby("user").size().reset_index(name="count")
176
+ user_groups = user_groups.loc[user_groups["count"] >= min_interaction, :]
177
+
178
+ user_groups.loc[:, "count"] = user_groups.loc[:, "count"].apply(
179
+ lambda x: x + np.random.choice(list(range(10)))
180
+ )
181
+ user_groups = user_groups.sort_values("count", ascending=False)
182
+ user_groups.loc[:, "count"] = np.arange(user_groups.shape[0]) + 1
183
+ first_thr = np.rint(proportions[0] * user_groups.shape[0])
184
+ second_thr = np.rint(proportions[1] * user_groups.shape[0]) + first_thr
185
+ first_thr = first_thr if first_thr > 0 else 1
186
+ first_group = user_groups.loc[user_groups["count"] <= first_thr, "user"]
187
+ second_group = user_groups.loc[user_groups["count"].lt(second_thr), "user"]
188
+
189
+ conditions = [
190
+ user_groups["user"].isin(first_group),
191
+ user_groups["user"].isin(second_group),
192
+ ]
193
+ choices = (1, 2)
194
+ default = len(proportions)
195
+ user_groups.loc[:, "group"] = np.select(conditions, choices, default=default)
196
+
197
+ return user_groups[["user", "group"]].astype({"user": str, "group": str})
198
+
199
+
200
+ class DiscreteFeatureSegmentation(Segmentation):
201
+
202
+ """
203
+ Segmentation of entities (users or items) according to one of
204
+ their features (e.g., gender for users or genre for items)
205
+ """
206
+
207
+ @classmethod
208
+ def segment(cls, feature: pd.DataFrame, fill_na: int = -1) -> pd.DataFrame:
209
+ """
210
+ Segmentation of users/items based on one of their features.
211
+ Before assigning the group, the nans are given a -1 value by default.
212
+ Make sure that this is not one of the feature values, already.
213
+
214
+ :param feature: The feature dataframe in form of [id, feature] storing the categorical feature to be used for grouping.
215
+ :type feature: pd.DataFrame
216
+ :param fill_na: The value with which to fill not assigned values. Default is -1.
217
+ :type fill_na: int, default -1
218
+ :raises InvalidValueException: If the fill_na value is already present in the features dataframe.
219
+ :return: DataFrame with items and belonging group.
220
+ :rtype: pd.DataFrame
221
+ """
222
+
223
+ if fill_na in feature[feature.columns[1]].unique():
224
+ raise InvalidValueException(fill_na)
225
+
226
+ # The str dtype (default for strings since pandas 3) rejects a non-string fill_na
227
+ if isinstance(feature[feature.columns[1]].dtype, pd.StringDtype):
228
+ feature[feature.columns[1]] = feature[feature.columns[1]].astype(object)
229
+ feature = feature.fillna({str(feature.columns[1]): fill_na})
230
+
231
+ feature[feature.columns[1]] = (
232
+ feature[feature.columns[1]].astype("category").cat.codes
233
+ )
234
+ feature = feature.rename({str(feature.columns[1]): "group"}, axis="columns")
235
+ return feature
@@ -0,0 +1,22 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ from recsyslearn.utils import check_columns_exist
5
+
6
+
7
+ def find_relevant_items(target_df: pd.DataFrame) -> pd.DataFrame:
8
+ """
9
+ Find relevant items for every user in the dataset.
10
+
11
+ :param target_df: Target Interaction dataframe of, i.e., items to be recommended. Columns: ['user', 'item'].
12
+ :type target_df: pd.DataFrame
13
+ :raises ColumnsNotExistException: If target_df does not contain columns ('user', 'item').
14
+ :return: The DataFrame containing all the relevant items per user in the form ('user', 'pos_items').
15
+ :rtype: pd.DataFrame
16
+ """
17
+
18
+ check_columns_exist(target_df, ["user", "item"])
19
+ target_df = target_df[["user", "item"]]
20
+ pos_items = target_df.groupby("user")["item"].apply(np.asarray).reset_index()
21
+ pos_items.columns = ["user", "pos_items"]
22
+ return pos_items
@@ -0,0 +1,19 @@
1
+ from __future__ import annotations
2
+
3
+ from .errors import (
4
+ ColumnsNotExistException,
5
+ InvalidGroupException,
6
+ InvalidValueException,
7
+ RecListTooShortException,
8
+ SegmentationNotSupportedException,
9
+ WrongProportionsException,
10
+ )
11
+
12
+ __all__ = [
13
+ "ColumnsNotExistException",
14
+ "InvalidGroupException",
15
+ "InvalidValueException",
16
+ "RecListTooShortException",
17
+ "SegmentationNotSupportedException",
18
+ "WrongProportionsException",
19
+ ]
@@ -0,0 +1,57 @@
1
+ class ColumnsNotExistException(Exception):
2
+
3
+ """Exception raised when columns are not found in the DataFrame."""
4
+
5
+ def __init__(
6
+ self, columns: list, message: str = "Dataframe does not contain columns."
7
+ ) -> None:
8
+ super().__init__(f"{message} {columns}")
9
+
10
+
11
+ class RecListTooShortException(Exception):
12
+
13
+ """Exception raised when the values for the recommendation list length is not compatbile with the dataset."""
14
+
15
+ def __init__(
16
+ self,
17
+ ats: int,
18
+ message: str = "Values for the recommendation list length is not compatbile with the dataset.",
19
+ ) -> None:
20
+ super().__init__(f"{message} ats={ats}")
21
+
22
+
23
+ class SegmentationNotSupportedException(Exception):
24
+
25
+ """Exception raised when there are too many group to be segmented."""
26
+
27
+ def __init__(self, message: str) -> None:
28
+ super().__init__(message)
29
+
30
+
31
+ class WrongProportionsException(Exception):
32
+
33
+ """Exception raised when proportions of the segmentation does not cover all the items or users."""
34
+
35
+ def __init__(
36
+ self, message: str = "Proportions doesn't cover all the items/users."
37
+ ) -> None:
38
+ super().__init__(message)
39
+
40
+
41
+ class InvalidValueException(Exception):
42
+
43
+ """Exception raised when the value of fill_na of the segmentation value is invalid."""
44
+
45
+ def __init__(self, fill_na) -> None:
46
+ message = (
47
+ f"Feature contains {fill_na} as value. Please select another fill_na value."
48
+ )
49
+ super().__init__(message)
50
+
51
+
52
+ class InvalidGroupException(Exception):
53
+
54
+ """Exception raised when user wants to segment a non valid group"""
55
+
56
+ def __init__(self, user_group) -> None:
57
+ super().__init__(f"{user_group} is not a valid group")
@@ -0,0 +1 @@
1
+ from __future__ import annotations
@@ -0,0 +1,146 @@
1
+ from abc import ABC
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ from recsyslearn.fairness.utils import eff_matrix, exp_matrix, prob_matrix
7
+ from recsyslearn.utils import check_columns_exist
8
+
9
+
10
+ class FairnessMetric(ABC):
11
+
12
+ """
13
+ Abstract Class for Metrics.
14
+ """
15
+
16
+ def __init__(self) -> None:
17
+ return
18
+
19
+
20
+ class Entropy(FairnessMetric):
21
+
22
+ """
23
+ Entropy evaluator for recommender systems.
24
+ """
25
+
26
+ def evaluate(self, top_n: pd.DataFrame, rel_matrix: pd.DataFrame = None) -> float:
27
+ """
28
+ Compute the entropy of a model by using its recommendation list.
29
+
30
+ :param top_n: Top N recommendations' lists for every user with items or users already segmented.
31
+ :type top_n: pd.DataFrame
32
+ :param rel_matrix: Relevant items for users. It could be, for example, the items with a rating >= threshold.
33
+ :type rel_matrix: pd.DataFrame, default None
34
+ :raises ColumnsNotExistException: If top_n not in the form ('user', 'item', 'rank', 'group').
35
+ :return: The computed entropy.
36
+ :rtype: float
37
+ """
38
+
39
+ check_columns_exist(top_n, ["user", "item", "rank", "group"])
40
+
41
+ top_n = eff_matrix(top_n, rel_matrix) if rel_matrix is not None else top_n
42
+ top_n = prob_matrix(top_n)
43
+ top_n = top_n[["group", "rank"]].groupby("group", as_index=False).sum()
44
+ top_n["rank"] = top_n["rank"] * np.log2(top_n["rank"])
45
+ return -top_n["rank"].sum()
46
+
47
+
48
+ class KullbackLeibler(FairnessMetric):
49
+
50
+ """
51
+ Kullback-Leibler divergence evaluator for recommender systems.
52
+ """
53
+
54
+ def evaluate(
55
+ self,
56
+ top_n: pd.DataFrame,
57
+ target_representation: pd.DataFrame,
58
+ rel_matrix: pd.DataFrame = None,
59
+ ) -> float:
60
+ """
61
+ Compute the Kullback-Leibler divergence of a model, for a given target representation, by using its recommendation list.
62
+
63
+ :param top_n: Top N recommendations' lists for every user with items or users already segmented.
64
+ :type top_n: pd.DataFrame
65
+ :param target_representation: The target representation desired for each group.
66
+ :type target_representation: pd.DataFrame
67
+ :param rel_matrix: Relevant items for users. It could be, for example, the items with a rating >= threshold.
68
+ :type rel_matrix: pd.DataFrame, default None
69
+ :raises ColumnsNotExistException: If top_n not in the form ('user', 'item', 'rank', 'group') or if target_representation not in the form ('group', 'target_representation').
70
+ :return: The computed KL Divergence for the given target representation.
71
+ :rtype: float
72
+ """
73
+
74
+ check_columns_exist(top_n, ["user", "item", "rank", "group"])
75
+ check_columns_exist(target_representation, ["group", "target_representation"])
76
+
77
+ top_n = (
78
+ eff_matrix(top_n, rel_matrix)
79
+ if rel_matrix is not None
80
+ else exp_matrix(top_n)
81
+ )
82
+ top_n = prob_matrix(top_n)
83
+ top_n = top_n[["group", "rank"]].groupby("group", as_index=False).sum()
84
+ top_n = top_n.merge(target_representation, on="group")
85
+ top_n["rank"] = top_n["rank"] * np.log2(
86
+ top_n["rank"] / top_n["target_representation"]
87
+ )
88
+ return top_n["rank"].sum()
89
+
90
+
91
+ class MutualInformation(FairnessMetric):
92
+
93
+ """
94
+ Mutual Information evaluator for recommender systems.
95
+ """
96
+
97
+ def evaluate(
98
+ self, top_n: pd.DataFrame, flag: str, rel_matrix: pd.DataFrame = None
99
+ ) -> float:
100
+ """
101
+ Compute the Mutual Information of a model by using its recommendation list.
102
+
103
+ :param top_n: Top N recommendations' lists for every user with items or users already segmented.
104
+ :type top_n: pd.DataFrame
105
+ :param flag: Which actor of the recommendation scenario has been segmented (i.e. user).
106
+ :type flag: str
107
+ :param rel_matrix: Relevant items for users. It could be, for example, the items with a rating >= threshold.
108
+ :type rel_matrix: pd.DataFrame, default None
109
+ :raises ColumnsNotExistException: If top_n not in the form ('user', 'item', 'rank', 'group').
110
+ :raises KeyError: If flag is neither 'user' nor 'item'.
111
+ :return: The computed Mutual Information.
112
+ :rtype: float
113
+ """
114
+
115
+ check_columns_exist(top_n, ["user", "item", "rank", "group"])
116
+
117
+ not_flagged = {"user": "item", "item": "user"}
118
+ if flag not in not_flagged:
119
+ raise KeyError(f"Invalid flag {flag!r}, expected 'user' or 'item'")
120
+
121
+ top_n = (
122
+ eff_matrix(top_n, rel_matrix)
123
+ if rel_matrix is not None
124
+ else exp_matrix(top_n)
125
+ )
126
+ top_n = prob_matrix(top_n)
127
+ not_grouped = not_flagged.get(flag)
128
+ P_xy = (
129
+ top_n[[not_grouped, "group", "rank"]]
130
+ .groupby([not_grouped, "group"], as_index=False)
131
+ .sum()
132
+ )
133
+ P_xP_y = (
134
+ top_n[[not_grouped, "group", "rank"]]
135
+ .groupby(not_grouped, as_index=False)
136
+ .agg({"rank": "sum"})
137
+ )
138
+ P_xP_y = P_xy[[not_grouped, "group"]].merge(P_xP_y, on=not_grouped)
139
+ tmp = top_n[["group", "rank"]].groupby("group", as_index=False).sum()
140
+ P_xP_y = P_xP_y.merge(tmp, on=["group"])
141
+ P_xP_y["rank"] = P_xP_y["rank_x"] * P_xP_y["rank_y"]
142
+ tmp = P_xP_y[[not_grouped, "group", "rank"]].merge(
143
+ P_xy, on=[not_grouped, "group"]
144
+ )
145
+ tmp["rank"] = tmp["rank_y"] * np.log2(tmp["rank_y"] / tmp["rank_x"])
146
+ return tmp["rank"].sum()
@@ -0,0 +1,62 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ from recsyslearn.utils import check_columns_exist
5
+
6
+
7
+ def exp_matrix(top_n: pd.DataFrame) -> pd.DataFrame:
8
+ """
9
+ Compute exposure matrix for given recommendation lists.
10
+
11
+ :param top_n: Recommendation lists per user in the form (user, item, rank, group).
12
+ :type top_n: pd.DataFrame
13
+ :raises ColumnsNotExistException: If top_n is not in the form (user, item, rank, group).
14
+ :return: The DataFrame with computed exposure.
15
+ :rtype: pd.DataFrame
16
+ """
17
+
18
+ check_columns_exist(top_n, ["user", "item", "rank", "group"])
19
+
20
+ top_n["rank"] = 1 / np.log2(1 + top_n["rank"])
21
+ return top_n
22
+
23
+
24
+ def prob_matrix(top_n: pd.DataFrame) -> pd.DataFrame:
25
+ """
26
+ Compute probability distribution matrix for given recommendation lists.
27
+
28
+ :param top_n: Recommendation lists per user in the form (user, item, rank, group).
29
+ :type top_n: pd.DataFrame
30
+ :raises ColumnsNotExistException: If top_n is not in the form (user, item, rank, group).
31
+ :return: The DataFrame with computed probability distribution.
32
+ :rtype: pd.DataFrame
33
+ """
34
+
35
+ check_columns_exist(top_n, ["user", "item", "rank", "group"])
36
+
37
+ top_n["rank"] = top_n["rank"] / top_n["rank"].sum()
38
+ return top_n
39
+
40
+
41
+ def eff_matrix(top_n: pd.DataFrame, rel_matrix: pd.DataFrame) -> pd.DataFrame:
42
+ """
43
+ Compute effectiveness matrix for given recommendation lists.
44
+
45
+ :param top_n: Recommendation lists per user in the form (user, item, rank, group).
46
+ :type top_n: pd.DataFrame
47
+ :param rel_matrix: Dataframe containing relevant items for every user.
48
+ :type rel_matrix: pd.DataFrame
49
+ :raises ColumnsNotExistException: If top_n header is not in the form (user, item, rank, group)
50
+ of if rel_matrix header is not in the form (user, item, rank).
51
+ :return: The DataFrame with computed effectiveness.
52
+ :rtype: pd.DataFrame
53
+ """
54
+
55
+ check_columns_exist(top_n, ["user", "item", "rank", "group"])
56
+ check_columns_exist(rel_matrix, ["user", "item", "rank", "group"])
57
+
58
+ top_n = exp_matrix(top_n)
59
+ top_n = top_n.merge(rel_matrix, on=["user", "item", "group"], how="outer")
60
+ top_n.loc[:, ["rank_x", "rank_y"]] = top_n.loc[:, ["rank_x", "rank_y"]].fillna(0)
61
+ top_n["rank"] = top_n["rank_x"] * top_n["rank_y"]
62
+ return top_n[["user", "item", "rank", "group"]]
recsyslearn/utils.py ADDED
@@ -0,0 +1,30 @@
1
+ import pandas as pd
2
+
3
+ from recsyslearn.errors.errors import ColumnsNotExistException
4
+
5
+
6
+ def check_columns_exist(df: pd.DataFrame, columns: list) -> pd.DataFrame:
7
+ """
8
+ Raise ColumnsNotExistException if pd.Dataframe does not contain the expected columns.
9
+
10
+ :param df: Input that should be tested.
11
+ :type df: pd.DataFrame
12
+ :param columns: pd.DataFrame columns that should be contained.
13
+ :type columns: list
14
+ :raises ColumnsNotExistException: If input does not contained expected columns.
15
+ :return: The DataFrame with the expected columns and types.
16
+ :rtype: pd.DataFrame
17
+ """
18
+
19
+ if not set(columns).issubset(set(df.columns)):
20
+ raise ColumnsNotExistException(columns)
21
+
22
+ dtypes = {
23
+ "user": str,
24
+ "item": str,
25
+ "rank": float,
26
+ "group": str,
27
+ "target_representation": float,
28
+ }
29
+
30
+ return df.astype({col: dtypes[col] for col in df.columns if col in dtypes.keys()})
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: recsyslearn
3
+ Version: 3.0.0
4
+ Summary: A library to compute fairness of recommender systems.
5
+ Author-email: Giulio Davide Carparelli <giulio.davide.97@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/giuliowaitforitdavide/recsyslearn
8
+ Project-URL: Documentation, https://recsyslearn.readthedocs.io
9
+ Keywords: recsyslearn
10
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
11
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/x-rst
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy>=1.26
19
+ Requires-Dist: pandas>=2.1
20
+ Dynamic: license-file
21
+
22
+ ===========
23
+ Recsyslearn
24
+ ===========
25
+
26
+
27
+ .. image:: https://github.com/giuliowaitforitdavide/recsyslearn/actions/workflows/tests.yml/badge.svg
28
+ :target: https://github.com/giuliowaitforitdavide/recsyslearn/actions/workflows/tests.yml
29
+ :alt: Test Status
30
+
31
+ .. image:: https://readthedocs.org/projects/recsyslearn/badge/?version=latest
32
+ :target: https://recsyslearn.readthedocs.io/en/latest/?version=latest
33
+ :alt: Documentation Status
34
+
35
+ .. image:: https://img.shields.io/pypi/v/recsyslearn.svg
36
+ :target: https://pypi.python.org/pypi/recsyslearn
37
+ :alt: Library Version
38
+
39
+
40
+ *recsyslearn* is a Python library designed to evaluate recommendation systems comprehensively.
41
+ It offers a set of tools to measure recommendation accuracy, coverage, novelty, and fairness.
42
+ This library is a valuable resource for data scientists and engineers who aim to enhance the performance
43
+ and fairness of their recommendation algorithms.
44
+
45
+
46
+ Key Features
47
+ ------------
48
+
49
+
50
+ Dataset Utilities
51
+ ^^^^^^^^^^^^^^^^^
52
+
53
+ *recsyslearn* simplifies the process of calculating item popularity and user activity, and of
54
+ segmenting (i.e., categorizing) users and items into groups. The users and items can be segmented
55
+ based on various criteria, hence providing the basis for group fairness analyses on
56
+ several dimensions.
57
+
58
+ In particular, the following type of segmentations are provided:
59
+ * item segmentation based on a popularity value, or user segmentation based on an activity value, corresponding to the percentage of user-item interactions.
60
+ * user or item segmentation based on one of their categorical features (e.g., user gender, or item genre).
61
+ * item segmentation based on the cumulative number of interactions of the items in each group. For instance, keeping the argument of the method to the default value of 80 − 20, the most popular items corresponding to the first group account for 80% of the interactions, and the items in the second group account for the remaining 20%.
62
+ * user segmentation based their grade of activity. For instance, keeping the argument of the method to the default value of 80 − 20, the most active 80% users will belong to the first group, and the least active 20% users to the second.
63
+
64
+
65
+ Accuracy Evaluation metrics
66
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
67
+
68
+ * NDCG@k: *recsyslearn* computes the Normalized Discounted Cumulative Gain (NDCG) metric to assess recommendation accuracy at a specific cutoff k. NDCG@k provides insights into the relevance of recommended items and their ranking.
69
+
70
+
71
+ Beyond Accuracy metrics
72
+ ^^^^^^^^^^^^^^^^^^^^^^^
73
+
74
+ * Coverage: evaluate the coverage of your recommendation system using various metrics. These metrics measure the extent to which unique items are recommended to users and provide insights into the diversity of recommendations.
75
+ * Novelty: measure the novelty of recommendations to ensure that users receive fresh and engaging content.
76
+
77
+
78
+ *recsyslearn* helps you assess the diversity and freshness of recommended items.
79
+
80
+
81
+ Fairness metrics
82
+ ^^^^^^^^^^^^^^^^
83
+
84
+ * Entropy: the measure of diversity (i.e., recommendations or accurate recommendations) over user or item groups.
85
+ * Mutual Information: measures to what extent the information on the user group provides information about the groups to which the recommendations belong.
86
+ * Kullback-Leibler: measures the KL divergence between the distribution of utility over user or item groups, computed on the list of recommendations, and a target distribution.
87
+
88
+
89
+ License
90
+ -------
91
+
92
+ Recsyslearn is released as free software under the MIT License.
93
+
94
+ Documentation
95
+ -------------
96
+
97
+ For in-depth documentation, detailed explanations of functions, and usage examples, please visit the
98
+ `official documentation`_.
99
+
100
+ Citation
101
+ --------
102
+
103
+ If you use *recsyslearn* in your research, please cite the following paper:
104
+
105
+ .. code-block:: console
106
+
107
+ @proceedings{Moscati2023MultiObjectiveHyperOpt,
108
+ title = {Multiobjective Hyperparameter Optimization of Recommender Systems},
109
+ author = {Moscati, Marta and Deldjoo, Yashar and Carparelli, Giulio Davide and Schedl, Markus},
110
+ booktitle = {Proceedings of the 3rd Workshop on Perspectives on the Evaluation of Recommender Systems co-located with the 17th ACM Conference on Recommender Systems (RecSys 2023), Singapore, Singapore.},
111
+ editor = {Said, Alan and Zangerle, Eva and Bauer, Christine},
112
+ publisher = {CEUR-WS.org},
113
+ url = {https://ceur-ws.org/Vol-3476/paper3.pdf},
114
+ volume = {3476},
115
+ year = {2023}
116
+ }
117
+
118
+
119
+ Credits
120
+ -------
121
+
122
+ This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.
123
+
124
+ .. _Cookiecutter: https://github.com/audreyr/cookiecutter
125
+ .. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage
126
+ .. _`official documentation`: https://recsyslearn.readthedocs.io/en/latest/?version=latest
127
+
@@ -0,0 +1,19 @@
1
+ recsyslearn/__init__.py,sha256=g0nF3yL8RhfoDozQoNz06Lfwg6RZIOK5hMhTH3chvAw,139
2
+ recsyslearn/utils.py,sha256=FRMa0pBfTVq12vEhfXzpVHOAd_s0cwxGlIh0l4XETeU,939
3
+ recsyslearn/accuracy/__init__.py,sha256=nAzrfgrV1rPTIq6bN6xjwpN5hfa-B2y2rVleUzjxOmM,116
4
+ recsyslearn/accuracy/metrics.py,sha256=x7cufzP6ldQ7sbbJRJ39jTQfl6rZLtFGwsTKD5beu_c,3552
5
+ recsyslearn/beyond_accuracy/__init__.py,sha256=0dqccLBPoOi37LhjCymXFH2Edqs1gbrYD8w0IEB-Y7Y,156
6
+ recsyslearn/beyond_accuracy/metrics.py,sha256=9w5TErxawHLFSBSXLKZg_PLEgM9XluHPTumyKn7BuGY,2714
7
+ recsyslearn/dataset/__init__.py,sha256=FCnLgkAQjMV8T3RHHR7awlyvFHdh23DY3597G3WMNUA,422
8
+ recsyslearn/dataset/segmentations.py,sha256=qcQwUasZ_NNopt7r9tvQXOkRGebNxmHKQ-7nrfG1QYY,8767
9
+ recsyslearn/dataset/utils.py,sha256=JEACX8fxGO1V3r6cRgLA3iYQ3dQFXJw8EY_XtFIrIEc,848
10
+ recsyslearn/errors/__init__.py,sha256=j2FV8sfFeHBxLjJp9v8CJF1fR3k0iGk5QuU5lUYzxHk,455
11
+ recsyslearn/errors/errors.py,sha256=0_ZI1dkwxx1wSKCDWX-j28t3TfeReYqUsqmFSWJDbW0,1718
12
+ recsyslearn/fairness/__init__.py,sha256=U4S_2y3zgLZVfMenHRaJFBW8yqh2mUBuI291LGQVOJ8,35
13
+ recsyslearn/fairness/metrics.py,sha256=gDeTyGrzsGySau6k3nsZeXGYAVNI28hbKWJxJB9_tWY,5524
14
+ recsyslearn/fairness/utils.py,sha256=D-1WpjxluVy1I9DUEF3nBRKmA6JSxTSH7P8sG2AMWGs,2317
15
+ recsyslearn-3.0.0.dist-info/licenses/LICENSE,sha256=iT1pOPVLzqd8N_tJOMzU5God2r7gQlP8gGNXttqkJjg,1101
16
+ recsyslearn-3.0.0.dist-info/METADATA,sha256=3WUwOQT_swN6pYAEAfG3f_l1sOjaaDFvUp-Mgjp7rZU,5696
17
+ recsyslearn-3.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
18
+ recsyslearn-3.0.0.dist-info/top_level.txt,sha256=62cW-1_ZHl_DVuaZaxFjZREqCUb01IgP8oU2qdd_u6A,12
19
+ recsyslearn-3.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-2026 Giulio Davide Carparelli, Marta Moscati
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ recsyslearn