Source code for torchvision.models.detection.retinanet
importmathimportwarningsfromcollectionsimportOrderedDictfromfunctoolsimportpartialfromtypingimportAny,Callable,Dict,List,Optional,Tupleimporttorchfromtorchimportnn,Tensorfrom...opsimportboxesasbox_ops,miscasmisc_nn_ops,sigmoid_focal_lossfrom...ops.feature_pyramid_networkimportLastLevelP6P7from...transforms._presetsimportObjectDetectionfrom...utilsimport_log_api_usage_oncefrom.._apiimportregister_model,Weights,WeightsEnumfrom.._metaimport_COCO_CATEGORIESfrom.._utilsimport_ovewrite_value_param,handle_legacy_interfacefrom..resnetimportresnet50,ResNet50_Weightsfrom.import_utilsasdet_utilsfrom._utilsimport_box_loss,overwrite_epsfrom.anchor_utilsimportAnchorGeneratorfrom.backbone_utilsimport_resnet_fpn_extractor,_validate_trainable_layersfrom.transformimportGeneralizedRCNNTransform__all__=["RetinaNet","RetinaNet_ResNet50_FPN_Weights","RetinaNet_ResNet50_FPN_V2_Weights","retinanet_resnet50_fpn","retinanet_resnet50_fpn_v2",]def_sum(x:List[Tensor])->Tensor:res=x[0]foriinx[1:]:res=res+ireturnresdef_v1_to_v2_weights(state_dict,prefix):foriinrange(4):fortypein["weight","bias"]:old_key=f"{prefix}conv.{2*i}.{type}"new_key=f"{prefix}conv.{i}.0.{type}"ifold_keyinstate_dict:state_dict[new_key]=state_dict.pop(old_key)def_default_anchorgen():anchor_sizes=tuple((x,int(x*2**(1.0/3)),int(x*2**(2.0/3)))forxin[32,64,128,256,512])aspect_ratios=((0.5,1.0,2.0),)*len(anchor_sizes)anchor_generator=AnchorGenerator(anchor_sizes,aspect_ratios)returnanchor_generatorclassRetinaNetHead(nn.Module):""" A regression and classification head for use in RetinaNet. Args: in_channels (int): number of channels of the input feature num_anchors (int): number of anchors to be predicted num_classes (int): number of classes to be predicted norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None """def__init__(self,in_channels,num_anchors,num_classes,norm_layer:Optional[Callable[...,nn.Module]]=None):super().__init__()self.classification_head=RetinaNetClassificationHead(in_channels,num_anchors,num_classes,norm_layer=norm_layer)self.regression_head=RetinaNetRegressionHead(in_channels,num_anchors,norm_layer=norm_layer)defcompute_loss(self,targets,head_outputs,anchors,matched_idxs):# type: (List[Dict[str, Tensor]], Dict[str, Tensor], List[Tensor], List[Tensor]) -> Dict[str, Tensor]return{"classification":self.classification_head.compute_loss(targets,head_outputs,matched_idxs),"bbox_regression":self.regression_head.compute_loss(targets,head_outputs,anchors,matched_idxs),}defforward(self,x):# type: (List[Tensor]) -> Dict[str, Tensor]return{"cls_logits":self.classification_head(x),"bbox_regression":self.regression_head(x)}classRetinaNetClassificationHead(nn.Module):""" A classification head for use in RetinaNet. Args: in_channels (int): number of channels of the input feature num_anchors (int): number of anchors to be predicted num_classes (int): number of classes to be predicted norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None """_version=2def__init__(self,in_channels,num_anchors,num_classes,prior_probability=0.01,norm_layer:Optional[Callable[...,nn.Module]]=None,):super().__init__()conv=[]for_inrange(4):conv.append(misc_nn_ops.Conv2dNormActivation(in_channels,in_channels,norm_layer=norm_layer))self.conv=nn.Sequential(*conv)forlayerinself.conv.modules():ifisinstance(layer,nn.Conv2d):torch.nn.init.normal_(layer.weight,std=0.01)iflayer.biasisnotNone:torch.nn.init.constant_(layer.bias,0)self.cls_logits=nn.Conv2d(in_channels,num_anchors*num_classes,kernel_size=3,stride=1,padding=1)torch.nn.init.normal_(self.cls_logits.weight,std=0.01)torch.nn.init.constant_(self.cls_logits.bias,-math.log((1-prior_probability)/prior_probability))self.num_classes=num_classesself.num_anchors=num_anchors# This is to fix using det_utils.Matcher.BETWEEN_THRESHOLDS in TorchScript.# TorchScript doesn't support class attributes.# https://github.com/pytorch/vision/pull/1697#issuecomment-630255584self.BETWEEN_THRESHOLDS=det_utils.Matcher.BETWEEN_THRESHOLDSdef_load_from_state_dict(self,state_dict,prefix,local_metadata,strict,missing_keys,unexpected_keys,error_msgs,):version=local_metadata.get("version",None)ifversionisNoneorversion<2:_v1_to_v2_weights(state_dict,prefix)super()._load_from_state_dict(state_dict,prefix,local_metadata,strict,missing_keys,unexpected_keys,error_msgs,)defcompute_loss(self,targets,head_outputs,matched_idxs):# type: (List[Dict[str, Tensor]], Dict[str, Tensor], List[Tensor]) -> Tensorlosses=[]cls_logits=head_outputs["cls_logits"]fortargets_per_image,cls_logits_per_image,matched_idxs_per_imageinzip(targets,cls_logits,matched_idxs):# determine only the foregroundforeground_idxs_per_image=matched_idxs_per_image>=0num_foreground=foreground_idxs_per_image.sum()# create the target classificationgt_classes_target=torch.zeros_like(cls_logits_per_image)gt_classes_target[foreground_idxs_per_image,targets_per_image["labels"][matched_idxs_per_image[foreground_idxs_per_image]],]=1.0# find indices for which anchors should be ignoredvalid_idxs_per_image=matched_idxs_per_image!=self.BETWEEN_THRESHOLDS# compute the classification losslosses.append(sigmoid_focal_loss(cls_logits_per_image[valid_idxs_per_image],gt_classes_target[valid_idxs_per_image],reduction="sum",)/max(1,num_foreground))return_sum(losses)/len(targets)defforward(self,x):# type: (List[Tensor]) -> Tensorall_cls_logits=[]forfeaturesinx:cls_logits=self.conv(features)cls_logits=self.cls_logits(cls_logits)# Permute classification output from (N, A * K, H, W) to (N, HWA, K).N,_,H,W=cls_logits.shapecls_logits=cls_logits.view(N,-1,self.num_classes,H,W)cls_logits=cls_logits.permute(0,3,4,1,2)cls_logits=cls_logits.reshape(N,-1,self.num_classes)# Size=(N, HWA, 4)all_cls_logits.append(cls_logits)returntorch.cat(all_cls_logits,dim=1)classRetinaNetRegressionHead(nn.Module):""" A regression head for use in RetinaNet. Args: in_channels (int): number of channels of the input feature num_anchors (int): number of anchors to be predicted norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None """_version=2__annotations__={"box_coder":det_utils.BoxCoder,}def__init__(self,in_channels,num_anchors,norm_layer:Optional[Callable[...,nn.Module]]=None):super().__init__()conv=[]for_inrange(4):conv.append(misc_nn_ops.Conv2dNormActivation(in_channels,in_channels,norm_layer=norm_layer))self.conv=nn.Sequential(*conv)self.bbox_reg=nn.Conv2d(in_channels,num_anchors*4,kernel_size=3,stride=1,padding=1)torch.nn.init.normal_(self.bbox_reg.weight,std=0.01)torch.nn.init.zeros_(self.bbox_reg.bias)forlayerinself.conv.modules():ifisinstance(layer,nn.Conv2d):torch.nn.init.normal_(layer.weight,std=0.01)iflayer.biasisnotNone:torch.nn.init.zeros_(layer.bias)self.box_coder=det_utils.BoxCoder(weights=(1.0,1.0,1.0,1.0))self._loss_type="l1"def_load_from_state_dict(self,state_dict,prefix,local_metadata,strict,missing_keys,unexpected_keys,error_msgs,):version=local_metadata.get("version",None)ifversionisNoneorversion<2:_v1_to_v2_weights(state_dict,prefix)super()._load_from_state_dict(state_dict,prefix,local_metadata,strict,missing_keys,unexpected_keys,error_msgs,)defcompute_loss(self,targets,head_outputs,anchors,matched_idxs):# type: (List[Dict[str, Tensor]], Dict[str, Tensor], List[Tensor], List[Tensor]) -> Tensorlosses=[]bbox_regression=head_outputs["bbox_regression"]fortargets_per_image,bbox_regression_per_image,anchors_per_image,matched_idxs_per_imageinzip(targets,bbox_regression,anchors,matched_idxs):# determine only the foreground indices, ignore the restforeground_idxs_per_image=torch.where(matched_idxs_per_image>=0)[0]num_foreground=foreground_idxs_per_image.numel()# select only the foreground boxesmatched_gt_boxes_per_image=targets_per_image["boxes"][matched_idxs_per_image[foreground_idxs_per_image]]bbox_regression_per_image=bbox_regression_per_image[foreground_idxs_per_image,:]anchors_per_image=anchors_per_image[foreground_idxs_per_image,:]# compute the losslosses.append(_box_loss(self._loss_type,self.box_coder,anchors_per_image,matched_gt_boxes_per_image,bbox_regression_per_image,)/max(1,num_foreground))return_sum(losses)/max(1,len(targets))defforward(self,x):# type: (List[Tensor]) -> Tensorall_bbox_regression=[]forfeaturesinx:bbox_regression=self.conv(features)bbox_regression=self.bbox_reg(bbox_regression)# Permute bbox regression output from (N, 4 * A, H, W) to (N, HWA, 4).N,_,H,W=bbox_regression.shapebbox_regression=bbox_regression.view(N,-1,4,H,W)bbox_regression=bbox_regression.permute(0,3,4,1,2)bbox_regression=bbox_regression.reshape(N,-1,4)# Size=(N, HWA, 4)all_bbox_regression.append(bbox_regression)returntorch.cat(all_bbox_regression,dim=1)classRetinaNet(nn.Module):""" Implements RetinaNet. The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each image, and should be in 0-1 range. Different images can have different sizes. The behavior of the model changes depending on if it is in training or evaluation mode. During training, the model expects both the input tensors and targets (list of dictionary), containing: - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. - labels (Int64Tensor[N]): the class label for each ground-truth box The model returns a Dict[Tensor] during training, containing the classification and regression losses. During inference, the model requires only the input tensors, and returns the post-processed predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as follows: - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. - labels (Int64Tensor[N]): the predicted labels for each image - scores (Tensor[N]): the scores for each prediction Args: backbone (nn.Module): the network used to compute the features for the model. It should contain an out_channels attribute, which indicates the number of output channels that each feature map has (and it should be the same for all feature maps). The backbone should return a single Tensor or an OrderedDict[Tensor]. num_classes (int): number of output classes of the model (including the background). min_size (int): Images are rescaled before feeding them to the backbone: we attempt to preserve the aspect ratio and scale the shorter edge to ``min_size``. If the resulting longer edge exceeds ``max_size``, then downscale so that the longer edge does not exceed ``max_size``. This may result in the shorter edge beeing lower than ``min_size``. max_size (int): See ``min_size``. image_mean (Tuple[float, float, float]): mean values used for input normalization. They are generally the mean values of the dataset on which the backbone has been trained on image_std (Tuple[float, float, float]): std values used for input normalization. They are generally the std values of the dataset on which the backbone has been trained on anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature maps. head (nn.Module): Module run on top of the feature pyramid. Defaults to a module containing a classification and regression module. score_thresh (float): Score threshold used for postprocessing the detections. nms_thresh (float): NMS threshold used for postprocessing the detections. detections_per_img (int): Number of best detections to keep after NMS. fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be considered as positive during training. bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be considered as negative during training. topk_candidates (int): Number of best detections to keep before NMS. Example: >>> import torch >>> import torchvision >>> from torchvision.models.detection import RetinaNet >>> from torchvision.models.detection.anchor_utils import AnchorGenerator >>> # load a pre-trained model for classification and return >>> # only the features >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features >>> # RetinaNet needs to know the number of >>> # output channels in a backbone. For mobilenet_v2, it's 1280, >>> # so we need to add it here >>> backbone.out_channels = 1280 >>> >>> # let's make the network generate 5 x 3 anchors per spatial >>> # location, with 5 different sizes and 3 different aspect >>> # ratios. We have a Tuple[Tuple[int]] because each feature >>> # map could potentially have different sizes and >>> # aspect ratios >>> anchor_generator = AnchorGenerator( >>> sizes=((32, 64, 128, 256, 512),), >>> aspect_ratios=((0.5, 1.0, 2.0),) >>> ) >>> >>> # put the pieces together inside a RetinaNet model >>> model = RetinaNet(backbone, >>> num_classes=2, >>> anchor_generator=anchor_generator) >>> model.eval() >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] >>> predictions = model(x) """__annotations__={"box_coder":det_utils.BoxCoder,"proposal_matcher":det_utils.Matcher,}def__init__(self,backbone,num_classes,# transform parametersmin_size=800,max_size=1333,image_mean=None,image_std=None,# Anchor parametersanchor_generator=None,head=None,proposal_matcher=None,score_thresh=0.05,nms_thresh=0.5,detections_per_img=300,fg_iou_thresh=0.5,bg_iou_thresh=0.4,topk_candidates=1000,**kwargs,):super().__init__()_log_api_usage_once(self)ifnothasattr(backbone,"out_channels"):raiseValueError("backbone should contain an attribute out_channels ""specifying the number of output channels (assumed to be the ""same for all the levels)")self.backbone=backboneifnotisinstance(anchor_generator,(AnchorGenerator,type(None))):raiseTypeError(f"anchor_generator should be of type AnchorGenerator or None instead of {type(anchor_generator)}")ifanchor_generatorisNone:anchor_generator=_default_anchorgen()self.anchor_generator=anchor_generatorifheadisNone:head=RetinaNetHead(backbone.out_channels,anchor_generator.num_anchors_per_location()[0],num_classes)self.head=headifproposal_matcherisNone:proposal_matcher=det_utils.Matcher(fg_iou_thresh,bg_iou_thresh,allow_low_quality_matches=True,)self.proposal_matcher=proposal_matcherself.box_coder=det_utils.BoxCoder(weights=(1.0,1.0,1.0,1.0))ifimage_meanisNone:image_mean=[0.485,0.456,0.406]ifimage_stdisNone:image_std=[0.229,0.224,0.225]self.transform=GeneralizedRCNNTransform(min_size,max_size,image_mean,image_std,**kwargs)self.score_thresh=score_threshself.nms_thresh=nms_threshself.detections_per_img=detections_per_imgself.topk_candidates=topk_candidates# used only on torchscript modeself._has_warned=False@torch.jit.unuseddefeager_outputs(self,losses,detections):# type: (Dict[str, Tensor], List[Dict[str, Tensor]]) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]ifself.training:returnlossesreturndetectionsdefcompute_loss(self,targets,head_outputs,anchors):# type: (List[Dict[str, Tensor]], Dict[str, Tensor], List[Tensor]) -> Dict[str, Tensor]matched_idxs=[]foranchors_per_image,targets_per_imageinzip(anchors,targets):iftargets_per_image["boxes"].numel()==0:matched_idxs.append(torch.full((anchors_per_image.size(0),),-1,dtype=torch.int64,device=anchors_per_image.device))continuematch_quality_matrix=box_ops.box_iou(targets_per_image["boxes"],anchors_per_image)matched_idxs.append(self.proposal_matcher(match_quality_matrix))returnself.head.compute_loss(targets,head_outputs,anchors,matched_idxs)defpostprocess_detections(self,head_outputs,anchors,image_shapes):# type: (Dict[str, List[Tensor]], List[List[Tensor]], List[Tuple[int, int]]) -> List[Dict[str, Tensor]]class_logits=head_outputs["cls_logits"]box_regression=head_outputs["bbox_regression"]num_images=len(image_shapes)detections:List[Dict[str,Tensor]]=[]forindexinrange(num_images):box_regression_per_image=[br[index]forbrinbox_regression]logits_per_image=[cl[index]forclinclass_logits]anchors_per_image,image_shape=anchors[index],image_shapes[index]image_boxes=[]image_scores=[]image_labels=[]forbox_regression_per_level,logits_per_level,anchors_per_levelinzip(box_regression_per_image,logits_per_image,anchors_per_image):num_classes=logits_per_level.shape[-1]# remove low scoring boxesscores_per_level=torch.sigmoid(logits_per_level).flatten()keep_idxs=scores_per_level>self.score_threshscores_per_level=scores_per_level[keep_idxs]topk_idxs=torch.where(keep_idxs)[0]# keep only topk scoring predictionsnum_topk=det_utils._topk_min(topk_idxs,self.topk_candidates,0)scores_per_level,idxs=scores_per_level.topk(num_topk)topk_idxs=topk_idxs[idxs]anchor_idxs=torch.div(topk_idxs,num_classes,rounding_mode="floor")labels_per_level=topk_idxs%num_classesboxes_per_level=self.box_coder.decode_single(box_regression_per_level[anchor_idxs],anchors_per_level[anchor_idxs])boxes_per_level=box_ops.clip_boxes_to_image(boxes_per_level,image_shape)image_boxes.append(boxes_per_level)image_scores.append(scores_per_level)image_labels.append(labels_per_level)image_boxes=torch.cat(image_boxes,dim=0)image_scores=torch.cat(image_scores,dim=0)image_labels=torch.cat(image_labels,dim=0)# non-maximum suppressionkeep=box_ops.batched_nms(image_boxes,image_scores,image_labels,self.nms_thresh)keep=keep[:self.detections_per_img]detections.append({"boxes":image_boxes[keep],"scores":image_scores[keep],"labels":image_labels[keep],})returndetectionsdefforward(self,images,targets=None):# type: (List[Tensor], Optional[List[Dict[str, Tensor]]]) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]""" Args: images (list[Tensor]): images to be processed targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional) Returns: result (list[BoxList] or dict[Tensor]): the output from the model. During training, it returns a dict[Tensor] which contains the losses. During testing, it returns list[BoxList] contains additional fields like `scores`, `labels` and `mask` (for Mask R-CNN models). """ifself.training:iftargetsisNone:torch._assert(False,"targets should not be none when in training mode")else:fortargetintargets:boxes=target["boxes"]torch._assert(isinstance(boxes,torch.Tensor),"Expected target boxes to be of type Tensor.")torch._assert(len(boxes.shape)==2andboxes.shape[-1]==4,"Expected target boxes to be a tensor of shape [N, 4].",)# get the original image sizesoriginal_image_sizes:List[Tuple[int,int]]=[]forimginimages:val=img.shape[-2:]torch._assert(len(val)==2,f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}",)original_image_sizes.append((val[0],val[1]))# transform the inputimages,targets=self.transform(images,targets)# Check for degenerate boxes# TODO: Move this to a functioniftargetsisnotNone:fortarget_idx,targetinenumerate(targets):boxes=target["boxes"]degenerate_boxes=boxes[:,2:]<=boxes[:,:2]ifdegenerate_boxes.any():# print the first degenerate boxbb_idx=torch.where(degenerate_boxes.any(dim=1))[0][0]degen_bb:List[float]=boxes[bb_idx].tolist()torch._assert(False,"All bounding boxes should have positive height and width."f" Found invalid box {degen_bb} for target at index {target_idx}.",)# get the features from the backbonefeatures=self.backbone(images.tensors)ifisinstance(features,torch.Tensor):features=OrderedDict([("0",features)])# TODO: Do we want a list or a dict?features=list(features.values())# compute the retinanet heads outputs using the featureshead_outputs=self.head(features)# create the set of anchorsanchors=self.anchor_generator(images,features)losses={}detections:List[Dict[str,Tensor]]=[]ifself.training:iftargetsisNone:torch._assert(False,"targets should not be none when in training mode")else:# compute the losseslosses=self.compute_loss(targets,head_outputs,anchors)else:# recover level sizesnum_anchors_per_level=[x.size(2)*x.size(3)forxinfeatures]HW=0forvinnum_anchors_per_level:HW+=vHWA=head_outputs["cls_logits"].size(1)A=HWA//HWnum_anchors_per_level=[hw*Aforhwinnum_anchors_per_level]# split outputs per levelsplit_head_outputs:Dict[str,List[Tensor]]={}forkinhead_outputs:split_head_outputs[k]=list(head_outputs[k].split(num_anchors_per_level,dim=1))split_anchors=[list(a.split(num_anchors_per_level))forainanchors]# compute the detectionsdetections=self.postprocess_detections(split_head_outputs,split_anchors,images.image_sizes)detections=self.transform.postprocess(detections,images.image_sizes,original_image_sizes)iftorch.jit.is_scripting():ifnotself._has_warned:warnings.warn("RetinaNet always returns a (Losses, Detections) tuple in scripting")self._has_warned=Truereturnlosses,detectionsreturnself.eager_outputs(losses,detections)_COMMON_META={"categories":_COCO_CATEGORIES,"min_size":(1,1),}
[docs]classRetinaNet_ResNet50_FPN_Weights(WeightsEnum):COCO_V1=Weights(url="https://download.pytorch.org/models/retinanet_resnet50_fpn_coco-eeacb38b.pth",transforms=ObjectDetection,meta={**_COMMON_META,"num_params":34014999,"recipe":"https://github.com/pytorch/vision/tree/main/references/detection#retinanet","_metrics":{"COCO-val2017":{"box_map":36.4,}},"_ops":151.54,"_file_size":130.267,"_docs":"""These weights were produced by following a similar training recipe as on the paper.""",},)DEFAULT=COCO_V1
[docs]classRetinaNet_ResNet50_FPN_V2_Weights(WeightsEnum):COCO_V1=Weights(url="https://download.pytorch.org/models/retinanet_resnet50_fpn_v2_coco-5905b1c5.pth",transforms=ObjectDetection,meta={**_COMMON_META,"num_params":38198935,"recipe":"https://github.com/pytorch/vision/pull/5756","_metrics":{"COCO-val2017":{"box_map":41.5,}},"_ops":152.238,"_file_size":146.037,"_docs":"""These weights were produced using an enhanced training recipe to boost the model accuracy.""",},)DEFAULT=COCO_V1
[docs]@register_model()@handle_legacy_interface(weights=("pretrained",RetinaNet_ResNet50_FPN_Weights.COCO_V1),weights_backbone=("pretrained_backbone",ResNet50_Weights.IMAGENET1K_V1),)defretinanet_resnet50_fpn(*,weights:Optional[RetinaNet_ResNet50_FPN_Weights]=None,progress:bool=True,num_classes:Optional[int]=None,weights_backbone:Optional[ResNet50_Weights]=ResNet50_Weights.IMAGENET1K_V1,trainable_backbone_layers:Optional[int]=None,**kwargs:Any,)->RetinaNet:""" Constructs a RetinaNet model with a ResNet-50-FPN backbone. .. betastatus:: detection module Reference: `Focal Loss for Dense Object Detection <https://arxiv.org/abs/1708.02002>`_. The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each image, and should be in ``0-1`` range. Different images can have different sizes. The behavior of the model changes depending on if it is in training or evaluation mode. During training, the model expects both the input tensors and targets (list of dictionary), containing: - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. - labels (``Int64Tensor[N]``): the class label for each ground-truth box The model returns a ``Dict[Tensor]`` during training, containing the classification and regression losses. During inference, the model requires only the input tensors, and returns the post-processed predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as follows, where ``N`` is the number of detections: - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. - labels (``Int64Tensor[N]``): the predicted labels for each detection - scores (``Tensor[N]``): the scores of each detection For more details on the output, you may refer to :ref:`instance_seg_output`. Example:: >>> model = torchvision.models.detection.retinanet_resnet50_fpn(weights=RetinaNet_ResNet50_FPN_Weights.DEFAULT) >>> model.eval() >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] >>> predictions = model(x) Args: weights (:class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights`, optional): The pretrained weights to use. See :class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights` below for more details, and possible values. By default, no pre-trained weights are used. progress (bool): If True, displays a progress bar of the download to stderr. Default is True. num_classes (int, optional): number of output classes of the model (including the background) weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for the backbone. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is passed (the default) this value is set to 3. **kwargs: parameters passed to the ``torchvision.models.detection.RetinaNet`` base class. Please refer to the `source code <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/retinanet.py>`_ for more details about this class. .. autoclass:: torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights :members: """weights=RetinaNet_ResNet50_FPN_Weights.verify(weights)weights_backbone=ResNet50_Weights.verify(weights_backbone)ifweightsisnotNone:weights_backbone=Nonenum_classes=_ovewrite_value_param("num_classes",num_classes,len(weights.meta["categories"]))elifnum_classesisNone:num_classes=91is_trained=weightsisnotNoneorweights_backboneisnotNonetrainable_backbone_layers=_validate_trainable_layers(is_trained,trainable_backbone_layers,5,3)norm_layer=misc_nn_ops.FrozenBatchNorm2difis_trainedelsenn.BatchNorm2dbackbone=resnet50(weights=weights_backbone,progress=progress,norm_layer=norm_layer)# skip P2 because it generates too many anchors (according to their paper)backbone=_resnet_fpn_extractor(backbone,trainable_backbone_layers,returned_layers=[2,3,4],extra_blocks=LastLevelP6P7(256,256))model=RetinaNet(backbone,num_classes,**kwargs)ifweightsisnotNone:model.load_state_dict(weights.get_state_dict(progress=progress,check_hash=True))ifweights==RetinaNet_ResNet50_FPN_Weights.COCO_V1:overwrite_eps(model,0.0)returnmodel
[docs]@register_model()@handle_legacy_interface(weights=("pretrained",RetinaNet_ResNet50_FPN_V2_Weights.COCO_V1),weights_backbone=("pretrained_backbone",ResNet50_Weights.IMAGENET1K_V1),)defretinanet_resnet50_fpn_v2(*,weights:Optional[RetinaNet_ResNet50_FPN_V2_Weights]=None,progress:bool=True,num_classes:Optional[int]=None,weights_backbone:Optional[ResNet50_Weights]=None,trainable_backbone_layers:Optional[int]=None,**kwargs:Any,)->RetinaNet:""" Constructs an improved RetinaNet model with a ResNet-50-FPN backbone. .. betastatus:: detection module Reference: `Bridging the Gap Between Anchor-based and Anchor-free Detection via Adaptive Training Sample Selection <https://arxiv.org/abs/1912.02424>`_. :func:`~torchvision.models.detection.retinanet_resnet50_fpn` for more details. Args: weights (:class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights`, optional): The pretrained weights to use. See :class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights` below for more details, and possible values. By default, no pre-trained weights are used. progress (bool): If True, displays a progress bar of the download to stderr. Default is True. num_classes (int, optional): number of output classes of the model (including the background) weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for the backbone. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is passed (the default) this value is set to 3. **kwargs: parameters passed to the ``torchvision.models.detection.RetinaNet`` base class. Please refer to the `source code <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/retinanet.py>`_ for more details about this class. .. autoclass:: torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights :members: """weights=RetinaNet_ResNet50_FPN_V2_Weights.verify(weights)weights_backbone=ResNet50_Weights.verify(weights_backbone)ifweightsisnotNone:weights_backbone=Nonenum_classes=_ovewrite_value_param("num_classes",num_classes,len(weights.meta["categories"]))elifnum_classesisNone:num_classes=91is_trained=weightsisnotNoneorweights_backboneisnotNonetrainable_backbone_layers=_validate_trainable_layers(is_trained,trainable_backbone_layers,5,3)backbone=resnet50(weights=weights_backbone,progress=progress)backbone=_resnet_fpn_extractor(backbone,trainable_backbone_layers,returned_layers=[2,3,4],extra_blocks=LastLevelP6P7(2048,256))anchor_generator=_default_anchorgen()head=RetinaNetHead(backbone.out_channels,anchor_generator.num_anchors_per_location()[0],num_classes,norm_layer=partial(nn.GroupNorm,32),)head.regression_head._loss_type="giou"model=RetinaNet(backbone,num_classes,anchor_generator=anchor_generator,head=head,**kwargs)ifweightsisnotNone:model.load_state_dict(weights.get_state_dict(progress=progress,check_hash=True))returnmodel
Docs
Access comprehensive developer documentation for PyTorch
To analyze traffic and optimize your experience, we serve cookies on this site. By clicking or navigating, you agree to allow our usage of cookies. As the current maintainers of this site, Facebook’s Cookies Policy applies. Learn more, including about available controls: Cookies Policy.