Custom negative sampler

class CustomNegativeSampler:
    def __init__(self, k=1):
        self.k = k
        neg_g, _ = dgl.load_graphs(neg_graph.dgl')
        self.neg_g = neg_g[0]

    def __call__(self, g, eids, exclude_eids=None):
        src, dst = self.neg_g.edges()
        num_samples = len(eids) * self.k
        random_indices = torch.randint(0, len(src), (num_samples,))
        neg_src = src[random_indices]
        neg_dst = dst[random_indices]

this is my custom negative sampler im trying to use and i get this error:

TypeError: This sampler does not support edge or link prediction; please add anoptional third argument for edge IDs to exclude in its sample() method.

can anyone explain what i must modify in my code ?

Hi @angelosmath, how do you invoke this sampler?

I’m using it here:

    test_sampler = as_edge_prediction_sampler(
        sampler,
        exclude = "reverse_id" if args.exclude_edges else None,
        reverse_eids = reverse_eids if args.exclude_edges else None,
        negative_sampler =  CustomNegativeSampler(k=1),
    )

my reference for the negative sampler is this example:

https://docs.dgl.ai/en/0.8.x/guide/minibatch-link.html#guide-minibatch-link-classification-sampler

thanks for the reply if you need more information feel free to ask.

Could you try the latest tutorial? 6.3 Training GNN for Link Prediction with Neighborhood Sampling — DGL 2.0 documentation

I’m trying but i dont know what is wrong with graphbolt, i get the error:

AttributeError: module 'dgl' has no attribute 'graphbolt'

Αlso, do I need to use the DataLoader you present in 6.3 or can I use the 6.3 negative sampler with the dataloader I have?

test_sampler = NeighborSampler(
        [15, 10, 5],
        prefetch_node_feats = ["feat"],
        fused = fused_sampling,
    ) 

    test_sampler = as_edge_prediction_sampler(
        sampler,
        exclude = "reverse_id" if args.exclude_edges else None,
        reverse_eids = reverse_eids if args.exclude_edges else None,
        negative_sampler =  CustomNegativeSampler(k=1)
    )

    test_dataloader = DataLoader(
        test_pos_graph,
        seed_edges,
        sampler,
        device=device,
        batch_size=args.train_batch_size,
        shuffle=True,
        drop_last=False,
        num_workers=0,
        use_uva=use_uva,
    )

It is just release on last Friday in DGL 2.0 for Linux, please update your DGL version and retry it, we are happy to hear your feedback.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.