Skip to content

knn_graph

knn_graph(
    x: array,
    k: int,
    batch_indices: Optional[array] = None,
    loop: bool = False,
    flow: Literal["source_to_target", "target_to_source"] = "source_to_target",
    cosine: bool = False,
    num_graphs: Optional[int] = None,
) -> array

Computes the graph connecting each point to its k nearest points.

Parameters:

Name Type Description Default
x array

Point coordinates (or features), of shape [N, num_features].

required
k int

The number of neighbors of each point.

required
batch_indices Optional[array]

Graph of each point, of shape [N]. Only points of the same graph are connected. Default: None (a single graph).

None
loop bool

If True, each point is one of its own neighbors (with a self-loop). Default: False

False
flow Literal['source_to_target', 'target_to_source']

Direction of the edges, for use with message passing. With "source_to_target", the edges go from the neighbors to the center point, so that each point aggregates its k neighbors. Default: "source_to_target"

'source_to_target'
cosine bool

If True, uses the cosine distance instead of the euclidean distance. Default: False

False
num_graphs Optional[int]

Number of graphs. Default: None (inferred from batch_indices).

None

Returns:

Type Description
array

The edge_index of shape [2, num_edges]. The edges are grouped

array

by center point, closest neighbors first.

Example:

import mlx.core as mx
from mlx_graphs.utils import knn_graph

x = mx.array([[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0]])
batch_indices = mx.array([0, 0, 0, 0])
edge_index = knn_graph(x, k=2, batch_indices=batch_indices)
>>> edge_index.shape
(2, 8)
Source code in mlx_graphs/utils/spatial.py
def knn_graph(
    x: mx.array,
    k: int,
    batch_indices: Optional[mx.array] = None,
    loop: bool = False,
    flow: Literal["source_to_target", "target_to_source"] = "source_to_target",
    cosine: bool = False,
    num_graphs: Optional[int] = None,
) -> mx.array:
    """Computes the graph connecting each point to its ``k`` nearest points.

    Args:
        x: Point coordinates (or features), of shape ``[N, num_features]``.
        k: The number of neighbors of each point.
        batch_indices: Graph of each point, of shape ``[N]``. Only points of the
            same graph are connected. Default: ``None`` (a single graph).
        loop: If ``True``, each point is one of its own neighbors (with a
            self-loop). Default: ``False``
        flow: Direction of the edges, for use with message passing. With
            ``"source_to_target"``, the edges go from the neighbors to the
            center point, so that each point aggregates its ``k`` neighbors.
            Default: ``"source_to_target"``
        cosine: If ``True``, uses the cosine distance instead of the euclidean
            distance. Default: ``False``
        num_graphs: Number of graphs. Default: ``None`` (inferred from
            ``batch_indices``).

    Returns:
        The ``edge_index`` of shape ``[2, num_edges]``. The edges are grouped
        by center point, closest neighbors first.

    Example:

    .. code-block:: python

        import mlx.core as mx
        from mlx_graphs.utils import knn_graph

        x = mx.array([[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0]])
        batch_indices = mx.array([0, 0, 0, 0])
        edge_index = knn_graph(x, k=2, batch_indices=batch_indices)
        >>> edge_index.shape
        (2, 8)
    """
    _check_flow(flow)
    rows = list(
        _neighbor_blocks(
            x, x, batch_indices, batch_indices, num_graphs, k, not loop, cosine
        )
    )
    edge_index = _sorted_pairs(rows, by_distance=True)
    return edge_index[::-1] if flow == "source_to_target" else edge_index

from mlx_graphs.utils import knn_graph · mlx_graphs/utils/spatial.py