Skip to content

scatter_mean

scatter_mean(
    values: array, index: array, out_size: int, axis: int = 0
) -> array

Computes the mean of values that are scattered along a specified axis, grouped by index.

Parameters:

Name Type Description Default
values array

Input array containing values to be scattered. These values will undergo a scatter and mean operation.

required
index array

Array containing indices that determine the scatter of the values.

required
out_size int

Size of the output array.

required
axis int

Axis along which to scatter.

0

Returns:

Type Description
array

An array containing mean of values grouped by index.

Source code in mlx_graphs/utils/scatter.py
def scatter_mean(
    values: mx.array, index: mx.array, out_size: int, axis: int = 0
) -> mx.array:
    """Computes the mean of values that are scattered along a specified axis, grouped
    by index.

    Args:
        values: Input array containing values to be scattered. These values will
            undergo a scatter and mean operation.
        index: Array containing indices that determine the scatter of the `values`.
        out_size: Size of the output array.
        axis: Axis along which to scatter.

    Returns:
        An array containing mean of `values` grouped by `index`.
    """
    scatt_add = scatter(values, index, out_size, aggr="add", axis=axis)
    out_size = scatt_add.shape[axis]

    degrees = degree(index, out_size)
    degrees = mx.where(degrees < 1, 1, degrees)  # Avoid 0 division
    degrees = broadcast(degrees, scatt_add, axis)  # Match the shapes for division

    return mx.divide(scatt_add, degrees)

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