Skip to content

Node2Vec

Node2Vec(
    edge_index: array,
    embedding_dim: int,
    walk_length: int,
    context_size: int,
    num_nodes: int,
    walks_per_node: int = 1,
    p: float = 1.0,
    q: float = 1.0,
    num_negative_samples: int = 1,
    use_gpu: bool = True,
)

Bases: Module

The Node2Vec model from the "node2vec: Scalable Feature Learning for Networks" paper where random walks of length walk_length are sampled in a given graph, and node embeddings are learned via negative sampling optimization.

Note

Random-walk sampling uses the kernels of mlx_cluster, a dependency of mlx-graphs on macOS.

Parameters:

Name Type Description Default
edge_index

The edge indices.

required
embedding_dim

The size of each embedding vector.

required
walk_length

The walk length.

required
context_size

The actual context size which is considered for positive samples. This parameter increases the effective sampling rate by reusing samples across different source nodes.

required
num_nodes

Number of nodes in a graph

required
walks_per_node

The number of walks to sample for each node. (default: 1)

required
p

Likelihood of immediately revisiting a node in the walk. (default: 1)

required
q

Control parameter to interpolate between breadth-first strategy and depth-first strategy (default: 1)

required
num_negative_samples int

The number of negative samples to use for each positive sample. (default: 1)

1

Methods:

Name Description
__call__

Returns the embeddings for the nodes in batch.

dataloader

Dataloader for nodes

loss

Computes the loss given positive and negative random walks.

Source code in mlx_graphs/algorithms/node2vec.py
def __init__(
    self,
    edge_index: mx.array,
    embedding_dim: int,
    walk_length: int,
    context_size: int,
    num_nodes: int,
    walks_per_node: int = 1,
    p: float = 1.0,
    q: float = 1.0,
    num_negative_samples: int = 1,
    use_gpu: bool = True,
):
    super().__init__()
    self.edge_index = edge_index.astype(mx.int64)
    self.num_nodes = num_nodes
    self.p = p
    self.q = q
    self.walk_length = walk_length - 1
    self.num_negative_samples = num_negative_samples
    self.embedding_dim = embedding_dim
    self.embedding = nn.Embedding(self.num_nodes, embedding_dim)
    self.context_size = context_size
    self.walks_per_node = walks_per_node
    self.EPS = 1e-15
    self.use_gpu = use_gpu
    assert walk_length >= context_size

    # Converting a CSC matrix to a CSR matrix
    sorted_edge_index = sort_edge_index(edge_index=self.edge_index)
    row = sorted_edge_index[0][0]
    col = sorted_edge_index[0][1]
    self.rowptr = index_to_ptr(row, num_nodes)
    self.col = col

__call__

__call__(batch)

Returns the embeddings for the nodes in batch.

Source code in mlx_graphs/algorithms/node2vec.py
def __call__(self, batch):
    """Returns the embeddings for the nodes in :obj:`batch`."""
    emb = self.embedding.weight
    return emb if batch is None else emb[batch]

dataloader

dataloader(batch_size)

Dataloader for nodes

Source code in mlx_graphs/algorithms/node2vec.py
def dataloader(self, batch_size):
    r"""Dataloader for nodes"""
    data_array = mx.arange(self.num_nodes).astype(mx.int64)
    perm = mx.array(np.random.permutation(self.num_nodes))

    for s in range(0, self.num_nodes, batch_size):
        ids = perm[s : s + batch_size]
        yield (
            self.pos_sample(data_array[ids]),
            self.neg_sample(data_array[ids]),
        )

loss

loss(pos_array, neg_array)

Computes the loss given positive and negative random walks.

Source code in mlx_graphs/algorithms/node2vec.py
def loss(self, pos_array, neg_array):
    r"""Computes the loss given positive and negative random walks."""

    # Positive loss
    start, rest = pos_array[:, 0], pos_array[:, 1:]
    h_start = self.embedding(start).reshape(pos_array.shape[0], 1, -1)

    h_rest = self.embedding(rest.reshape(-1)).reshape(
        pos_array.shape[0], -1, self.embedding_dim
    )

    out = (h_start * h_rest).sum(axis=-1)
    pos_loss = -mx.mean(mx.log(mx.sigmoid(out) + self.EPS))

    # Negative loss
    start, rest = neg_array[:, 0], neg_array[:, 1:]
    h_start = self.embedding(start).reshape(neg_array.shape[0], 1, -1)
    h_rest = self.embedding(rest.reshape(-1)).reshape(
        neg_array.shape[0], -1, self.embedding_dim
    )
    out = (h_start * h_rest).sum(axis=-1)
    neg_loss = -mx.mean(mx.log(1 - mx.sigmoid(out) + self.EPS))

    return pos_loss + neg_loss

from mlx_graphs.algorithms import Node2Vec · mlx_graphs/algorithms/node2vec.py