HEX
Server: LiteSpeed
System: Linux houston.panomity.com 6.8.0-100-generic #100-Ubuntu SMP PREEMPT_DYNAMIC Tue Jan 13 16:40:06 UTC 2026 x86_64
User: nudepix (1011)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: //opt/DAIN/balancedsampler.py
from torch.utils.data.sampler import Sampler
import torch

class RandomBalancedSampler(Sampler):
    """Samples elements randomly, with an arbitrary size, independant from dataset length.
    this is a balanced sampling that will sample the whole dataset with a random permutation.

    Arguments:
        data_source (Dataset): dataset to sample from
    """

    def __init__(self, data_source, epoch_size):
        self.data_size = len(data_source)
        self.epoch_size = epoch_size
        self.index = 0

    def __next__(self):
        if self.index == 0:
            #re-shuffle the sampler
            self.indices = torch.randperm(self.data_size)
        self.index = (self.index+1)%self.data_size
        return self.indices[self.index]

    def next(self):
        return self.__next__()

    def __iter__(self):
        return self

    def __len__(self):
        return min(self.data_size,self.epoch_size) if self.epoch_size>0 else self.data_size

class SequentialBalancedSampler(Sampler):
    """Samples elements dequentially, with an arbitrary size, independant from dataset length.
    this is a balanced sampling that will sample the whole dataset before resetting it.

    Arguments:
        data_source (Dataset): dataset to sample from
    """

    def __init__(self, data_source, epoch_size):
        self.data_size = len(data_source)
        self.epoch_size = epoch_size
        self.index = 0

    def __next__(self):
        self.index = (self.index+1)%self.data_size
        return self.index

    def next(self):
        return self.__next__()

    def __iter__(self):
        return self

    def __len__(self):
        return min(self.data_size,self.epoch_size) if self.epoch_size>0 else self.data_size