Skip to content

evaluator

logger = logging.getLogger(__name__) module-attribute

EvaluatorPipeline dataclass

Bases: EvaluatorBase

Evaluation via pipeline.

Source code in src/recnexteval/evaluators/pipeline/evaluator.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
@dataclass(kw_only=True)
class EvaluatorPipeline(EvaluatorBase):
    """Evaluation via pipeline."""

    algo_state_mgr: AlgorithmStateManager

    def _ready_evaluator(self) -> None:
        self._data_release_step()
        logger.debug("Algorithms trained with background data...")

        self._acc = MetricAccumulator()
        logger.debug("Metric accumulator instantiated...")

        self.setting.restore()
        logger.debug("Setting data generators ready...")

    def _evaluate_step(self) -> None:
        logger.info("Phase 2: Evaluating the algorithms...")
        try:
            unlabeled_data, ground_truth_data, _ = self._get_evaluation_data()
        except EOWSettingError as e:
            raise e

        # get the top k interaction per user
        # X_true = ground_truth_data.get_users_n_first_interaction(self.metric_k)
        y_true = ground_truth_data.item_interaction_sequence_matrix
        for algo_state in self.algo_state_mgr.values():
            y_pred = algo_state.algorithm_ptr.predict(unlabeled_data)
            logger.debug("Shape of prediction matrix: %s", y_pred.shape)
            logger.debug("Shape of ground truth matrix: %s", y_true.shape)

            if not self.ignore_unknown_item:
                y_pred = self._prediction_unknown_item_handler(y_true=y_true, y_pred=y_pred)

            self._add_metric_results_for_prediction(
                ground_truth_data=ground_truth_data,
                y_pred=y_pred,
                algorithm_name=self.algo_state_mgr.get_algorithm_identifier(algo_id=algo_state.algorithm_uuid),
            )

    def _data_release_step(self) -> None:
        if self._run_step != 0 and not self.setting.is_sliding_window_setting:
            return
        training_data = self._get_training_data()
        for algo_state in self.algo_state_mgr.values():
            algo_state.algorithm_ptr.fit(training_data)

    def reset(self) -> None:
        """Reset the evaluator to initial state."""
        logger.info("Resetting the evaluator for a new run...")
        self._run_step = 0

    def run_step(self) -> None:
        """Run a single step of the evaluator."""
        if self._run_step == 0:
            logger.info(f"There is a total of {self.setting.num_split} steps. Running step {self._run_step}")
            self._ready_evaluator()

        if self._run_step > self.setting.num_split:
            logger.info("Finished running all steps, call `run_step(reset=True)` to run the evaluation again")
            warn("Running this method again will not have any effect.")
            return
        logger.info("Running step %d", self._run_step)
        self._evaluate_step()
        self._data_release_step()

    def run_steps(self, num_steps: int) -> None:
        """Run multiple steps of the evaluator.

        Effectively runs the run_step method num_steps times. Call
        this method to run multiple steps of the evaluator at once.

        Args:
            num_steps: Number of steps to run.

        Raises:
            ValueError: If cannot run the specified number of steps.
        """
        if self._run_step + num_steps > self.setting.num_split:
            raise ValueError(f"Cannot run {num_steps} steps, only {self.setting.num_split - self._run_step} steps left")
        for _ in tqdm(range(num_steps)):
            self.run_step()

    def run(self) -> None:
        """Run the evaluator across all steps and splits.

        This method should be called when the programmer wants to step through
        all phases and splits to arrive to the metrics computed. An alternative
        to running through all splits is to call the run_step method which runs
        only one step at a time.
        """
        self._ready_evaluator()

        with tqdm(total=self.setting.num_split, desc="Evaluating steps") as pbar:
            while self._run_step <= self.setting.num_split:
                logger.info("Running step %d", self._run_step)
                self._evaluate_step()
                pbar.update(1)
                # if is last step, no need to release data anymore
                # since there is no more evaluation that can be done
                # break out of the loop
                if self._run_step == self.setting.num_split:
                    break
                self._data_release_step()

algo_state_mgr instance-attribute

metric_entries instance-attribute

setting instance-attribute

metric_k instance-attribute

ignore_unknown_user = False class-attribute instance-attribute

ignore_unknown_item = False class-attribute instance-attribute

seed = 42 class-attribute instance-attribute

user_item_base = field(default_factory=UserItemKnowledgeBase) class-attribute instance-attribute

reset()

Reset the evaluator to initial state.

Source code in src/recnexteval/evaluators/pipeline/evaluator.py
61
62
63
64
def reset(self) -> None:
    """Reset the evaluator to initial state."""
    logger.info("Resetting the evaluator for a new run...")
    self._run_step = 0

run_step()

Run a single step of the evaluator.

