Skip to content

homophily

homophily(
    edge_index: array,
    node_labels: array,
    method: Literal["edge", "node"] = "edge",
) -> float

Computes the homophily of a graph: how often connected nodes share the same label.

Parameters:

Name Type Description Default
edge_index array

a [2, num_edges] array representing the source and target nodes of each edge

required
node_labels array

Array of shape [num_nodes] (or [num_nodes, 1]) with the class index of each node.

required
method Literal['edge', 'node']

The homophily measure:

  • "edge": the fraction of edges that connect two nodes with the same label.
  • "node": for each node, the fraction of its incoming edges that come from a node with the same label, averaged over all the nodes (nodes without incoming edges count as 0).

Default: "edge"

'edge'

Returns:

Type Description
float

The homophily ratio, between 0 and 1. It is nan if it is undefined

float

(no edges for "edge", no nodes for "node").

Example:

edge_index = mx.array([[0, 1, 2, 3], [1, 2, 0, 4]])
node_labels = mx.array([0, 0, 0, 0, 1])

homophily(edge_index, node_labels, method="edge")
# 0.75

homophily(edge_index, node_labels, method="node")
# 0.6
Source code in mlx_graphs/utils/laplacian.py
def homophily(
    edge_index: mx.array,
    node_labels: mx.array,
    method: Literal["edge", "node"] = "edge",
) -> float:
    """
    Computes the homophily of a graph: how often connected nodes share the
    same label.

    Args:
        edge_index: a [2, num_edges] array representing the source and target
            nodes of each edge
        node_labels: Array of shape ``[num_nodes]`` (or ``[num_nodes, 1]``)
            with the class index of each node.
        method: The homophily measure:

            - ``"edge"``: the fraction of edges that connect two nodes with
              the same label.
            - ``"node"``: for each node, the fraction of its incoming edges
              that come from a node with the same label, averaged over all
              the nodes (nodes without incoming edges count as 0).

            Default: ``"edge"``

    Returns:
        The homophily ratio, between 0 and 1. It is ``nan`` if it is undefined
        (no edges for ``"edge"``, no nodes for ``"node"``).

    Example:

    .. code-block:: python

        edge_index = mx.array([[0, 1, 2, 3], [1, 2, 0, 4]])
        node_labels = mx.array([0, 0, 0, 0, 1])

        homophily(edge_index, node_labels, method="edge")
        # 0.75

        homophily(edge_index, node_labels, method="node")
        # 0.6
    """
    return _homophily(edge_index, node_labels, method)

from mlx_graphs.utils import homophily · mlx_graphs/utils/laplacian.py