Creating a Dataloader with atleast 2 instances from each class

I am performing a multiclass classification problem which requires me to find the intra class covariance in each epoch. For this reason, I need atleast 2 instancess from each class as the covariance formula has 1/(n-1) where n is the number of instance per class and if ther is only a single instance, then it gives Zero Divison Error. So, my question is how do I make a dataloader which has atleast 2 instanceper data class ?

By default all samples will be used in each epoch, so assuming your dataset contains at least two samples per class you wouldn’t have to change anything.
If that’s not the case you could try to oversample the classes with a single sample e.g. with a WeightedRandomSampler or you could create a custom sampler guaranteeing to sample specific classes.

Well, I need a dataloader where each batch contains atleast 2 samples from each class. Sorry for the confusion !!

In this case this topic might be interesting.