Skip to content

NegativeSampling

NegativeSampling(
    mode: Literal["binary", "triplet"],
    amount: Union[int, float] = 1,
    src_weight: Optional[Union[array, ndarray]] = None,
    dst_weight: Optional[Union[array, ndarray]] = None,
)

Configuration of the negative sampling done by LinkNeighborLoader.

Negative nodes are drawn uniformly at random (or proportionally to src_weight / dst_weight), without checking that the resulting pairs are absent from the graph: like in PyG, negatives are not guaranteed to be true negatives.

Parameters:

Name Type Description Default
mode Literal['binary', 'triplet']

"binary" samples random negative edges, added to edge_label_index with label 0. "triplet" samples amount random negative destination nodes for every positive edge, returned as src_index / dst_pos_index / dst_neg_index.

required
amount Union[int, float]

Number of negatives per positive edge. Can be a float for "binary" (ceil(amount * num_positives) negatives), must be an integer for "triplet". Defaults to 1

1
src_weight Optional[Union[array, ndarray]]

Optional sampling weight of every source node.

None
dst_weight Optional[Union[array, ndarray]]

Optional sampling weight of every destination node.

None

Example:

NegativeSampling("binary", amount=2)
NegativeSampling("triplet", amount=3)

Methods:

Name Description
sample_in_time

ceil(amount) negatives per seed (in blocks of one negative per

Source code in mlx_graphs/loaders/link_neighbor_loader.py
def __init__(
    self,
    mode: Literal["binary", "triplet"],
    amount: Union[int, float] = 1,
    src_weight: Optional[Union[mx.array, np.ndarray]] = None,
    dst_weight: Optional[Union[mx.array, np.ndarray]] = None,
):
    if mode not in ("binary", "triplet"):
        raise ValueError(f"`mode` must be 'binary' or 'triplet' (got '{mode}')")
    if amount <= 0:
        raise ValueError(f"`amount` must be positive (got {amount})")
    if mode == "triplet" and amount != math.ceil(amount):
        raise ValueError(
            f"`amount` must be an integer for 'triplet' negative sampling "
            f"(got {amount})"
        )
    self.mode = mode
    self.amount = int(amount) if mode == "triplet" else amount
    self.src_weight = None if src_weight is None else to_numpy(src_weight)
    self.dst_weight = None if dst_weight is None else to_numpy(dst_weight)

sample_in_time

sample_in_time(
    endpoint: Literal["src", "dst"],
    seed_time: ndarray,
    num_nodes: int,
    node_time: Optional[ndarray],
) -> ndarray

ceil(amount) negatives per seed (in blocks of one negative per seed, as in PyG), drawn among the nodes whose time is not later than the seed's when node_time is given: invalid draws are redrawn up to 5 times, then replaced by the earliest node (as in PyG).

Source code in mlx_graphs/loaders/link_neighbor_loader.py
def sample_in_time(
    self,
    endpoint: Literal["src", "dst"],
    seed_time: np.ndarray,
    num_nodes: int,
    node_time: Optional[np.ndarray],
) -> np.ndarray:
    """``ceil(amount)`` negatives per seed (in blocks of one negative per
    seed, as in PyG), drawn among the nodes whose time is not later than
    the seed's when ``node_time`` is given: invalid draws are redrawn up
    to 5 times, then replaced by the earliest node (as in PyG)."""
    sample = self.sample_src if endpoint == "src" else self.sample_dst
    per_seed = math.ceil(self.amount)
    times = np.tile(seed_time, per_seed)
    out = sample(times.size, num_nodes)
    if node_time is None:
        return out
    invalid = np.nonzero(node_time[out] > times)[0]
    for _ in range(5):
        if invalid.size == 0:
            break
        out[invalid] = sample(invalid.size, num_nodes)
        invalid = invalid[node_time[out[invalid]] > times[invalid]]
    out[invalid] = int(np.argmin(node_time))
    return out

from mlx_graphs.loaders import NegativeSampling · mlx_graphs/loaders/link_neighbor_loader.py