Skip to content

ImbalancedSampler

ImbalancedSampler(
    dataset: Union[GraphData, Dataset, Sequence[GraphData], array, ndarray],
    input_nodes: Optional[Union[array, ndarray]] = None,
    num_samples: Optional[int] = None,
)

Samples elements with probabilities inversely proportional to the frequency of their class, to rebalance an imbalanced classification task.

Indices are drawn with replacement. The sampler can be passed as sampler to:

  • Dataloader, for graph classification (dataset is a Dataset or a list of GraphData with one graph_labels entry each);
  • NeighborLoader, for node classification (dataset is the GraphData, and input_nodes the same seed nodes as given to the loader). It then yields positions in input_nodes.

Parameters:

Name Type Description Default
dataset Union[GraphData, Dataset, Sequence[GraphData], array, ndarray]

A GraphData (node-level labels node_labels), a Dataset or list of GraphData (graph-level labels graph_labels), or directly an array of integer class labels.

required
input_nodes Optional[Union[array, ndarray]]

Node indices or boolean mask restricting the labels to a subset of nodes, when dataset is a GraphData or an array. Defaults to None (all nodes)

None
num_samples Optional[int]

Number of indices drawn per epoch. Defaults to the number of labels.

None

Example:

from mlx_graphs.loaders import Dataloader, ImbalancedSampler, NeighborLoader

# Graph classification
sampler = ImbalancedSampler(dataset)
loader = Dataloader(dataset, batch_size=64, sampler=sampler)

# Node classification
sampler = ImbalancedSampler(data, input_nodes=data.train_mask)
loader = NeighborLoader(
    data,
    num_neighbors=[10, 10],
    input_nodes=data.train_mask,
    batch_size=64,
    sampler=sampler,
)
Source code in mlx_graphs/loaders/samplers.py
def __init__(
    self,
    dataset: Union[GraphData, Dataset, Sequence[GraphData], mx.array, np.ndarray],
    input_nodes: Optional[Union[mx.array, np.ndarray]] = None,
    num_samples: Optional[int] = None,
):
    if isinstance(dataset, GraphData):
        if dataset.node_labels is None:
            raise ValueError("The graph has no `node_labels`.")
        y = to_numpy(dataset.node_labels).reshape(-1)
        if y.size != dataset.num_nodes:
            raise ValueError("ImbalancedSampler requires one label per node.")
        y = y[to_index(input_nodes, y.size)]
    elif isinstance(dataset, (mx.array, np.ndarray)):
        y = to_numpy(dataset).reshape(-1)
        y = y[to_index(input_nodes, y.size)]
    else:
        labels = []
        for i in range(len(dataset)):
            graph = dataset[i]
            if graph.graph_labels is None:
                raise ValueError("Every graph needs `graph_labels`.")
            labels.append(to_numpy(graph.graph_labels).reshape(-1))
        y = np.concatenate(labels) if labels else np.zeros(0, dtype=np.int64)
        if y.size != len(dataset):
            raise ValueError("ImbalancedSampler requires one label per graph.")

    if y.size and not np.all(np.equal(np.mod(y, 1), 0)):
        raise ValueError("ImbalancedSampler requires integer class labels.")
    y = y.astype(np.int64)
    if y.size and y.min() < 0:
        raise ValueError("Class labels must be non-negative.")

    self.labels = y
    self.num_samples = y.size if num_samples is None else int(num_samples)
    counts = np.bincount(y) if y.size else np.zeros(0, dtype=np.int64)
    with np.errstate(divide="ignore"):
        class_weight = 1.0 / counts
    self.weight = class_weight[y]

from mlx_graphs.loaders import ImbalancedSampler · mlx_graphs/loaders/samplers.py