Skip to content

DegreeScalerAggregation

DegreeScalerAggregation(
    aggr: Union[str, List[Union[str, Aggregation]], Aggregation],
    scaler: Union[Scalers, List[Scalers]],
    deg: Union[array, ndarray, Sequence[int]],
    train_norm: bool = False,
    aggr_kwargs: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None,
)

Bases: Aggregation

Combines one or more aggregations and rescales their output with one or more degree-based scalers, from "Principal Neighbourhood Aggregation for Graph Nets" paper.

With \(d\) the number of elements of a set (the in-degree of a node in message passing), and \(\delta\) the average of \(\log(d + 1)\) (or of \(d\), for the linear scalers) over the training graphs, the scalers multiply the aggregated features by:

  • "identity": \(1\)
  • "amplification": \(\log(d + 1) / \delta\)
  • "attenuation": \(\delta / \log(\max(d, 1) + 1)\)
  • "linear": \(d / \delta_{lin}\)
  • "inverse_linear": \(\delta_{lin} / \max(d, 1)\)

The outputs of all the scalers are concatenated along the last axis.

Parameters:

Name Type Description Default
aggr Union[str, List[Union[str, Aggregation]], Aggregation]

The aggregation(s): a name, a list of names/aggregations (combined with MultiAggregation, mode="cat") or an Aggregation.

required
scaler Union[Scalers, List[Scalers]]

A scaler name or a list of scaler names.

required
deg Union[array, ndarray, Sequence[int]]

Histogram of the in-degrees of the training nodes: deg[i] is the number of nodes with in-degree i (see get_degree_histogram()). An mx.array, a numpy array or a list.

required
train_norm bool

If True, the normalization constants \(\delta\) are learnable parameters. Default: False

False
aggr_kwargs Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]

Arguments used to build the aggregation(s) given by name (a dict, or a list of dicts for a list of aggregations). Default: None

None

Example:

import mlx.core as mx
from mlx_graphs.nn.aggr import DegreeScalerAggregation

deg = mx.array([0, 2, 3, 1])  # 2 nodes of degree 1, 3 of degree 2, ...
aggr = DegreeScalerAggregation(
    ["mean", "max"], ["identity", "amplification"], deg
)
x = mx.random.normal((6, 16))
index = mx.array([0, 0, 1, 1, 1, 2])
>>> aggr(x, index).shape
(3, 64)

Methods:

Name Description
reset_parameters

Resets the normalization constants to their values from deg.

Source code in mlx_graphs/nn/aggr/scaler.py
def __init__(
    self,
    aggr: Union[str, List[Union[str, Aggregation]], Aggregation],
    scaler: Union[Scalers, List[Scalers]],
    deg: Union[mx.array, np.ndarray, Sequence[int]],
    train_norm: bool = False,
    aggr_kwargs: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None,
):
    super().__init__()

    if isinstance(aggr, (str, Aggregation)):
        self.aggr = aggregation_resolver(aggr, **(aggr_kwargs or {}))
    elif isinstance(aggr, (list, tuple)):
        self.aggr = MultiAggregation(list(aggr), aggr_kwargs)
    else:
        raise ValueError(
            "Only strings, lists, tuples and Aggregation instances are valid "
            f"aggregation schemes (got '{type(aggr).__name__}')"
        )

    scalers = [scaler] if isinstance(scaler, str) else list(scaler)
    for name in scalers:
        if name not in get_args(Scalers):
            raise ValueError(
                f"Unknown scaler '{name}'. Available: {get_args(Scalers)}"
            )
    self.scaler = scalers

    deg = np.asarray(deg, dtype=np.float64).reshape(-1)
    num_nodes = deg.sum()
    if num_nodes <= 0:
        raise ValueError("The degree histogram `deg` must count some nodes")
    bins = np.arange(deg.size)
    self._init_avg_deg_lin = float((bins * deg).sum() / num_nodes)
    self._init_avg_deg_log = float((np.log(bins + 1) * deg).sum() / num_nodes)
    self.train_norm = train_norm
    self.reset_parameters()

reset_parameters

reset_parameters()

Resets the normalization constants to their values from deg.

Source code in mlx_graphs/nn/aggr/scaler.py
def reset_parameters(self):
    """Resets the normalization constants to their values from ``deg``."""
    if self.train_norm:
        self.avg_deg_lin = mx.array([self._init_avg_deg_lin])
        self.avg_deg_log = mx.array([self._init_avg_deg_log])
    else:
        self.avg_deg_lin = self._init_avg_deg_lin
        self.avg_deg_log = self._init_avg_deg_log

from mlx_graphs.nn.aggr import DegreeScalerAggregation · mlx_graphs/nn/aggr/scaler.py