Skip to content

TGBNodePropPredDataset

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

Bases: _TGBDataset

The dynamic node property prediction datasets of the Temporal Graph Benchmark (TGB), as py-tgb's tgb.nodeproppred.dataset_pyg.PyGNodePropPredDataset.

The dataset is a single TemporalData stream of weighted events sorted by time (msg holds the weights), split chronologically (train_mask, val_mask, test_mask). The task is to predict, at given timestamps, the distribution of the future interactions of some nodes over num_classes items (e.g. the share of each trading partner of a nation the next year, or of each music genre of a user the next week), evaluated with NDCG@10 (TGBEvaluator).

The labels form a stream of label timestamps (label_timestamps). As in py-tgb, get_node_label() returns the labels of the next label timestamp once the events reach it, and reset_label_time() rewinds the stream at the start of every pass over the events. node_labels() gives the labels of any label timestamp directly.

================= ========== =========== ========= ========== Name #nodes #events #classes #features ================= ========== =========== ========= ========== "tgbn-trade" 255 468,245 255 1 "tgbn-genre" 1,505 17,858,395 513 1 "tgbn-reddit" 11,766 27,174,118 698 1 "tgbn-token" 61,756 72,936,998 1,001 2 ================= ========== =========== ========= ==========

The node ids are those of py-tgb: the classes (genres, subreddits, tokens) are the nodes 0 to num_classes - 1 and the users are numbered after them; the nations of "tgbn-trade" are both the nodes and the classes. The features are the edge weights (and, for "tgbn-token", whether the user is the sender), with the natural logarithm of the weights for "tgbn-token" (as py-tgb once its processed files are cached).

Parameters:

Name Type Description Default
name str

Name of the dataset, e.g. "tgbn-trade"

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 applied to the TemporalData after processing (it is applied every time the dataset is loaded, as the processed arrays are stored without it)

None
transform Optional[Callable]

A function/transform applied to the TemporalData at every access

None

Example:

from mlx_graphs.datasets import TGBNodePropPredDataset
from mlx_graphs.loaders import TemporalDataLoader

dataset = TGBNodePropPredDataset("tgbn-trade")
data = dataset[0]
train_data = data[dataset.train_mask]
dataset.reset_label_time()
label_t = dataset.get_label_time()
for batch in TemporalDataLoader(train_data, batch_size=200):
    query_t = batch.t[-1].item()
    if query_t > label_t:
        label_ts, label_nodes, labels = dataset.get_node_label(query_t)
        label_t = dataset.get_label_time()
        ...  # predict `labels` [num_label_nodes, num_classes]

Methods:

Name Description
node_labels

The node labels of the i-th label timestamp.

get_node_label

The labels of the next label timestamp if cur_t reached it, as

get_label_time

The next label timestamp of the stream (the last one once the

reset_label_time

Rewinds the label stream to the first label timestamp.

Attributes:

Name Type Description
num_classes int

The number of classes of the node labels (as py-tgb).

label_dim int

The size of the label vectors (the number of classes seen in the

label_timestamps ndarray

The sorted timestamps at which there are node labels.

num_label_timestamps int

The number of label timestamps.

Source code in mlx_graphs/datasets/tgb.py
def __init__(
    self,
    name: str,
    base_dir: Optional[str] = None,
    pre_transform: Optional[Callable] = None,
    transform: Optional[Callable] = None,
):
    super().__init__(name, base_dir, pre_transform, transform)
    self.label_ts_idx = 0

num_classes property

num_classes: int

The number of classes of the node labels (as py-tgb).

label_dim property

label_dim: int

The size of the label vectors (the number of classes seen in the events, at most num_classes).

label_timestamps property

label_timestamps: ndarray

The sorted timestamps at which there are node labels.

num_label_timestamps property

num_label_timestamps: int

The number of label timestamps.

node_labels

node_labels(i: int) -> tuple[array, array, array]

The node labels of the i-th label timestamp.

Parameters:

Name Type Description Default
i int

Index in label_timestamps

required

Returns:

Type Description
array

The timestamp repeated for every labeled node, the labeled nodes,

array

and their label vectors (float32, shape [num_nodes, label_dim]),

array

in the order of py-tgb.

Source code in mlx_graphs/datasets/tgb.py
def node_labels(self, i: int) -> tuple[mx.array, mx.array, mx.array]:
    """The node labels of the ``i``-th label timestamp.

    Args:
        i: Index in :attr:`label_timestamps`

    Returns:
        The timestamp repeated for every labeled node, the labeled nodes,
        and their label vectors (float32, shape `[num_nodes, label_dim]`),
        in the order of ``py-tgb``.
    """
    a = self.arrays
    start, end = int(a["label_ptr"][i]), int(a["label_ptr"][i + 1])
    nodes = a["label_node"][start:end]
    labels = np.zeros((end - start, self.label_dim), dtype=np.float32)
    e_start, e_end = a["label_entry_ptr"][start], a["label_entry_ptr"][end]
    rows = np.repeat(
        np.arange(end - start), np.diff(a["label_entry_ptr"][start : end + 1])
    )
    labels[rows, a["label_class"][e_start:e_end]] = a["label_value"][e_start:e_end]
    ts = np.full(end - start, a["label_ts"][i], dtype=np.int64)
    return mx.array(ts), mx.array(nodes.astype(np.int32)), mx.array(labels)

get_node_label

get_node_label(
    cur_t: Union[int, array],
) -> Optional[tuple[array, array, array]]

The labels of the next label timestamp if cur_t reached it, as py-tgb's get_node_label: the label stream then moves to the following label timestamp. Returns None otherwise (or after the last label timestamp).

Parameters:

Name Type Description Default
cur_t Union[int, array]

The current time (e.g. the time of the last event of a mini-batch)

required

Returns:

Type Description
Optional[tuple[array, array, array]]

(label_ts, label_nodes, labels), see node_labels().

Source code in mlx_graphs/datasets/tgb.py
def get_node_label(
    self, cur_t: Union[int, mx.array]
) -> Optional[tuple[mx.array, mx.array, mx.array]]:
    """The labels of the next label timestamp if ``cur_t`` reached it, as
    ``py-tgb``'s ``get_node_label``: the label stream then moves to the
    following label timestamp. Returns ``None`` otherwise (or after the
    last label timestamp).

    Args:
        cur_t: The current time (e.g. the time of the last event of a
            mini-batch)

    Returns:
        ``(label_ts, label_nodes, labels)``, see :meth:`node_labels`.
    """
    if isinstance(cur_t, mx.array):
        cur_t = cur_t.item()
    if self.label_ts_idx >= self.num_label_timestamps:
        return None
    if cur_t >= self.arrays["label_ts"][self.label_ts_idx]:
        self.label_ts_idx += 1
        return self.node_labels(self.label_ts_idx - 1)
    return None

get_label_time

get_label_time() -> int

The next label timestamp of the stream (the last one once the stream is exhausted).

Source code in mlx_graphs/datasets/tgb.py
def get_label_time(self) -> int:
    """The next label timestamp of the stream (the last one once the
    stream is exhausted)."""
    label_ts = self.arrays["label_ts"]
    return int(label_ts[min(self.label_ts_idx, len(label_ts) - 1)])

reset_label_time

reset_label_time()

Rewinds the label stream to the first label timestamp.

Source code in mlx_graphs/datasets/tgb.py
def reset_label_time(self):
    """Rewinds the label stream to the first label timestamp."""
    self.label_ts_idx = 0

from mlx_graphs.datasets import TGBNodePropPredDataset · mlx_graphs/datasets/tgb.py