Skip to content

TGBEvaluator

TGBEvaluator(name: str, k_value: int = 10)

The evaluator of a Temporal Graph Benchmark dataset, with the same interface and results as py-tgb's Evaluator classes.

  • Link property prediction (tgbl-*, thgl-*, tkgl-*): each positive edge is ranked against its negative edges (one-vs-many) and the metrics are the mean reciprocal rank "mrr" and "hits@k" (see tgb_mrr_hits()). Inputs: "y_pred_pos" of shape [num_pos] and "y_pred_neg" of shape [num_pos, num_neg].
  • Node property prediction (tgbn-*): "ndcg" is the NDCG@10 of the predicted class scores (see tgb_ndcg()), "mse" also returns "rmse". Inputs: "y_true" and "y_pred" of shape [num_nodes, num_classes].

Inputs can be MLX or NumPy arrays (or torch tensors).

Parameters:

Name Type Description Default
name str

Name of the TGB dataset, e.g. "tgbl-wiki"

required
k_value int

The k of "hits@k" for link prediction. Default: 10

10

Example:

from mlx_graphs.metrics import TGBEvaluator

evaluator = TGBEvaluator("tgbl-wiki")
evaluator.eval(
    {"y_pred_pos": pos_scores, "y_pred_neg": neg_scores,
     "eval_metric": ["mrr"]}
)
>>> {"hits@10": 0.83, "mrr": 0.61}

Methods:

Name Description
eval

Computes the metrics.

Source code in mlx_graphs/metrics/tgb.py
def __init__(self, name: str, k_value: int = 10):
    if name not in TGB_EVAL_METRICS:
        raise NotImplementedError(
            f"Unknown TGB dataset '{name}', available: {list(TGB_EVAL_METRICS)}"
        )
    self.name = name
    self.k_value = k_value
    self.metric = TGB_EVAL_METRICS[name]
    if self.metric == "mrr":
        self.valid_metric_list = ["hits@", "mrr"]
    else:
        self.valid_metric_list = ["mse", "rmse", "ndcg"]

eval

eval(input_dict: dict, verbose: bool = False) -> dict

Computes the metrics.

Parameters:

Name Type Description Default
input_dict dict

The predictions (see the class description) and "eval_metric", a list of metric names

required
verbose bool

Whether to print the metrics

False

Returns:

Type Description
dict

A dictionary of metric values (floats).

Source code in mlx_graphs/metrics/tgb.py
def eval(self, input_dict: dict, verbose: bool = False) -> dict:
    """Computes the metrics.

    Args:
        input_dict: The predictions (see the class description) and
            ``"eval_metric"``, a list of metric names
        verbose: Whether to print the metrics

    Returns:
        A dictionary of metric values (floats).
    """
    if "eval_metric" not in input_dict:
        raise RuntimeError("Missing key of eval_metric!")
    for metric in input_dict["eval_metric"]:
        if metric not in self.valid_metric_list:
            raise ValueError(
                f"Unsupported eval metric: {metric}, not found in "
                f"{self.valid_metric_list}"
            )

    if self.metric == "mrr":
        for key in ("y_pred_pos", "y_pred_neg"):
            if key not in input_dict:
                raise RuntimeError(f"Missing key of {key}")
        mrr, hits = tgb_mrr_hits(
            input_dict["y_pred_pos"], input_dict["y_pred_neg"], self.k_value
        )
        perf = {f"hits@{self.k_value}": hits, "mrr": mrr}
    else:
        for key in ("y_true", "y_pred"):
            if key not in input_dict:
                raise RuntimeError(f"Missing key of {key}")
        y_true = _host(input_dict["y_true"])
        y_pred = _host(input_dict["y_pred"])
        if y_true.shape != y_pred.shape:
            raise RuntimeError("Shape of y_true and y_pred must be the same!")
        perf = {}
        for metric in input_dict["eval_metric"]:
            if metric in ("mse", "rmse"):
                mse = float(np.mean((y_true - y_pred) ** 2))
                perf.update(mse=mse, rmse=math.sqrt(mse))
            elif metric == "ndcg":
                perf["ndcg"] = tgb_ndcg(y_true, y_pred, k=10)

    if verbose:
        for key, value in perf.items():
            print(f"\t>>> {key}: {value:.4f}")
    return perf

from mlx_graphs.metrics import TGBEvaluator · mlx_graphs/metrics/tgb.py