Skip to content

LinkPredMetricCollection

LinkPredMetricCollection(
    metrics: Union[List[_LinkPredMetric], Dict[str, _LinkPredMetric]],
)

A collection of link prediction metrics updated together.

Parameters:

Name Type Description Default
metrics Union[List[_LinkPredMetric], Dict[str, _LinkPredMetric]]

A list of metrics (named "<Name>@<k>", with a "Weighted" prefix for weighted metrics) or a dictionary of named metrics.

required

Example:

from mlx_graphs.metrics import (
    LinkPredMAP,
    LinkPredMetricCollection,
    LinkPredPrecision,
    LinkPredRecall,
)

metrics = LinkPredMetricCollection(
    [
        LinkPredMAP(k=10),
        LinkPredPrecision(k=100),
        LinkPredRecall(k=50),
    ]
)
metrics.update(pred_index_mat, edge_label_index)
out = metrics.compute()  # {"LinkPredMAP@10": ..., ...}
metrics.reset()

Methods:

Name Description
update

Updates all metrics with a mini-batch of predictions (see

compute

Returns the value of every metric.

reset

Resets all metrics.

Attributes:

Name Type Description
max_k int

The largest \(k\) of the metrics.

weighted bool

Whether the collection has a weighted metric.

Source code in mlx_graphs/metrics/link_pred.py
def __init__(
    self, metrics: Union[List[_LinkPredMetric], Dict[str, _LinkPredMetric]]
):
    if isinstance(metrics, (list, tuple)):
        metrics = {
            f"{'Weighted' if getattr(m, 'weighted', False) else ''}"
            f"{m.__class__.__name__}@{m.k}": m
            for m in metrics
        }
    if not isinstance(metrics, dict) or len(metrics) == 0:
        raise ValueError("Expected a non-empty list or dict of metrics")
    for metric in metrics.values():
        if not isinstance(metric, _LinkPredMetric):
            raise TypeError(f"'{metric}' is not a link prediction metric")
    self.metrics: Dict[str, _LinkPredMetric] = dict(metrics)

max_k property

max_k: int

The largest \(k\) of the metrics.

weighted property

weighted: bool

Whether the collection has a weighted metric.

update

update(
    pred_index_mat: ArrayLike,
    edge_label_index: EdgeLabelIndex,
    edge_label_weight: Optional[ArrayLike] = None,
)

Updates all metrics with a mini-batch of predictions (see LinkPredMetric.update()). Ground-truth pairs with non-positive weights are dropped for all metrics, as in PyG.

Source code in mlx_graphs/metrics/link_pred.py
def update(
    self,
    pred_index_mat: ArrayLike,
    edge_label_index: EdgeLabelIndex,
    edge_label_weight: Optional[ArrayLike] = None,
):
    """Updates all metrics with a mini-batch of predictions (see
    :meth:`LinkPredMetric.update`). Ground-truth pairs with non-positive
    weights are dropped for all metrics, as in PyG."""
    if self.weighted and edge_label_weight is None:
        raise ValueError(
            f"'edge_label_weight' is a required argument for weighted "
            f"'{self.__class__.__name__}' metrics"
        )
    data = LinkPredMetricData(pred_index_mat, edge_label_index, edge_label_weight)
    unweighted = LinkPredMetricData(data.pred_index_mat, (data.row, data.col))
    for metric in self.metrics.values():
        if isinstance(metric, LinkPredMetric):
            metric._update(data if metric.weighted else unweighted)
        else:
            metric.update(pred_index_mat, edge_label_index, edge_label_weight)

compute

compute() -> Dict[str, array]

Returns the value of every metric.

Source code in mlx_graphs/metrics/link_pred.py
def compute(self) -> Dict[str, mx.array]:
    """Returns the value of every metric."""
    return {name: metric.compute() for name, metric in self.metrics.items()}

reset

reset()

Resets all metrics.

Source code in mlx_graphs/metrics/link_pred.py
def reset(self):
    """Resets all metrics."""
    for metric in self.metrics.values():
        metric.reset()

from mlx_graphs.metrics import LinkPredMetricCollection · mlx_graphs/metrics/link_pred.py