Skip to content

Dataset

Dataset(
    name: str,
    base_dir: Optional[str] = None,
    pre_transform: Optional[Callable] = None,
    transform: Optional[Callable] = None,
)

Bases: BaseDataset

A dataset class for graph data. download and process methods must be implemented by children classes. The save and load methods save and load only the processed self.graphs attribute by default. You may want to override them to store/load additional processed attributes.

Graph data within the dataset should be stored in self.graphs as a list[GraphData]. The creation and preprocessing of this list of graphs is typically done within the overridden process method.

Parameters:

Name Type Description Default
name str

name of the dataset

required
base_dir Optional[str]

Directory where to store dataset files. Default is in the local directory .mlx_graphs_data/.

None
pre_transform Optional[Callable]

A function/transform that takes in a GraphData object and returns a transformed version. The transformation is applied before the first access.

None
transform Optional[Callable]

A function/transform that takes in a GraphData object and returns a transformed version. The transformation is applied before every access, i.e., during the __getitem__ call. By default, no transformation is applied.

None

Methods:

Name Description
index_select

Returns a new dataset with the graphs at the indices idx.

shuffle

Returns a copy of the dataset with the graphs in random order.

Attributes:

Name Type Description
processed_path str

The path where raw files are stored. Defaults at <base_dir>/<name>/processed

num_graphs int

Returns the number of graphs in the dataset.

num_node_classes Union[int, dict[str, int]]

Returns the number of node classes to predict.

num_edge_classes Union[int, dict[str, int]]

Returns the number of edge classes to predict.

num_graph_classes Union[int, dict[str, int]]

Returns the number of graph classes to predict.

num_node_features int

Returns the number of node features, after transform (as in PyG).

num_edge_features int

Returns the number of edge features, after transform (as in PyG).

num_graph_features int

Returns the number of graph features, after transform (as in PyG).

num_classes int

