Skip to content

GraphSAINTNodeSampler

GraphSAINTNodeSampler(
    data: GraphData,
    batch_size: int,
    num_steps: int = 1,
    sample_coverage: int = 0,
    save_dir: Optional[str] = None,
)

Bases: GraphSAINTSampler

GraphSAINT node sampler: samples batch_size edges uniformly at random and keeps their source nodes (so nodes are drawn proportionally to their out-degree), then takes the induced subgraph.

See GraphSAINTSampler for the arguments and the batch content.

Example:

from mlx_graphs.loaders import GraphSAINTNodeSampler

loader = GraphSAINTNodeSampler(
    data, batch_size=6000, num_steps=5, sample_coverage=100
)
for batch in loader:
    out = model(batch.node_features, batch.edge_index)
    loss = (batch.node_norm * loss_fn(out, batch.node_labels)).sum()
Source code in mlx_graphs/loaders/graph_saint.py
def __init__(
    self,
    data: GraphData,
    batch_size: int,
    num_steps: int = 1,
    sample_coverage: int = 0,
    save_dir: Optional[str] = None,
):
    if batch_size < 1:
        raise ValueError(f"`batch_size` must be positive (got {batch_size})")
    for name in ("node_norm", "edge_norm"):
        if getattr(data, name, None) is not None:
            raise ValueError(f"`data` already has a '{name}' attribute.")

    self.data = data
    self.batch_size = batch_size
    self.num_steps = num_steps
    self.sample_coverage = sample_coverage
    self.save_dir = save_dir

    self.N = data.num_nodes
    self.E = data.num_edges
    self._adj = Adjacency(data.edge_index, self.N)
    self._step = 0

    self.node_norm: Optional[np.ndarray] = None
    self.edge_norm: Optional[np.ndarray] = None
    if sample_coverage > 0:
        path = (
            os.path.join(save_dir, self._filename) if save_dir is not None else None
        )
        if path is not None and os.path.exists(path):
            saved = np.load(path)
            self.node_norm, self.edge_norm = saved["node_norm"], saved["edge_norm"]
        else:
            self.node_norm, self.edge_norm = self._compute_norm()
            if path is not None:
                os.makedirs(save_dir, exist_ok=True)  # type: ignore
                np.savez(path, node_norm=self.node_norm, edge_norm=self.edge_norm)

from mlx_graphs.loaders import GraphSAINTNodeSampler · mlx_graphs/loaders/graph_saint.py