Ë
    Ž\;jÜ2  ã                   ó˜   — d dl ZddlmZ ddlmZ  G d„ d«      Z G d„ de«      Z G d	„ d
e«      Zdd„Z	 G d„ de«      Z
 G d„ de«      Zy)é    Né   )Úcore)Úrandpermc                   ó   — e Zd ZdZdd„Zd„ Zy)ÚSamplera8  
    An abstract class to encapsulate methods and behaviors of samplers.

    All sampler used by :code:`paddle.io.BatchSampler` should be a subclass
    of :code:`paddle.io.Sampler`, BatchSampler subclasses should
    implement following methods:

    :code:`__iter__`: return sample index iterably, which iterate over indices
    of dataset elements

    :code:`__len__`: the number of sample in :attr:`data_source`


    Args:
        data_source(Dataset, optional): this could be an instance of
                :code:`paddle.io.Dataset` other Python object which
                implemented :code:`__len__` for Sampler to get indices
                as the range of :attr:`dataset` length. Default None.

    Returns:
        Sampler: an iterable object for sample indices iterating

    Examples:

        .. code-block:: python

            >>> from paddle.io import Dataset, Sampler

            >>> class RandomDataset(Dataset):
            ...     def __init__(self, num_samples):
            ...         self.num_samples = num_samples
            ...
            ...     def __getitem__(self, idx):
            ...         image = np.random.random([784]).astype('float32')
            ...         label = np.random.randint(0, 9, (1, )).astype('int64')
            ...         return image, label
            ...
            ...     def __len__(self):
            ...         return self.num_samples
            ...
            >>> class MySampler(Sampler):
            ...     def __init__(self, data_source):
            ...         self.data_source = data_source
            ...
            ...     def __iter__(self):
            ...         return iter(range(len(self.data_source)))
            ...
            ...     def __len__(self):
            ...         return len(self.data_source)
            ...
            >>> sampler = MySampler(data_source=RandomDataset(100))

            >>> for index in sampler:
            ...     print(index)
            0
            1
            2
            ...
            99

    see `paddle.io.BatchSampler`
    see `paddle.io.DataLoader`

    Nc                 ó   — || _         y ©N©Údata_source©Úselfr   s     úeG:\00. PROJECTS\API\Inventory\templateJSON\kerjaOCR\Lib\site-packages\paddle/io/dataloader/sampler.pyÚ__init__zSampler.__init__W   ó
   € Ø&ˆÕó    c                 ó   — t         ‚r	   )ÚNotImplementedError©r   s    r   Ú__iter__zSampler.__iter__Z   s   € Ü!Ð!r   r	   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   © r   r   r   r      s   „ ñ?óB'ó"r   r   c                   ó"   — e Zd ZdZd„ Zd„ Zd„ Zy)ÚSequenceSamplera÷  
    Iterate samples sequentially, yield :code:`0, 1, 2, ..., len(data_source) -1`
    generally,

    Args:
        data_source(Dataset): dataset to sample, this could be an
                instance of :code:`paddle.io.Dataset` other Python
                object which implemented :code:`__len__`.

    Returns:
        Sampler: a Sampler yield sample index sequentially

    Examples:

        .. code-block:: python

            >>> from paddle.io import Dataset, SequenceSampler

            >>> class RandomDataset(Dataset):
            ...     def __init__(self, num_samples):
            ...         self.num_samples = num_samples
            ...
            ...     def __getitem__(self, idx):
            ...         image = np.random.random([784]).astype('float32')
            ...         label = np.random.randint(0, 9, (1, )).astype('int64')
            ...         return image, label
            ...
            ...     def __len__(self):
            ...         return self.num_samples
            ...
            >>> sampler = SequenceSampler(data_source=RandomDataset(100))

            >>> for index in sampler:
            ...     print(index)
            0
            1
            2
            ...
            99

    see `paddle.io.Sampler`
    c                 ó   — || _         y r	   r
   r   s     r   r   zSequenceSampler.__init__�   r   r   c                 óP   — t        t        t        | j                  «      «      «      S r	   )ÚiterÚrangeÚlenr   r   s    r   r   zSequenceSampler.__iter__�   s   € Ü”Eœ#˜d×.Ñ.Ó/Ó0Ó1Ð1r   c                 ó,   — t        | j                  «      S r	   )r!   r   r   s    r   Ú__len__zSequenceSampler.__len__“   s   € Ü�4×#Ñ#Ó$Ð$r   N©r   r   r   r   r   r   r#   r   r   r   r   r   a   s   „ ñ)òV'ò2ó%r   r   c                   ó6   — e Zd ZdZ	 dd„Zed„ «       Zd„ Zd„ Zy)ÚRandomSampleraÿ  
    Iterate samples randomly, yield shuffled indices, if :attr:`replacement=False`,
    yield shuffled indices of the whole data souce, if :attr:`replacement=True`,
    :attr:`num_samples` can set to specify the sample number to draw.

    Args:
        data_source(Dataset): dataset to sample, this could be an
                instance of :ref:`api_paddle_io_Dataset` or :ref:`api_paddle_io_IterableDataset` or other Python
                object which implemented :code:`__len__` to get indices as the range of :code:`dataset` length. Default None.
        replacement(bool, optional): If False, sample the whole dataset, If True,
                set :attr:`num_samples` for how many samples to draw. Default False.
        num_samples(int, optional): set sample number to draw if :attr:`replacement`
                is True, then it will take samples according to the number you set. Default None, disabled.
        generator(Generator, optional): specify a generator to sample the :code:`data_source`. Default None, disabled.

    Returns:
        RandomSampler: a Sampler yield sample index randomly.

    Examples:

        .. code-block:: python

            >>> import numpy as np
            >>> from paddle.io import Dataset, RandomSampler

            >>> np.random.seed(2023)
            >>> class RandomDataset(Dataset):
            ...     def __init__(self, num_samples):
            ...         self.num_samples = num_samples
            ...
            ...     def __getitem__(self, idx):
            ...         image = np.random.random([784]).astype('float32')
            ...         label = np.random.randint(0, 9, (1, )).astype('int64')
            ...         return image, label
            ...
            ...     def __len__(self):
            ...         return self.num_samples
            ...
            >>> sampler = RandomSampler(data_source=RandomDataset(100))

            >>> for index in sampler:
            ...     print(index)
            56
            12
            68
            ...
            87
    Nc                 óT  — || _         || _        || _        || _        t	        | j                  t
        «      st        d| j                  › �«      ‚| j                  �|st        d«      ‚t	        | j                  t        «      r| j                  dk  rt        d| j                  › �«      ‚y )Nz:expect boolean value for replacement, but got replacement=z>num_samples should not be specified while replacement is Falser   z>num_samples should be a positive integer, but got num_samples=)
