Skip to content

KNNGraph

KNNGraph(
    k: int = 6,
    loop: bool = False,
    force_undirected: bool = False,
    flow: Literal["source_to_target", "target_to_source"] = "source_to_target",
    cosine: bool = False,
)

Bases: BaseTransform

Creates a k-NN graph from the node positions pos of a graph.

The previous edges of the graph are replaced, and its edge_features and edge_weights are dropped. For a GraphDataBatch, only the nodes of the same graph are connected.

Parameters:

Name Type Description Default
k int

The number of neighbors of each node. Default: 6

6
loop bool

If True, the graph contains self-loops. Default: False

False
force_undirected bool

If True, the reverse of every edge is added and duplicate edges are merged. 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 node. Default: "source_to_target"

'source_to_target'
cosine bool

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

False

Example:

import mlx.core as mx
from mlx_graphs.data import GraphData
from mlx_graphs.transforms import KNNGraph

pos = mx.random.normal((10, 3))
graph = GraphData(edge_index=mx.zeros((2, 0), dtype=mx.int32), pos=pos)
graph = KNNGraph(k=3)(graph)
>>> graph.edge_index.shape
(2, 30)

Methods:

Name Description
process

Replaces the edges of data by its k-NN graph.

Source code in mlx_graphs/transforms/spatial.py
def __init__(
    self,
    k: int = 6,
    loop: bool = False,
    force_undirected: bool = False,
    flow: Literal["source_to_target", "target_to_source"] = "source_to_target",
    cosine: bool = False,
):
    self.k = k
    self.loop = loop
    self.force_undirected = force_undirected
    self.flow = flow
    self.cosine = cosine

process

process(data: GraphData) -> GraphData

Replaces the edges of data by its k-NN graph.

Parameters:

Name Type Description Default
data GraphData

The graph to transform. It must have a pos attribute.

required

Returns:

Type Description
GraphData

The graph with the k-NN edges.

Source code in mlx_graphs/transforms/spatial.py
def process(self, data: GraphData) -> GraphData:
    """Replaces the edges of ``data`` by its k-NN graph.

    Args:
        data: The graph to transform. It must have a ``pos`` attribute.

    Returns:
        The graph with the k-NN edges.
    """
    pos = _positions(data)
    edge_index = knn_graph(
        pos,
        self.k,
        _batch_indices(data),
        loop=self.loop,
        flow=self.flow,
        cosine=self.cosine,
    )
    if self.force_undirected:
        edge_index = to_undirected(
            edge_index, coalesce=True, num_nodes=pos.shape[0]
        )
    return _set_edges(data, edge_index, pos.shape[0])

from mlx_graphs.transforms import KNNGraph · mlx_graphs/transforms/spatial.py