Skip to content

GAE

GAE(encoder: Module, decoder: Optional[Module] = None)

Bases: Module

The Graph Auto-Encoder model from the "Variational Graph Auto-Encoders" paper, based on user-defined encoder and decoder models.

The decoder is called as decoder(edge_index, z, sigmoid=...), like InnerProductDecoder.

Parameters:

Name Type Description Default
encoder Module

The encoder module, mapping its inputs (e.g. edge_index and node_features) to the latent node embeddings z.

required
decoder Optional[Module]

The decoder module. Default: InnerProductDecoder

None

Example:

import mlx.core as mx
import mlx.nn as nn
import mlx.optimizers as optim
from mlx_graphs.nn import GAE, GCN

model = GAE(GCN(node_features_dim, 32, num_layers=2, out_features_dim=16))
optimizer = optim.Adam(learning_rate=0.01)


def loss_fn(model, edge_index, node_features):
    z = model.encode(edge_index, node_features)
    return model.recon_loss(z, edge_index)


loss_and_grad = nn.value_and_grad(model, loss_fn)
loss, grads = loss_and_grad(model, edge_index, node_features)
optimizer.update(model, grads)

z = model.encode(edge_index, node_features)
auc, ap = model.test(z, test_pos_edge_index, test_neg_edge_index)

Methods:

Name Description
__call__

Alias for encode().

encode

Runs the encoder and computes the latent node embeddings.

decode

Runs the decoder and computes edge probabilities.

recon_loss

Binary cross entropy of the reconstruction of positive edges and of

test

Computes the area under the ROC curve (AUC) and the average

Source code in mlx_graphs/nn/models/autoencoder.py
def __init__(self, encoder: nn.Module, decoder: Optional[nn.Module] = None):
    super().__init__()
    self.encoder = encoder
    self.decoder = InnerProductDecoder() if decoder is None else decoder

__call__

__call__(*args: Any, **kwargs: Any) -> array

Alias for encode().

Source code in mlx_graphs/nn/models/autoencoder.py
def __call__(self, *args: Any, **kwargs: Any) -> mx.array:
    """Alias for :meth:`encode`."""
    return self.encode(*args, **kwargs)

encode

encode(*args: Any, **kwargs: Any) -> array

Runs the encoder and computes the latent node embeddings.

Source code in mlx_graphs/nn/models/autoencoder.py
def encode(self, *args: Any, **kwargs: Any) -> mx.array:
    """Runs the encoder and computes the latent node embeddings."""
    return self.encoder(*args, **kwargs)

decode

decode(*args: Any, **kwargs: Any) -> array

Runs the decoder and computes edge probabilities.

Source code in mlx_graphs/nn/models/autoencoder.py
def decode(self, *args: Any, **kwargs: Any) -> mx.array:
    """Runs the decoder and computes edge probabilities."""
    return self.decoder(*args, **kwargs)

recon_loss

recon_loss(
    z: array, pos_edge_index: array, neg_edge_index: Optional[array] = None
) -> array

Binary cross entropy of the reconstruction of positive edges and of negative edges.

Parameters:

Name Type Description Default
z array

The latent space \(\mathbf{Z}\)

required
pos_edge_index array

The positive edges to train against

required
neg_edge_index Optional[array]

The negative edges to train against. If None, as many negative edges as positive ones are sampled with negative_sampling(). Default: None

None

Returns:

Type Description
array

The scalar loss.

Source code in mlx_graphs/nn/models/autoencoder.py
def recon_loss(
    self,
    z: mx.array,
    pos_edge_index: mx.array,
    neg_edge_index: Optional[mx.array] = None,
) -> mx.array:
    """Binary cross entropy of the reconstruction of positive edges and of
    negative edges.

    Args:
        z: The latent space :math:`\\mathbf{Z}`
        pos_edge_index: The positive edges to train against
        neg_edge_index: The negative edges to train against. If ``None``,
            as many negative edges as positive ones are sampled with
            :func:`~mlx_graphs.utils.negative_sampling`. Default: ``None``

    Returns:
        The scalar loss.
    """
    pos_loss = -mx.log(self.decoder(pos_edge_index, z, sigmoid=True) + EPS).mean()
    if neg_edge_index is None:
        neg_edge_index = negative_sampling(pos_edge_index, z.shape[0])
    neg_loss = -mx.log(
        1 - self.decoder(neg_edge_index, z, sigmoid=True) + EPS
    ).mean()
    return pos_loss + neg_loss

test

test(
    z: array, pos_edge_index: array, neg_edge_index: array
) -> Tuple[float, float]

Computes the area under the ROC curve (AUC) and the average precision (AP) of the predictions for positive and negative edges.

Parameters:

Name Type Description Default
z array

The latent space \(\mathbf{Z}\)

required
pos_edge_index array

The positive edges to evaluate against

required
neg_edge_index array

The negative edges to evaluate against

required

Returns:

Type Description
Tuple[float, float]

A tuple (auc, ap).

Source code in mlx_graphs/nn/models/autoencoder.py
def test(
    self, z: mx.array, pos_edge_index: mx.array, neg_edge_index: mx.array
) -> Tuple[float, float]:
    """Computes the area under the ROC curve (AUC) and the average
    precision (AP) of the predictions for positive and negative edges.

    Args:
        z: The latent space :math:`\\mathbf{Z}`
        pos_edge_index: The positive edges to evaluate against
        neg_edge_index: The negative edges to evaluate against

    Returns:
        A tuple ``(auc, ap)``.
    """
    pos_pred = self.decoder(pos_edge_index, z, sigmoid=True)
    neg_pred = self.decoder(neg_edge_index, z, sigmoid=True)
    pred = np.array(mx.concatenate([pos_pred, neg_pred]))
    y = np.concatenate([np.ones(pos_pred.shape[0]), np.zeros(neg_pred.shape[0])])
    return roc_auc_score(y, pred), average_precision_score(y, pred)

from mlx_graphs.nn import GAE · mlx_graphs/nn/models/autoencoder.py