r   ÚreplacementÚ_num_samplesÚ	generatorÚ
isinstanceÚboolÚ	TypeErrorÚ
ValueErrorÚnum_samplesÚint)r   r   r(   r/   r*   s        r   r   zRandomSampler.__init__É   s¾   € ð 'ˆÔØ&ˆÔØ'ˆÔØ"ˆŒä˜$×*Ñ*¬DÔ1ÜðØ#×/Ñ/Ð0ð2óð ð
 ×ÑÐ(±ÜØPóð ô ˜$×*Ñ*¬CÔ0°D×4DÑ4DÈÒ4IÜð'Ø'+×'7Ñ'7Ð&8ð:óð ð 5Jr   c                 ó\   — | j                   €t        | j                  «      S | j                   S r	   )r)   r!   r   r   s    r   r/   zRandomSampler.num_samplesâ   s+   € à×ÑÐ$Ü�t×'Ñ'Ó(Ð(Ø× Ñ Ð r   c              #   ó6  K  — t        | j                  «      }| j                  r5t        | j                  «      D ]  }	 t        | j                  «      }|–— Œ y | j                  rWt        j                  j                  t        j                  |«      | j                  d¬«      j                  «       D ]  }|–— Œ y t        j                  j                  t        j                  |«      |d¬«      j                  «       D ]  }|–— Œ y # t        $ r Y  y w xY w­w)NT)ÚreplaceF)r!   r   r*   r    r/   ÚnextÚStopIterationr(   ÚnpÚrandomÚchoiceÚarangeÚtolist)r   ÚnÚiÚindexs       r   r   zRandomSampler.__iter__è   sò   è ø€ Ü�× Ñ Ó!ˆØ�>Š>Ü˜4×+Ñ+Ö,�ðÜ  §¡Ó0�Eð “ñ -ð ×ÒÜŸY™Y×-Ñ-Ü—I‘I˜a“L $×"2Ñ"2¸Dð .ó ç‘&“(ò�Eð  “Kñô
  ŸY™Y×-Ñ-Ü—I‘I˜a“L !¨Uð .ó ç‘&“(ò�Eð  “Kñøô %ò Úðüs)   ‚:D½D	ÁB7DÄ		DÄDÄDÄDc                 ó   — | j                   S r	   )r/   r   s    r   r#   zRandomSampler.__len__ý   s   € Ø×ÑÐr   )FNN)	r   r   r   r   r   Úpropertyr/   r   r#   r   r   r   r&   r&   —   s2   „ ñ/ðd KOóð2 ñ!ó ð!ò
 ó* r   r&   c                 ó*  — t        | t        j                  «      r| j                  «       } t        | t        t
        f«      rt        j                  | «      } t        | t        j                  «      sJ d«       ‚t        | j                  «      dk  sJ d«       ‚| j                  d| j                  d   f«      } t        j                  | dk\  «      sJ d«       ‚t        j                  | t        j                  k(  «      rJ d«       ‚t        j                  | t        j                  k(  «      rJ d«       ‚t        j                   | dkD  d	¬
«      }t        j                  |dkD  «      sJ d«       ‚|st        j                  ||k\  «      sJ d«       ‚| | j!                  d	¬
«      z  } g }t#        | j                  d   «      D ]E  }t        j$                  j'                  | j                  d	   ||| |   «      }|j)                  |«       ŒG t        j                  |«      S )Nz=weights should be paddle.Tensor, numpy.ndarray, list or tupleé   z$weights should be a 1-D or 2-D arrayéÿÿÿÿg        z weights should be positive valuezweights shoule not be INFzweights shoule not be NaNé   )Úaxisr   z#weights should have positive valueszUweights positive value number should not less than num_samples when replacement=False)r+   r   Ú	LoDTensorÚnumpyÚlistÚtupler6   ÚarrayÚndarrayr!   ÚshapeÚreshapeÚallÚanyÚinfÚnanÚsumr    r7   r8   Úappend)Úweightsr/   r(   Ú	non_zerosÚretsr<   Úrets          r   Ú_weighted_samplerW     sÇ  € Ü�'œ4Ÿ>™>Ô*Ø—-‘-“/ˆÜ�'œD¤%˜=Ô)Ü—(‘(˜7Ó#ˆÜØ”—‘ôð GàFóGð ô ˆw�}‰}Ó Ò"ÐJÐ$JÓJÐ"Ø�o‰o˜r 7§=¡=°Ñ#4Ð5Ó6€GÜ�6‰6�'˜S‘.Ô!ÐEÐ#EÓEÐ!Ü�v‰v�g¤§¡Ñ'Ô(ÐEÐ*EÓEÐ(Ü�v‰v�g¤§¡Ñ'Ô(ÐEÐ*EÓEÐ(ä—‘�w ‘}¨1Ô-€IÜ�6‰6�)˜a‘-Ô ÐGÐ"GÓGÐ ÙÜ�v‰v�i ;Ñ.Ô/ð 	
ð;ó	
Ð/ð
 ˜Ÿ™¨˜Ó+Ñ+€GØ€DÜ�7—=‘= Ñ#Ö$ˆÜ�i‰i×ÑØ�M‰M˜!Ñ˜k¨;¸À¹