Source code in src/recnexteval/evaluators/pipeline/evaluator.py
66
67
68
69
70
71
72
73
74
75
76
77
78
def run_step(self) -> None:
    """Run a single step of the evaluator."""
    if self._run_step == 0:
        logger.info(f"There is a total of {self.setting.num_split} steps. Running step {self._run_step}")
        self._ready_evaluator()

    if self._run_step > self.setting.num_split:
        logger.info("Finished running all steps, call `run_step(reset=True)` to run the evaluation again")
        warn("Running this method again will not have any effect.")
        return
    logger.info("Running step %d", self._run_step)
    self._evaluate_step()
    self._data_release_step()

run_steps(num_steps)

Run multiple steps of the evaluator.

Effectively runs the run_step method num_steps times. Call this method to run multiple steps of the evaluator at once.

Parameters:

Name Type Description Default
num_steps int

Number of steps to run.

required

Raises:

Type Description
ValueError

If cannot run the specified number of steps.

Source code in src/recnexteval/evaluators/pipeline/evaluator.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def run_steps(self, num_steps: int) -> None:
    """Run multiple steps of the evaluator.

    Effectively runs the run_step method num_steps times. Call
    this method to run multiple steps of the evaluator at once.

    Args:
        num_steps: Number of steps to run.

    Raises:
        ValueError: If cannot run the specified number of steps.
    """
    if self._run_step + num_steps > self.setting.num_split:
        raise ValueError(f"Cannot run {num_steps} steps, only {self.setting.num_split - self._run_step} steps left")
    for _ in tqdm(range(num_steps)):
        self.run_step()

run()

Run the evaluator across all steps and splits.

This method should be called when the programmer wants to step through all phases and splits to arrive to the metrics computed. An alternative to running through all splits is to call the run_step method which runs only one step at a time.

Source code in src/recnexteval/evaluators/pipeline/evaluator.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def run(self) -> None:
    """Run the evaluator across all steps and splits.

    This method should be called when the programmer wants to step through
    all phases and splits to arrive to the metrics computed. An alternative
    to running through all splits is to call the run_step method which runs
    only one step at a time.
    """
    self._ready_evaluator()

    with tqdm(total=self.setting.num_split, desc="Evaluating steps") as pbar:
        while self._run_step <= self.setting.num_split:
            logger.info("Running step %d", self._run_step)
            self._evaluate_step()
            pbar.update(1)
            # if is last step, no need to release data anymore
            # since there is no more evaluation that can be done
            # break out of the loop
            if self._run_step == self.setting.num_split:
                break
            self._data_release_step()

metric_results(level=MetricLevelEnum.MACRO, only_current_timestamp=False, filter_timestamp=None, filter_algo=None)

Results of the metrics computed.

Computes the metrics of all algorithms based on the level specified and return the results in a pandas DataFrame. The results can be filtered based on the algorithm name and the current timestamp.

Specifics
  • User level: User level metrics computed across all timestamps.
  • Window level: Window level metrics computed across all timestamps. This can be viewed as a macro level metric in the context of a single window, where the scores of each user is averaged within the window.
  • Macro level: Macro level metrics computed for entire timeline. This score is computed by averaging the scores of all windows, treating each window equally.
  • Micro level: Micro level metrics computed for entire timeline. This score is computed by averaging the scores of all users, treating each user and the timestamp the user is in as unique contribution to the overall score.

Parameters:

Name Type Description Default
level MetricLevelEnum | Literal['macro', 'micro', 'window', 'user']

Level of the metric to compute, defaults to "macro".

MACRO
only_current_timestamp None | bool

Filter only the current timestamp, defaults to False.

False
filter_timestamp None | int

Timestamp value to filter on, defaults to None. If both only_current_timestamp and filter_timestamp are provided, filter_timestamp will be used.

None
filter_algo None | str

Algorithm name to filter on, defaults to None.

None

Returns:

Type Description
DataFrame

Dataframe representation of the metric.

Source code in src/recnexteval/evaluators/core/base.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def metric_results(
    self,
    level: MetricLevelEnum | Literal["macro", "micro", "window", "user"] = MetricLevelEnum.MACRO,
    only_current_timestamp: None | bool = False,
    filter_timestamp: None | int = None,
    filter_algo: None | str = None,
) -> pd.DataFrame:
    """Results of the metrics computed.

    Computes the metrics of all algorithms based on the level specified and
    return the results in a pandas DataFrame. The results can be filtered
    based on the algorithm name and the current timestamp.

    Specifics
    ---------
    - User level: User level metrics computed across all timestamps.
    - Window level: Window level metrics computed across all timestamps. This can
        be viewed as a macro level metric in the context of a single window, where
        the scores of each user is averaged within the window.
    - Macro level: Macro level metrics computed for entire timeline. This
        score is computed by averaging the scores of all windows, treating each
        window equally.
    - Micro level: Micro level metrics computed for entire timeline. This
        score is computed by averaging the scores of all users, treating each
        user and the timestamp the user is in as unique contribution to the
        overall score.

    Args:
        level: Level of the metric to compute, defaults to "macro".
        only_current_timestamp: Filter only the current timestamp, defaults to False.
        filter_timestamp: Timestamp value to filter on, defaults to None.
            If both `only_current_timestamp` and `filter_timestamp` are provided,
            `filter_timestamp` will be used.
        filter_algo: Algorithm name to filter on, defaults to None.

    Returns:
        Dataframe representation of the metric.
    """
    if isinstance(level, str) and not MetricLevelEnum.has_value(level):
        raise ValueError("Invalid level specified")
    level = MetricLevelEnum(level)

    if only_current_timestamp and filter_timestamp:
        raise ValueError("Cannot specify both only_current_timestamp and filter_timestamp.")

    timestamp = None
    if only_current_timestamp:
        timestamp = self._current_timestamp

    if filter_timestamp:
        timestamp = filter_timestamp

    return self._acc.df_metric(filter_algo=filter_algo, filter_timestamp=timestamp, level=level)