PyG-style number of classes of the labels y (the node labels if

num_features int

PyG-style alias of num_node_features.

Source code in mlx_graphs/datasets/dataset.py
def __init__(
    self,
    name: str,
    base_dir: Optional[str] = None,
    pre_transform: Optional[Callable] = None,
    transform: Optional[Callable] = None,
):
    self._name = name
    self._base_dir = base_dir if base_dir else DEFAULT_BASE_DIR
    self.transform = transform
    self.pre_transform = pre_transform
    self.graphs: list[GraphData] = []
    self._load()

processed_path property

processed_path: str

The path where raw files are stored. Defaults at <base_dir>/<name>/processed

num_graphs property

num_graphs: int

Returns the number of graphs in the dataset.

num_node_classes property

num_node_classes: Union[int, dict[str, int]]

Returns the number of node classes to predict.

num_edge_classes property

num_edge_classes: Union[int, dict[str, int]]

Returns the number of edge classes to predict.

num_graph_classes property

num_graph_classes: Union[int, dict[str, int]]

Returns the number of graph classes to predict.

num_node_features property

num_node_features: int

Returns the number of node features, after transform (as in PyG).

num_edge_features property

num_edge_features: int

Returns the number of edge features, after transform (as in PyG).

num_graph_features property

num_graph_features: int

Returns the number of graph features, after transform (as in PyG).

num_classes property

num_classes: int

PyG-style number of classes of the labels y (the node labels if the graphs have some, the graph labels otherwise, see GraphData.y), inferred as in PyG from the labels of all the graphs (after transform):

  • integer labels with one entry per node (graph): max + 1;
  • floating-point labels with one entry per node (graph): the number of distinct values (with a warning if there are more than two);
  • labels with several entries per node (graph), e.g. multi-label targets of shape [*, num_tasks]: their last dimension.

Returns 0 if no graph has labels.

num_features property

num_features: int

PyG-style alias of num_node_features.

index_select

index_select(idx: Union[slice, array, ndarray, Sequence]) -> Dataset

Returns a new dataset with the graphs at the indices idx.

The graphs are shared with this dataset (not copied), and the transform of the dataset is still applied lazily when a graph is accessed.

Parameters:

Name Type Description Default
idx Union[slice, array, ndarray, Sequence]

The graphs to select, as a slice, a list or array of indices (negative indices are allowed), or a boolean mask of shape [len(dataset)].

required

Returns:

Type Description
Dataset

The dataset restricted to the selected graphs.

Example:

subset = dataset.index_select([0, 2, 4])
len(subset)
# 3
Source code in mlx_graphs/datasets/dataset.py
def index_select(
    self, idx: Union[slice, mx.array, np.ndarray, Sequence]
) -> "Dataset":
    """Returns a new dataset with the graphs at the indices ``idx``.

    The graphs are shared with this dataset (not copied), and the
    ``transform`` of the dataset is still applied lazily when a graph is
    accessed.

    Args:
        idx: The graphs to select, as a slice, a list or array of indices
            (negative indices are allowed), or a boolean mask of shape
            ``[len(dataset)]``.

    Returns:
        The dataset restricted to the selected graphs.

    Example:

    .. code-block:: python

        subset = dataset.index_select([0, 2, 4])
        len(subset)
        # 3
    """
    indices = range(len(self))
    if isinstance(idx, slice):
        selected = list(indices[idx])
    else:
        idx_np = np.asarray(np.array(idx) if isinstance(idx, mx.array) else idx)
        idx_np = idx_np.reshape(-1)
        if idx_np.dtype == np.bool_:
            if idx_np.size != len(self):
                raise IndexError(
                    f"The boolean mask has {idx_np.size} entries but the "
                    f"dataset has {len(self)} graphs"
                )
            selected = np.nonzero(idx_np)[0].tolist()
        elif idx_np.size == 0 or np.issubdtype(idx_np.dtype, np.integer):
            selected = [indices[i] for i in idx_np.astype(np.int64).tolist()]
        else:
            raise IndexError(
                "Dataset indexing failed. Accepted indices are: slice, "
                "integer or boolean mx.array / np.ndarray, list, tuple "
                f"(got dtype '{idx_np.dtype}')"
            )

    dataset = copy.copy(self)
    dataset.graphs = [self.graphs[i] for i in selected]
    return dataset

shuffle

shuffle(return_perm: bool = False) -> Union[Dataset, tuple[Dataset, array]]

Returns a copy of the dataset with the graphs in random order.

The permutation comes from mx.random.permutation, so it is reproducible with mx.random.seed. The graphs themselves are shared, not copied.

Parameters:

Name Type Description Default
return_perm bool

Whether to also return the permutation. Default: False

False

Returns:

Type Description
Union[Dataset, tuple[Dataset, array]]

The shuffled dataset, and the permutation if return_perm is

Union[Dataset, tuple[Dataset, array]]

True (graph i of the shuffled dataset is graph perm[i]

Union[Dataset, tuple[Dataset, array]]

of this one).

Example:

mx.random.seed(42)
shuffled, perm = dataset.shuffle(return_perm=True)
Source code in mlx_graphs/datasets/dataset.py
def shuffle(
    self, return_perm: bool = False
) -> Union["Dataset", tuple["Dataset", mx.array]]:
    """Returns a copy of the dataset with the graphs in random order.

    The permutation comes from ``mx.random.permutation``, so it is
    reproducible with ``mx.random.seed``. The graphs themselves are shared,
    not copied.

    Args:
        return_perm: Whether to also return the permutation. Default:
            ``False``

    Returns:
        The shuffled dataset, and the permutation if ``return_perm`` is
        ``True`` (graph ``i`` of the shuffled dataset is graph ``perm[i]``
        of this one).

    Example:

    .. code-block:: python

        mx.random.seed(42)
        shuffled, perm = dataset.shuffle(return_perm=True)
    """
    perm = mx.random.permutation(len(self)).astype(mx.int32)
    dataset = self.index_select(perm)
    if return_perm:
        return dataset, perm
    return dataset

from mlx_graphs.datasets import Dataset · mlx_graphs/datasets/dataset.py