ó
ˆð 	�‰�CÕð	 %ô
 �8‰8�D‹>Ðr   c                   ó$   — e Zd ZdZdd„Zd„ Zd„ Zy)ÚWeightedRandomSampleraG  
    Random sample with given weights (probabilities), sampe index will be in range
    [0, len(weights) - 1], if :attr:`replacement` is True, index can be sampled
    multiple times.

    Args:
        weights(numpy.ndarray|paddle.Tensor|list|tuple): sequence of weights,
                should be numpy array, paddle.Tensor, list or tuple
        num_samples(int): set sample number to draw from sampler.
        replacement(bool): Whether to draw sample with replacements, default True

    Returns:
        Sampler: a Sampler yield sample index randomly by given weights

    Examples:

        .. code-block:: python

            >>> import numpy as np
            >>> from paddle.io import WeightedRandomSampler

            >>> np.random.seed(2023)
            >>> sampler = WeightedRandomSampler(
            ...     weights=[0.1, 0.3, 0.5, 0.7, 0.2],
            ...     num_samples=5,
            ...     replacement=True
            ... )
            >>> for index in sampler:
            ...     print(index)
            2
            4
            3
            1
            1
    c                 ó¤   — t        |t        «      r|dk  rt        d«      ‚t        |t        «      st        d«      ‚|| _        || _        || _        y )Nr   z(num_samples should be a positive integerz%replacement should be a boolean value)r+   r0   r.   r,   rS   r/   r(   )r   rS   r/   r(   s       r   r   zWeightedRandomSampler.__init__F  sL   € Ü˜+¤sÔ+¨{¸aÒ/?ÜÐGÓHÐHÜ˜+¤tÔ,ÜÐDÓEÐEØˆŒØ&ˆÔØ&ˆÕr   c                 ó¨   — t        | j                  | j                  | j                  «      }t	        |j                  d«      j                  «       «      S ©NrB   )rW   rS   r/   r(   r   rL   r:   )r   Úidxss     r   r   zWeightedRandomSampler.__iter__O  sB   € ÜØ�L‰L˜$×*Ñ*¨D×,<Ñ,<ó
