<commit_before>import numpy as np

from chainer import cuda

from chainercv.links.model.faster_rcnn.utils.bbox2loc import bbox2loc
from chainercv.utils.bbox.bbox_iou import bbox_iou


class ProposalTargetCreator(object):
    """Assign ground truth bounding boxes to given RoIs.

    The :meth:`__call__` of this class generates training targets
    for each object proposal.
    This is used to train Faster RCNN [#]_.

    .. [#] <NAME>, <NAME>, <NAME>, <NAME>. \
    Faster R-CNN: Towards Real-Time Object Detection with \
    Region Proposal Networks. NIPS 2015.

    Args:
        n_sample (int): The number of sampled regions.
        pos_fraction (float): Fraction of regions that is labeled as a
            foreground.
        pos_thresh (float): IoU threshold for a RoI to be considered as a
            foreground.
        neg_thresh_hi (float): RoI is considered to be the background if IoU
            is in [:obj:`neg_thresh_hi`, :obj:`neg_thresh_hi`).
        neg_thresh_lo (float): See above.

    """

    def __init__(self,
                 n_sample=128,
                 pos_fraction=0.25,
                 pos_thresh=0.5, neg_thresh_hi=0.5, neg_thresh_lo=0.0
                 ):
        self.n_sample = n_sample
        self.pos_fraction = pos_fraction
        self.pos_thresh = pos_thresh
        self.neg_thresh_hi = neg_thresh_hi
        self.neg_thresh_lo = neg_thresh_lo

    def __call__(self, roi, bbox, label,
                 loc_normalize_mean=(0., 0., 0., 0.),
                 loc_normalize_std=(0.1, 0.1, 0.2, 0.2)):
        """Assigns ground truth to sampled proposals.

        This function samples total of :obj:`self.n_sample` RoIs
        from the combination of :obj:`roi` and :obj:`bbox`.
        The RoIs are assigned with the ground truth class labels as well as
        bounding box offsets and scales to match the ground truth bounding
        boxes. As many as :obj:`pos_fraction * self.n_sample` RoIs are
        sampled as foregrounds.

        Offsets and scales of bounding boxes are calculated using
        :func:`chainercv.links.model.faster_rcnn.bbox2loc`.
        Also, types of input arrays and output arrays are same.

        Here are notations.

        * :math:`S` is the total number of sampled RoIs, which equals \
            :obj:`self.n_sample`.
        * :math:`L` is number of object classes possibly including the \
            background.

        Args:
            roi (array): Region of interests from which we sample.
                Its shape is :math:`(R, 4)`
            bbox (array): The coordinates of ground truth bounding boxes.
                Its shape is :math:`(R', 4)`.
            label (array): Ground truth bounding box labels. Its shape
                is :math:`(R',)`.
            loc_normalize_mean (tuple of four floats): Mean values to normalize
                coordinates of bouding boxes.
            loc_normalize_std (tupler of four floats): Standard deviation of
                the coordinates of bounding boxes.

        Returns:
            (array, array, array):

            * **sample_roi**: Regions of interests that are sampled. \
                Its shape is :math:`(S, 4)`.
            * **gt_roi_loc**: Offsets and scales to match \
                the sampled RoIs to the ground truth bounding boxes. \
                Its shape is :math:`(S, 4)`.
            * **gt_roi_label**: Labels assigned to sampled RoIs. Its shape is \
                :math:`(S,)`.

        """
        xp = cuda.get_array_module(roi)
        roi = cuda.to_cpu(roi)
        bbox = cuda.to_cpu(bbox)
        label = cuda.to_cpu(label)

        n_bbox, _ = bbox.shape

        roi = np.concatenate((roi, bbox), axis=0)

        fg_roi_per_image = np.round(self.n_sample * self.pos_fraction)
        iou = bbox_iou(roi, bbox)
        gt_assignment = iou.argmax(axis=1)
        max_iou = iou.max(axis=1)
        gt_roi_label = label[gt_assignment]

        # Select foreground RoIs as those with >= pos_thresh IoU.
        fg_index = np.where(max_iou >= self.pos_thresh)[0]
        fg_roi_per_this_image = int(min(fg_roi_per_image, fg_index.size))
        if fg_index.size > 0:
            fg_index = np.random.choice(
                fg_index, size=fg_roi_per_this_image, replace=False)

        # Select background RoIs as those within [neg_thresh_lo, neg_thresh_hi).
        bg_index = np.where((max_iou < self.neg_thresh_hi) &
                            (max_iou >= self.neg_thresh_lo))[0]
        bg_roi_per_this_image = self.n_sample - fg_roi_per_this_image
        bg_roi_per_this_image = int(min(bg_roi_per_this_image, bg_index.size))
        if bg_index.size > 0:
            bg_index = np.random.choice(
                bg_index, size=bg_roi_per_this_image, replace=False)

        # The indices that we're selecting (both fg and bg).
        keep_index = np.append(fg_index, bg_index)
        gt_roi_label = gt_roi_label[keep_index]
        gt_roi_label[fg_roi_per_this_image:] = 0  # BG labels --> 0
        sample_roi = roi[keep_index]

        # Compute offsets and scales to match sampled RoIs to the GTs.
        gt_roi_loc = bbox2loc(sample_roi, bbox[gt_assignment[keep_index]])
        gt_roi_loc = ((gt_roi_loc - np.array(loc_normalize_mean, np.float32)
                       ) / np.array(loc_normalize_std, np.float32))

        if xp != np:
            sample_roi = cuda.to_gpu(sample_roi)
            gt_roi_loc = cuda.to_gpu(gt_roi_loc)
            gt_roi_label = cuda.to_gpu(gt_roi_label)
        return sample_roi, gt_roi_loc, gt_roi_label
