Skip to content

OneHotDegree

OneHotDegree(max_degree: int, in_degree: bool = False, cat: bool = True)

Bases: BaseTransform

Adds the one-hot encoded degree of each node to the node features.

Parameters:

Name Type Description Default
max_degree int

Maximum degree of the graph(s). The encoding has max_degree + 1 columns.

required
in_degree bool

If True, uses the in-degree (number of incoming edges) instead of the out-degree. Default: False

False
cat bool

If True, the encoding is appended to the existing node features, otherwise it replaces them. Default: True

True

Example:

graph = GraphData(edge_index=mx.array([[0, 0, 1], [1, 2, 2]]))
graph = OneHotDegree(max_degree=2)(graph)
graph.node_features
# mx.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]])

Methods:

Name Description
process

Adds the one-hot degrees to the node features of data.

Source code in mlx_graphs/transforms/features.py
def __init__(self, max_degree: int, in_degree: bool = False, cat: bool = True):
    self.max_degree = max_degree
    self.in_degree = in_degree
    self.cat = cat

process

process(data: GraphData) -> GraphData

Adds the one-hot degrees to the node features of data.

Parameters:

Name Type Description Default
data GraphData

The graph to transform.

required

Returns:

Type Description
GraphData

The graph with the updated node_features.

Source code in mlx_graphs/transforms/features.py
def process(self, data: GraphData) -> GraphData:
    """Adds the one-hot degrees to the node features of ``data``.

    Args:
        data: The graph to transform.

    Returns:
        The graph with the updated ``node_features``.
    """
    num_nodes = _num_nodes(data)
    index = _host_edges(data)[1 if self.in_degree else 0]
    degrees = np.bincount(index, minlength=num_nodes)
    if degrees.max(initial=0) > self.max_degree:
        raise ValueError(
            f"The graph has a node of degree {int(degrees.max())}, which is "
            f"greater than max_degree={self.max_degree}"
        )
    encoding = np.zeros((num_nodes, self.max_degree + 1), dtype=np.float32)
    encoding[np.arange(num_nodes), degrees] = 1.0
    return _add_node_features(data, mx.array(encoding), self.cat)

from mlx_graphs.transforms import OneHotDegree · mlx_graphs/transforms/features.py