code
stringlengths
17
6.64M
class PointGenerator(object): def _meshgrid(self, x, y, row_major=True): xx = x.repeat(len(y)) yy = y.view((- 1), 1).repeat(1, len(x)).view((- 1)) if row_major: return (xx, yy) else: return (yy, xx) def grid_points(self, featmap_size, stride=16, device...
def build_assigner(cfg, **kwargs): if isinstance(cfg, assigners.BaseAssigner): return cfg elif isinstance(cfg, dict): return mmcv.runner.obj_from_dict(cfg, assigners, default_args=kwargs) else: raise TypeError('Invalid type {} for building a sampler'.format(type(cfg)))
def build_sampler(cfg, **kwargs): if isinstance(cfg, samplers.BaseSampler): return cfg elif isinstance(cfg, dict): return mmcv.runner.obj_from_dict(cfg, samplers, default_args=kwargs) else: raise TypeError('Invalid type {} for building a sampler'.format(type(cfg)))
def assign_and_sample(bboxes, gt_bboxes, gt_bboxes_ignore, gt_labels, cfg): bbox_assigner = build_assigner(cfg.assigner) bbox_sampler = build_sampler(cfg.sampler) assign_result = bbox_assigner.assign(bboxes, gt_bboxes, gt_bboxes_ignore, gt_labels) sampling_result = bbox_sampler.sample(assign_result, b...
class AssignResult(util_mixins.NiceRepr): 'Stores assignments between predicted and truth boxes.\n\n Attributes:\n num_gts (int): the number of truth boxes considered when computing this\n assignment\n\n gt_inds (LongTensor): for each predicted box indicates the 1-based\n in...
class BaseAssigner(metaclass=ABCMeta): @abstractmethod def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None): pass
class CombinedSampler(BaseSampler): def __init__(self, pos_sampler, neg_sampler, **kwargs): super(CombinedSampler, self).__init__(**kwargs) self.pos_sampler = build_sampler(pos_sampler, **kwargs) self.neg_sampler = build_sampler(neg_sampler, **kwargs) def _sample_pos(self, **kwargs):...
class InstanceBalancedPosSampler(RandomSampler): def _sample_pos(self, assign_result, num_expected, **kwargs): pos_inds = torch.nonzero((assign_result.gt_inds > 0)) if (pos_inds.numel() != 0): pos_inds = pos_inds.squeeze(1) if (pos_inds.numel() <= num_expected): re...
class IoUBalancedNegSampler(RandomSampler): 'IoU Balanced Sampling.\n\n arXiv: https://arxiv.org/pdf/1904.02701.pdf (CVPR 2019)\n\n Sampling proposals according to their IoU. `floor_fraction` of needed RoIs\n are sampled from proposals whose IoU are lower than `floor_thr` randomly.\n The others are sa...
class OHEMSampler(BaseSampler): 'Online Hard Example Mining Sampler described in [1]_.\n\n References:\n .. [1] https://arxiv.org/pdf/1604.03540.pdf\n ' def __init__(self, num, pos_fraction, context, neg_pos_ub=(- 1), add_gt_as_proposals=True, **kwargs): super(OHEMSampler, self).__init__...
class PseudoSampler(BaseSampler): def __init__(self, **kwargs): pass def _sample_pos(self, **kwargs): raise NotImplementedError def _sample_neg(self, **kwargs): raise NotImplementedError def sample(self, assign_result, bboxes, gt_bboxes, **kwargs): pos_inds = torch....
class RandomSampler(BaseSampler): def __init__(self, num, pos_fraction, neg_pos_ub=(- 1), add_gt_as_proposals=True, **kwargs): from mmdet.core.bbox import demodata super(RandomSampler, self).__init__(num, pos_fraction, neg_pos_ub, add_gt_as_proposals) self.rng = demodata.ensure_rng(kwargs...
def wider_face_classes(): return ['face']
def voc_classes(): return ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
def imagenet_det_classes(): return ['accordion', 'airplane', 'ant', 'antelope', 'apple', 'armadillo', 'artichoke', 'axe', 'baby_bed', 'backpack', 'bagel', 'balance_beam', 'banana', 'band_aid', 'banjo', 'baseball', 'basketball', 'bathing_cap', 'beaker', 'bear', 'bee', 'bell_pepper', 'bench', 'bicycle', 'binder', '...
def imagenet_vid_classes(): return ['airplane', 'antelope', 'bear', 'bicycle', 'bird', 'bus', 'car', 'cattle', 'dog', 'domestic_cat', 'elephant', 'fox', 'giant_panda', 'hamster', 'horse', 'lion', 'lizard', 'monkey', 'motorcycle', 'rabbit', 'red_panda', 'sheep', 'snake', 'squirrel', 'tiger', 'train', 'turtle', 'wa...
def coco_classes(): return ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic_light', 'fire_hydrant', 'stop_sign', 'parking_meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie'...
def cityscapes_classes(): return ['person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle']
def get_classes(dataset): 'Get class names of a dataset.' alias2name = {} for (name, aliases) in dataset_aliases.items(): for alias in aliases: alias2name[alias] = name if mmcv.is_str(dataset): if (dataset in alias2name): labels = eval((alias2name[dataset] + '_c...
class EvalHook(Hook): 'Evaluation hook.\n\n Attributes:\n dataloader (DataLoader): A PyTorch dataloader.\n interval (int): Evaluation interval (by epochs). Default: 1.\n ' def __init__(self, dataloader, interval=1, **eval_kwargs): if (not isinstance(dataloader, DataLoader)): ...
class DistEvalHook(EvalHook): 'Distributed evaluation hook.\n\n Attributes:\n dataloader (DataLoader): A PyTorch dataloader.\n interval (int): Evaluation interval (by epochs). Default: 1.\n tmpdir (str | None): Temporary directory to save the results of all\n processes. Default:...
def auto_fp16(apply_to=None, out_fp32=False): "Decorator to enable fp16 training automatically.\n\n This decorator is useful when you write custom modules and want to support\n mixed precision training. If inputs arguments are fp32 tensors, they will\n be converted to fp16 automatically. Arguments other ...
def force_fp32(apply_to=None, out_fp16=False): "Decorator to convert input arguments to fp32 in force.\n\n This decorator is useful when you write custom modules and want to support\n mixed precision training. If there are some inputs that must be processed\n in fp32 mode, then this decorator can handle ...
class Fp16OptimizerHook(OptimizerHook): 'FP16 optimizer hook.\n\n The steps of fp16 optimizer is as follows.\n 1. Scale the loss value.\n 2. BP in the fp16 model.\n 2. Copy gradients from fp16 model to fp32 weights.\n 3. Update fp32 weights.\n 4. Copy updated parameters from fp32 weights to fp16...
def wrap_fp16_model(model): model.half() patch_norm_fp32(model) for m in model.modules(): if hasattr(m, 'fp16_enabled'): m.fp16_enabled = True
def patch_norm_fp32(module): if isinstance(module, (nn.modules.batchnorm._BatchNorm, nn.GroupNorm)): module.float() if (isinstance(module, nn.GroupNorm) or (torch.__version__ < '1.3')): module.forward = patch_forward_method(module.forward, torch.half, torch.float) for child in modu...
def patch_forward_method(func, src_type, dst_type, convert_output=True): 'Patch the forward method of a module.\n\n Args:\n func (callable): The original forward method.\n src_type (torch.dtype): Type of input arguments to be converted from.\n dst_type (torch.dtype): Type of input argument...
def cast_tensor_type(inputs, src_type, dst_type): if isinstance(inputs, torch.Tensor): return inputs.to(dst_type) elif isinstance(inputs, str): return inputs elif isinstance(inputs, np.ndarray): return inputs elif isinstance(inputs, abc.Mapping): return type(inputs)({k:...
def split_combined_polys(polys, poly_lens, polys_per_mask): 'Split the combined 1-D polys into masks.\n\n A mask is represented as a list of polys, and a poly is represented as\n a 1-D array. In dataset, all masks are concatenated into a single 1-D\n tensor. Here we need to split the tensor into original...
def build_optimizer(model, optimizer_cfg): "Build optimizer from configs.\n\n Args:\n model (:obj:`nn.Module`): The model with parameters to be optimized.\n optimizer_cfg (dict): The config dict of the optimizer.\n Positional fields are:\n - type: class name of the optim...
@OPTIMIZERS.register_module class CopyOfSGD(SGD): 'A clone of torch.optim.SGD.\n\n A customized optimizer could be defined like CopyOfSGD. You may derive from\n built-in optimizers in torch.optim, or directly implement a new optimizer.\n '
def register_torch_optimizers(): torch_optimizers = [] for module_name in dir(torch.optim): if module_name.startswith('__'): continue _optim = getattr(torch.optim, module_name) if (inspect.isclass(_optim) and issubclass(_optim, torch.optim.Optimizer)): OPTIMIZER...
def _allreduce_coalesced(tensors, world_size, bucket_size_mb=(- 1)): if (bucket_size_mb > 0): bucket_size_bytes = ((bucket_size_mb * 1024) * 1024) buckets = _take_tensors(tensors, bucket_size_bytes) else: buckets = OrderedDict() for tensor in tensors: tp = tensor.ty...
def allreduce_grads(params, coalesce=True, bucket_size_mb=(- 1)): grads = [param.grad.data for param in params if (param.requires_grad and (param.grad is not None))] world_size = dist.get_world_size() if coalesce: _allreduce_coalesced(grads, world_size, bucket_size_mb) else: for tensor...
class DistOptimizerHook(OptimizerHook): def __init__(self, grad_clip=None, coalesce=True, bucket_size_mb=(- 1)): self.grad_clip = grad_clip self.coalesce = coalesce self.bucket_size_mb = bucket_size_mb def after_train_iter(self, runner): runner.optimizer.zero_grad() r...
def _concat_dataset(cfg, default_args=None): ann_files = cfg['ann_file'] img_prefixes = cfg.get('img_prefix', None) seg_prefixes = cfg.get('seg_prefix', None) proposal_files = cfg.get('proposal_file', None) datasets = [] num_dset = len(ann_files) for i in range(num_dset): data_cfg ...
def build_dataset(cfg, default_args=None): if isinstance(cfg, (list, tuple)): dataset = ConcatDataset([build_dataset(c, default_args) for c in cfg]) elif (cfg['type'] == 'RepeatDataset'): dataset = RepeatDataset(build_dataset(cfg['dataset'], default_args), cfg['times']) elif isinstance(cfg...
def build_dataloader(dataset, imgs_per_gpu, workers_per_gpu, num_gpus=1, dist=True, shuffle=True, seed=None, **kwargs): 'Build PyTorch DataLoader.\n\n In distributed training, each GPU/process has a dataloader.\n In non-distributed training, there is only one dataloader for all GPUs.\n\n Args:\n d...
def worker_init_fn(worker_id, num_workers, rank, seed): worker_seed = (((num_workers * rank) + worker_id) + seed) np.random.seed(worker_seed) random.seed(worker_seed)
@DATASETS.register_module class CityscapesDataset(CocoDataset): CLASSES = ('person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle') def _filter_imgs(self, min_size=32): 'Filter images too small or without ground truths.' valid_inds = [] ids_with_ann = set((_['image_...
@DATASETS.register_module class CocoDataset(CustomDataset): CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic_light', 'fire_hydrant', 'stop_sign', 'parking_meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe...
@DATASETS.register_module class CustomDataset(Dataset): "Custom dataset for detection.\n\n Annotation format:\n [\n {\n 'filename': 'a.jpg',\n 'width': 1280,\n 'height': 720,\n 'ann': {\n 'bboxes': <np.ndarray> (n, 4),\n 'label...
@DATASETS.register_module class ConcatDataset(_ConcatDataset): 'A wrapper of concatenated dataset.\n\n Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but\n concat the group flag for image aspect ratio.\n\n Args:\n datasets (list[:obj:`Dataset`]): A list of datasets.\n ' def __init_...
@DATASETS.register_module class RepeatDataset(object): 'A wrapper of repeated dataset.\n\n The length of repeated dataset will be `times` larger than the original\n dataset. This is useful when the data loading time is long but the dataset\n is small. Using RepeatDataset can reduce the data loading time ...
@PIPELINES.register_module class Compose(object): def __init__(self, transforms): assert isinstance(transforms, collections.abc.Sequence) self.transforms = [] for transform in transforms: if isinstance(transform, dict): transform = build_from_cfg(transform, PIP...
def to_tensor(data): 'Convert objects of various python types to :obj:`torch.Tensor`.\n\n Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,\n :class:`Sequence`, :class:`int` and :class:`float`.\n ' if isinstance(data, torch.Tensor): return data elif isinstance(data, np.n...
@PIPELINES.register_module class ToTensor(object): def __init__(self, keys): self.keys = keys def __call__(self, results): for key in self.keys: results[key] = to_tensor(results[key]) return results def __repr__(self): return (self.__class__.__name__ + '(keys...
@PIPELINES.register_module class ImageToTensor(object): def __init__(self, keys): self.keys = keys def __call__(self, results): for key in self.keys: img = results[key] if (len(img.shape) < 3): img = np.expand_dims(img, (- 1)) results[key] ...
@PIPELINES.register_module class Transpose(object): def __init__(self, keys, order): self.keys = keys self.order = order def __call__(self, results): for key in self.keys: results[key] = results[key].transpose(self.order) return results def __repr__(self): ...
@PIPELINES.register_module class ToDataContainer(object): def __init__(self, fields=(dict(key='img', stack=True), dict(key='gt_bboxes'), dict(key='gt_labels'))): self.fields = fields def __call__(self, results): for field in self.fields: field = field.copy() key = fie...
@PIPELINES.register_module class DefaultFormatBundle(object): 'Default formatting bundle.\n\n It simplifies the pipeline of formatting common fields, including "img",\n "proposals", "gt_bboxes", "gt_labels", "gt_masks" and "gt_semantic_seg".\n These fields are formatted as follows.\n\n - img: (1)trans...
@PIPELINES.register_module class Collect(object): 'Collect data from the loader relevant to the specific task.\n\n This is usually the last stage of the data loader pipeline. Typically keys\n is set to some subset of "img", "proposals", "gt_bboxes",\n "gt_bboxes_ignore", "gt_labels", and/or "gt_masks".\n...
@PIPELINES.register_module class WrapFieldsToLists(object): "Wrap fields of the data dictionary into lists for evaluation.\n\n This class can be used as a last step of a test or validation\n pipeline for single image evaluation or inference.\n\n Example:\n >>> test_pipeline = [\n >>> dic...
@PIPELINES.register_module class InstaBoost(object): 'Data augmentation method in paper "InstaBoost: Boosting Instance\n Segmentation Via Probability Map Guided Copy-Pasting" Implementation\n details can refer to https://github.com/GothicAi/Instaboost.' def __init__(self, action_candidate=('normal', 'h...
@PIPELINES.register_module class MultiScaleFlipAug(object): def __init__(self, transforms, img_scale, flip=False): self.transforms = Compose(transforms) self.img_scale = (img_scale if isinstance(img_scale, list) else [img_scale]) assert mmcv.is_list_of(self.img_scale, tuple) self....
class DistributedSampler(_DistributedSampler): def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True): super().__init__(dataset, num_replicas=num_replicas, rank=rank) self.shuffle = shuffle def __iter__(self): if self.shuffle: g = torch.Generator() ...
class GroupSampler(Sampler): def __init__(self, dataset, samples_per_gpu=1): assert hasattr(dataset, 'flag') self.dataset = dataset self.samples_per_gpu = samples_per_gpu self.flag = dataset.flag.astype(np.int64) self.group_sizes = np.bincount(self.flag) self.num_s...
class DistributedGroupSampler(Sampler): 'Sampler that restricts data loading to a subset of the dataset.\n It is especially useful in conjunction with\n :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each\n process can pass a DistributedSampler instance as a DataLoader sampler,\n an...
@DATASETS.register_module class VOCDataset(XMLDataset): CLASSES = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor') def __init__(self, **kwargs): super(VOC...
@DATASETS.register_module class WIDERFaceDataset(XMLDataset): 'Reader for the WIDER Face dataset in PASCAL VOC format.\n\n Conversion scripts can be found in\n https://github.com/sovrasov/wider-face-pascal-voc-annotations\n ' CLASSES = ('face',) def __init__(self, **kwargs): super(WIDERF...
@DATASETS.register_module class XMLDataset(CustomDataset): def __init__(self, min_size=None, **kwargs): super(XMLDataset, self).__init__(**kwargs) self.cat2label = {cat: (i + 1) for (i, cat) in enumerate(self.CLASSES)} self.min_size = min_size def load_annotations(self, ann_file): ...
@HEADS.register_module class GARetinaHead(GuidedAnchorHead): 'Guided-Anchor-based RetinaNet head.' def __init__(self, num_classes, in_channels, stacked_convs=4, conv_cfg=None, norm_cfg=None, **kwargs): self.stacked_convs = stacked_convs self.conv_cfg = conv_cfg self.norm_cfg = norm_cf...
@HEADS.register_module class RetinaHead(AnchorHead): 'An anchor-based head used in [1]_.\n\n The head contains two subnetworks. The first classifies anchor boxes and\n the second regresses deltas for the anchors.\n\n References:\n .. [1] https://arxiv.org/pdf/1708.02002.pdf\n\n Example:\n ...
@HEADS.register_module class RetinaSepBNHead(AnchorHead): '"RetinaHead with separate BN.\n\n In RetinaHead, conv/norm layers are shared across different FPN levels,\n while in RetinaSepBNHead, conv layers are shared across different FPN\n levels, but BN layers are separated.\n ' def __init__(self...
@HEADS.register_module class SSDHead(AnchorHead): def __init__(self, input_size=300, num_classes=81, in_channels=(512, 1024, 512, 256, 256, 256), anchor_strides=(8, 16, 32, 64, 100, 300), basesize_ratio_range=(0.1, 0.9), anchor_ratios=([2], [2, 3], [2, 3], [2, 3], [2], [2]), target_means=(0.0, 0.0, 0.0, 0.0), ta...
class HRModule(nn.Module): 'High-Resolution Module for HRNet.\n\n In this module, every branch has 4 BasicBlocks/Bottlenecks. Fusion/Exchange\n is in this module.\n ' def __init__(self, num_branches, blocks, num_blocks, in_channels, num_channels, multiscale_output=True, with_cp=False, conv_cfg=None,...
@BACKBONES.register_module class HRNet(nn.Module): "HRNet backbone.\n\n High-Resolution Representations for Labeling Pixels and Regions\n arXiv: https://arxiv.org/abs/1904.04514\n\n Args:\n extra (dict): detailed configuration for each stage of HRNet.\n in_channels (int): Number of input im...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, gcb=None, gen_attention=None): super(BasicBlock, self).__init__() assert (dcn is None), 'No...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, gcb=None, gen_attention=None): 'Bottleneck block for ResNet.\n\n If style is "pytorch", the ...
def make_res_layer(block, inplanes, planes, blocks, stride=1, dilation=1, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, gcb=None, gen_attention=None, gen_attention_blocks=[]): downsample = None if ((stride != 1) or (inplanes != (planes * block.expansion))): downsam...
@BACKBONES.register_module class ResNet(nn.Module): 'ResNet backbone.\n\n Args:\n depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.\n in_channels (int): Number of input image channels. Normally 3.\n num_stages (int): Resnet stages, normally 4.\n strides (Sequence[int]): Str...
class Bottleneck(_Bottleneck): def __init__(self, inplanes, planes, groups=1, base_width=4, **kwargs): 'Bottleneck block for ResNeXt.\n\n If style is "pytorch", the stride-two layer is the 3x3 conv layer, if\n it is "caffe", the stride-two layer is the first 1x1 conv layer.\n ' ...
def make_res_layer(block, inplanes, planes, blocks, stride=1, dilation=1, groups=1, base_width=4, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, gcb=None): downsample = None if ((stride != 1) or (inplanes != (planes * block.expansion))): downsample = nn.Sequential(b...
@BACKBONES.register_module class ResNeXt(ResNet): 'ResNeXt backbone.\n\n Args:\n depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.\n in_channels (int): Number of input image channels. Normally 3.\n num_stages (int): Resnet stages, normally 4.\n groups (int): Group of resnex...
@HEADS.register_module class ConvFCBBoxHead(BBoxHead): 'More general bbox head, with shared conv and fc layers and two optional\n separated branches.\n\n /-> cls convs -> cls fcs -> cls\n shared convs -> shared fcs\n \\-> reg convs -> reg fcs -> ...
@HEADS.register_module class SharedFCBBoxHead(ConvFCBBoxHead): def __init__(self, num_fcs=2, fc_out_channels=1024, *args, **kwargs): assert (num_fcs >= 1) super(SharedFCBBoxHead, self).__init__(*args, num_shared_convs=0, num_shared_fcs=num_fcs, num_cls_convs=0, num_cls_fcs=0, num_reg_convs=0, num...
class BasicResBlock(nn.Module): 'Basic residual block.\n\n This block is a little different from the block in the ResNet backbone.\n The kernel size of conv1 is 1 in this block while 3 in ResNet BasicBlock.\n\n Args:\n in_channels (int): Channels of the input feature map.\n out_channels (in...
@HEADS.register_module class DoubleConvFCBBoxHead(BBoxHead): 'Bbox head used in Double-Head R-CNN\n\n /-> cls\n /-> shared convs ->\n \\-> reg\n roi features\n /-> cls\n ...
def build(cfg, registry, default_args=None): if isinstance(cfg, list): modules = [build_from_cfg(cfg_, registry, default_args) for cfg_ in cfg] return nn.Sequential(*modules) else: return build_from_cfg(cfg, registry, default_args)
def build_backbone(cfg): return build(cfg, BACKBONES)
def build_neck(cfg): return build(cfg, NECKS)
def build_roi_extractor(cfg): return build(cfg, ROI_EXTRACTORS)
def build_shared_head(cfg): return build(cfg, SHARED_HEADS)
def build_head(cfg): return build(cfg, HEADS)
def build_loss(cfg): return build(cfg, LOSSES)
def build_detector(cfg, train_cfg=None, test_cfg=None): return build(cfg, DETECTORS, dict(train_cfg=train_cfg, test_cfg=test_cfg))
@DETECTORS.register_module class ATSS(SingleStageDetector): def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None): super(ATSS, self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained)
@DETECTORS.register_module class DoubleHeadRCNN(TwoStageDetector): def __init__(self, reg_roi_scale_factor, **kwargs): super().__init__(**kwargs) self.reg_roi_scale_factor = reg_roi_scale_factor def forward_dummy(self, img): outs = () x = self.extract_feat(img) if sel...
@DETECTORS.register_module class FastRCNN(TwoStageDetector): def __init__(self, backbone, bbox_roi_extractor, bbox_head, train_cfg, test_cfg, neck=None, shared_head=None, mask_roi_extractor=None, mask_head=None, pretrained=None): super(FastRCNN, self).__init__(backbone=backbone, neck=neck, shared_head=sh...
@DETECTORS.register_module class FasterRCNN(TwoStageDetector): def __init__(self, backbone, rpn_head, bbox_roi_extractor, bbox_head, train_cfg, test_cfg, neck=None, shared_head=None, pretrained=None): super(FasterRCNN, self).__init__(backbone=backbone, neck=neck, shared_head=shared_head, rpn_head=rpn_hea...
@DETECTORS.register_module class FCOS(SingleStageDetector): def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None): super(FCOS, self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained)
@DETECTORS.register_module class FOVEA(SingleStageDetector): def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None): super(FOVEA, self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained)
@DETECTORS.register_module class MaskRCNN(TwoStageDetector): def __init__(self, backbone, rpn_head, bbox_roi_extractor, bbox_head, mask_roi_extractor, mask_head, train_cfg, test_cfg, neck=None, shared_head=None, pretrained=None): super(MaskRCNN, self).__init__(backbone=backbone, neck=neck, shared_head=sh...
@DETECTORS.register_module class RetinaNet(SingleStageDetector): def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None): super(RetinaNet, self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained)
@DETECTORS.register_module class SingleStageDetector(BaseDetector): 'Base class for single-stage detectors.\n\n Single-stage detectors directly and densely predict bounding boxes on the\n output features of the backbone+neck.\n ' def __init__(self, backbone, neck=None, bbox_head=None, train_cfg=None...
def accuracy(pred, target, topk=1): assert isinstance(topk, (int, tuple)) if isinstance(topk, int): topk = (topk,) return_single = True else: return_single = False maxk = max(topk) (_, pred_label) = pred.topk(maxk, dim=1) pred_label = pred_label.t() correct = pred_l...
class Accuracy(nn.Module): def __init__(self, topk=(1,)): super().__init__() self.topk = topk def forward(self, pred, target): return accuracy(pred, target, self.topk)
@weighted_loss def balanced_l1_loss(pred, target, beta=1.0, alpha=0.5, gamma=1.5, reduction='mean'): assert (beta > 0) assert ((pred.size() == target.size()) and (target.numel() > 0)) diff = torch.abs((pred - target)) b = ((np.e ** (gamma / alpha)) - 1) loss = torch.where((diff < beta), ((((alpha ...
@LOSSES.register_module class BalancedL1Loss(nn.Module): 'Balanced L1 Loss.\n\n arXiv: https://arxiv.org/pdf/1904.02701.pdf (CVPR 2019)\n ' def __init__(self, alpha=0.5, gamma=1.5, beta=1.0, reduction='mean', loss_weight=1.0): super(BalancedL1Loss, self).__init__() self.alpha = alpha ...
def cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None): loss = F.cross_entropy(pred, label, reduction='none') if (weight is not None): weight = weight.float() loss = weight_reduce_loss(loss, weight=weight, reduction=reduction, avg_factor=avg_factor) return loss