[docs]defiou_loss(pred:torch.Tensor,target:torch.Tensor,reducer:LossReducer=identity_loss,mode:str="log",eps:float=1e-6,)->torch.Tensor:"""Compute IoU loss. Args: pred (torch.Tensor): Predicted bboxes. target (torch.Tensor): Target bboxes. reducer (LossReducer): Reducer to reduce the loss value. Defaults to identy_loss, which is no reduction. mode (str, optional): Mode to calculate the loss. Defaults to "log". eps (float, optional): Epsilon value to avoid division by zero. Returns: torch.Tensor : The reduced IoU loss. """assertmodein{"linear","square","log",},f"Invalid mode {mode}. Must be one of 'linear', 'square', 'log'."ious=bbox_iou_aligned(pred,target).clamp(min=eps)ifmode=="linear":loss=1-iouselifmode=="square":loss=1-ious**2else:loss=-ious.log()returnreducer(loss)
[docs]classIoULoss(Loss):"""IoU loss. Computing the IoU loss between a set of predicted bboxes and target bboxes. The loss is calculated depending on the mode: - linear: 1 - IoU - square: 1 - IoU^2 - log: -log(IoU) Args: reducer (LossReducer): Reducer to reduce the loss value. Defaults to identy_loss, which is no reduction. mode (str, optional): Mode to calculate the loss. Defaults to "log". eps (float, optional): Epsilon value to avoid division by zero. """def__init__(self,reducer:LossReducer=identity_loss,mode:str="log",eps:float=1e-6,):"""Creates an instance of the class."""super().__init__(reducer)self.mode=modeself.eps=epsassertmodein{"linear","square","log",},f"Invalid mode {mode}. Must be one of 'linear', 'square', 'log'."
[docs]defforward(# pylint: disable=arguments-differself,pred:torch.Tensor,target:torch.Tensor)->torch.Tensor:"""Forward function. Args: pred (torch.Tensor): Predicted bboxes. target (torch.Tensor): Target bboxes. Returns: torch.Tensor: The reduced IoU loss. """returniou_loss(pred,target,reducer=self.reducer,mode=self.mode,eps=self.eps)