<commit_msg>fix doc<commit_after>import numpy as np

from chainer import cuda

from chainercv.links.model.faster_rcnn.utils.bbox2loc import bbox2loc
from chainercv.utils.bbox.bbox_iou import bbox_iou


class ProposalTargetCreator(object):
    """Assign ground truth bounding boxes to given RoIs.

    The :meth:`__call__` of this class generates training targets
    for each object proposal.
    This is used to train Faster RCNN [#]_.

    .. [#] <NAME>, <NAME>, <NAME>, <NAME>. \
    Faster R-CNN: Towards Real-Time Object Detection with \
    Region Proposal Networks. NIPS 2015.

    Args:
        n_sample (int): The number of sampled regions.
        pos_fraction (float): Fraction of regions that is labeled as a
            foreground.
        pos_thresh (float): IoU threshold for a RoI to be considered as a
            foreground.
        neg_thresh_hi (float): RoI is considered to be the background if IoU
            is in [:obj:`neg_thresh_hi`, :obj:`neg_thresh_hi`).
        neg_thresh_lo (float): See above.

    """

    def __init__(self,
                 n_sample=128,
                 pos_fraction=0.25,
                 pos_thresh=0.5, neg_thresh_hi=0.5, neg_thresh_lo=0.0
                 ):
        self.n_sample = n_sample
        self.pos_fraction = pos_fraction
        self.pos_thresh = pos_thresh
        self.neg_thresh_hi = neg_thresh_hi
        self.neg_thresh_lo = neg_thresh_lo

    def __call__(self, roi, bbox, label,
                 loc_normalize_mean=(0., 0., 0., 0.),
                 loc_normalize_std=(0.1, 0.1, 0.2, 0.2)):
        """Assigns ground truth to sampled proposals.

        This function samples total of :obj:`self.n_sample` RoIs
        from the combination of :obj:`roi` and :obj:`bbox`.
        The RoIs are assigned with the ground truth class labels as well as
        bounding box offsets and scales to match the ground truth bounding
        boxes. As many as :obj:`pos_fraction * self.n_sample` RoIs are
        sampled as foregrounds.

        Offsets and scales of bounding boxes are calculated using
        :func:`chainercv.links.model.faster_rcnn.bbox2loc`.
        Also, types of input arrays and output arrays are same.

        Here are notations.

        * :math:`S` is the total number of sampled RoIs, which equals \
            :obj:`self.n_sample`.
        * :math:`L` is number of object classes possibly including the \
            background.

        Args:
            roi (array): Region of Interests (RoIs) from which we sample.
                Its shape is :math:`(R, 4)`
            bbox (array): The coordinates of ground truth bounding boxes.
                Its shape is :math:`(R', 4)`.
            label (array): Ground truth bounding box labels. Its shape
                is :math:`(R',)`.
            loc_normalize_mean (tuple of four floats): Mean values to normalize
                coordinates of bouding boxes.
            loc_normalize_std (tupler of four floats): Standard deviation of
                the coordinates of bounding boxes.

        Returns:
            (array, array, array):

            * **sample_roi**: Regions of interests that are sampled. \
                Its shape is :math:`(S, 4)`.
            * **gt_roi_loc**: Offsets and scales to match \
                the sampled RoIs to the ground truth bounding boxes. \
                Its shape is :math:`(S, 4)`.
            * **gt_roi_label**: Labels assigned to sampled RoIs. Its shape is \
                :math:`(S,)`.

        """
        xp = cuda.get_array_module(roi)
        roi = cuda.to_cpu(roi)
        bbox = cuda.to_cpu(bbox)
        label = cuda.to_cpu(label)

        n_bbox, _ = bbox.shape

        roi = np.concatenate((roi, bbox), axis=0)

        fg_roi_per_image = np.round(self.n_sample * self.pos_fraction)
        iou = bbox_iou(roi, bbox)
        gt_assignment = iou.argmax(axis=1)
        max_iou = iou.max(axis=1)
        gt_roi_label = label[gt_assignment]

        # Select foreground RoIs as those with >= pos_thresh IoU.
        fg_index = np.where(max_iou >= self.pos_thresh)[0]
        fg_roi_per_this_image = int(min(fg_roi_per_image, fg_index.size))
        if fg_index.size > 0:
            fg_index = np.random.choice(
                fg_index, size=fg_roi_per_this_image, replace=False)

        # Select background RoIs as those within [neg_thresh_lo, neg_thresh_hi).
        bg_index = np.where((max_iou < self.neg_thresh_hi) &
                            (max_iou >= self.neg_thresh_lo))[0]
        bg_roi_per_this_image = self.n_sample - fg_roi_per_this_image
        bg_roi_per_this_image = int(min(bg_roi_per_this_image, bg_index.size))
        if bg_index.size > 0:
            bg_index = np.random.choice(
                bg_index, size=bg_roi_per_this_image, replace=False)

        # The indices that we're selecting (both fg and bg).
        keep_index = np.append(fg_index, bg_index)
        gt_roi_label = gt_roi_label[keep_index]
        gt_roi_label[fg_roi_per_this_image:] = 0  # BG labels --> 0
        sample_roi = roi[keep_index]

        # Compute offsets and scales to match sampled RoIs to the GTs.
        gt_roi_loc = bbox2loc(sample_roi, bbox[gt_assignment[keep_index]])
        gt_roi_loc = ((gt_roi_loc - np.array(loc_normalize_mean, np.float32)
                       ) / np.array(loc_normalize_std, np.float32))

        if xp != np:
            sample_roi = cuda.to_gpu(sample_roi)
            gt_roi_loc = cuda.to_gpu(gt_roi_loc)
            gt_roi_label = cuda.to_gpu(gt_roi_label)
        return sample_roi, gt_roi_loc, gt_roi_label

{'fraction_non_alphanumeric': 0.08972399532500225, 'fraction_numerical': 0.00881057268722467, 'mean_word_length': 2.177377892030848, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1463311', 'n_tokens_mistral': 3747, 'n_tokens_neox': 3531, 'n_words': 966}