ˆô �D—L‘L Ó$×+Ñ+Ó-Ó.Ð.r   c                 ó¦   — t        j                  | j                  j                  «      | j                  j                  d   z  }| j                  |z  S r\   )r6   ÚprodrS   rK   r/   )r   Úmuls     r   r#   zWeightedRandomSampler.__len__U  s?   € Ü�g‰g�d—l‘l×(Ñ(Ó)¨T¯\©\×-?Ñ-?ÀÑ-CÑCˆØ×Ñ #Ñ%Ð%r   N©Tr$   r   r   r   rY   rY   !  s   „ ñ"óH'ò/ó&r   rY   c                   ó(   — e Zd ZdZd„ Zd„ Zdefd„Zy)ÚSubsetRandomSamplera  
    Randomly sample elements from a given list of indices, without replacement.

    Args:
        indices (sequence): a sequence of indices

    Examples:

        .. code-block:: python

            >>> import paddle
            >>> from paddle.io import SubsetRandomSampler

            >>> paddle.seed(2023)
            >>> sampler = SubsetRandomSampler(indices=[1, 3, 5, 7, 9])

            >>> for index in sampler:
            ...     print(index)
            9
            3
            7
            5
            1

    c                 óD   — t        |«      dk(  rt        d«      ‚|| _        y )Nr   zHThe length of `indices` in SubsetRandomSampler should be greater than 0.)r!   r.   Úindices)r   re   s     r   r   zSubsetRandomSampler.__init__u  s'   € Üˆw‹<˜1ÒÜØZóð ð ˆ�r   c              #   ót   K  — t        t        | j                  «      «      D ]  }| j                  |   –— Œ y ­wr	   )r   r!   re   )r   r<   s     r   r   zSubsetRandomSampler.__iter__|  s,   è ø€ Üœ#˜dŸl™lÓ+Ö,ˆAØ—,‘,˜q‘/Ó!ñ -ùs   ‚68Úreturnc                 ó,   — t        | j                  «      S r	   )r!   re   r   s    r   r#   zSubsetRandomSampler.__len__€  s   € Ü�4—<‘<Ó Ð r   N)r   r   r   r   r   r   r0   r#   r   r   r   rc   rc   Z  s   „ ñò4ò"ð!˜ô !r   rc   ra   )rF   r6   Ú	frameworkr   Útensorr   r   r   r&   rW   rY   rc   r   r   r   Ú<module>rk      sX   ðó å Ý ÷F"ñ F"ôX3%�gô 3%ôlg �Gô g óTô@6&˜Gô 6&ôr'!˜'õ '!r   