Skip to content

scatter_var

scatter_var(
    values: array, index: array, out_size: int, semi_grad: bool = False
) -> array

Computes the (population) variance of the values grouped by index (along axis 0), \(\mathrm{var}(\mathcal{X}) = \mathrm{mean}(\mathcal{X}^2) - \mathrm{mean}(\mathcal{X})^2\), as PyG's VarAggregation. Groups without any value are set to 0.

Parameters:

Name Type Description Default
values array

Input array of shape [num_values, ...].

required
index array

Array of shape [num_values] with the group of each value.

required
out_size int

Number of groups.

required
semi_grad bool

If True, no gradient flows through \(\mathrm{mean}(\mathcal{X}^2)\) (semi-gradient, as in PyG). Default: False

False

Returns:

Type Description
array

An array of shape [out_size, ...] with the variance of each group.

Source code in mlx_graphs/utils/scatter.py
def scatter_var(
    values: mx.array, index: mx.array, out_size: int, semi_grad: bool = False
) -> mx.array:
    r"""Computes the (population) variance of the values grouped by index
    (along axis 0),
    :math:`\mathrm{var}(\mathcal{X}) = \mathrm{mean}(\mathcal{X}^2) -
    \mathrm{mean}(\mathcal{X})^2`, as PyG's ``VarAggregation``. Groups without
    any value are set to 0.

    Args:
        values: Input array of shape ``[num_values, ...]``.
        index: Array of shape ``[num_values]`` with the group of each value.
        out_size: Number of groups.
        semi_grad: If ``True``, no gradient flows through
            :math:`\mathrm{mean}(\mathcal{X}^2)` (semi-gradient, as in PyG).
            Default: ``False``

    Returns:
        An array of shape ``[out_size, ...]`` with the variance of each group.
    """
    mean = scatter_mean(values, index, out_size)
    mean2 = scatter_mean(values * values, index, out_size)
    if semi_grad:
        mean2 = mx.stop_gradient(mean2)
    return mean2 - mean * mean

from mlx_graphs.utils.scatter import scatter_var · mlx_graphs/utils/scatter.py