plot_macro_level_metric()

Source code in src/recnexteval/evaluators/core/base.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def plot_macro_level_metric(self) -> None:
    df = self.metric_results("macro")
    df = df.reset_index()
    ax = sns.barplot(
        data=df,
        x="metric",
        y="macro_score",
        hue="algorithm",
        edgecolor="black"
    )

    ax.set_xlabel("Metric")
    ax.set_ylabel("Macro score")
    ax.set_title("Macro-level scores by metric and algorithm")

    for container in ax.containers:
        ax.bar_label(container, fmt='%.4f', padding=3, fontsize=8)
    plt.legend(
        title="Algorithm",
        loc="upper center",
        bbox_to_anchor=(0.5, -0.1),
    )
    ax.grid(axis="y", alpha=0.3, linestyle="--")
    plt.show()

plot_micro_level_metric()

Source code in src/recnexteval/evaluators/core/base.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def plot_micro_level_metric(self) -> None:
    df = self.metric_results("micro")
    df = df.reset_index()
    ax = sns.barplot(
        data=df,
        x="metric",
        y="micro_score",
        hue="algorithm",
        edgecolor="black"
    )

    ax.set_xlabel("Metric")
    ax.set_ylabel("Micro score")
    ax.set_title("Micro-level scores by metric and algorithm")

    for container in ax.containers:
        ax.bar_label(container, fmt='%.4f', padding=3, fontsize=8)
    plt.legend(
        title="Algorithm",
        loc="upper center",
        bbox_to_anchor=(0.5, -0.1),
    )
    ax.grid(axis="y", alpha=0.3, linestyle="--")
    plt.show()

plot_window_level_metric()

Source code in src/recnexteval/evaluators/core/base.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def plot_window_level_metric(self) -> None:
    df = self.metric_results("window")
    df = df.reset_index()
    metrics = df["metric"].unique()
    n_metrics = len(metrics)

    fig, axes = plt.subplots(n_metrics, 1, figsize=(10, 7), sharey=False)
    if n_metrics == 1:
        axes = [axes]

    fig.suptitle("Window-level scores over time", fontsize=14, fontweight="bold")

    for ax, metric in zip(axes, metrics):
        # Filter data for this metric
        metric_df = df[df["metric"] == metric]

        # Plot line for each algorithm
        sns.lineplot(
            data=metric_df,
            x="timestamp",
            y="window_score",
            hue="algorithm",
            marker="o",
            markersize=6,
            linewidth=2,
            ax=ax,
        )
        ax.set_xlabel("Timestamp (epoch)")
        ax.set_ylabel(f"{metric} score")
        ax.grid(axis="both", alpha=0.3, linestyle="--")

        # Remove individual legends
        if ax.get_legend() is not None:
            ax.get_legend().remove()

    # Create single shared legend at bottom
    handles, labels = axes[0].get_legend_handles_labels()

    fig.legend(
        handles,
        labels,
        title="Algorithm",
        loc="lower center",
        bbox_to_anchor=(0.5, -0.15),
        ncol=1,  # vertical stacking
        frameon=True,
        fontsize=9,
    )
    plt.show()

restore()

Restore the generators before pickling.

This method is used to restore the generators after loading the object from a pickle file.

Source code in src/recnexteval/evaluators/core/base.py
310
311
312
313
314
315
316
317
def restore(self) -> None:
    """Restore the generators before pickling.

    This method is used to restore the generators after loading the object
    from a pickle file.
    """
    self.setting.restore(self._run_step)
    logger.debug("Generators restored")

current_step()

Return the current step of the evaluator.

Returns:

Type Description
int

Current step of the evaluator.

Source code in src/recnexteval/evaluators/core/base.py
319
320
321
322
323
324
325
def current_step(self) -> int:
    """Return the current step of the evaluator.

    Returns:
        Current step of the evaluator.
    """
    return self._run_step