Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/docstrings' into docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
glenn-jocher committed Feb 25, 2024
2 parents 32162cc + 32f93bd commit 5c4d857
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 10 deletions.
4 changes: 3 additions & 1 deletion utils/loggers/comet/hpo.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@


def get_args(known=False):
"""Parses command-line arguments for YOLOv5 training, supporting configuration of weights, data paths, hyperparameters, and more."""
"""Parses command-line arguments for YOLOv5 training, supporting configuration of weights, data paths,
hyperparameters, and more.
"""
parser = argparse.ArgumentParser()
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="initial weights path")
parser.add_argument("--cfg", type=str, default="", help="model.yaml path")
Expand Down
20 changes: 15 additions & 5 deletions utils/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#iss
class BCEBlurWithLogitsLoss(nn.Module):
# BCEwithLogitLoss() with reduced missing label effects.
def __init__(self, alpha=0.05):
"""Initializes a modified BCEWithLogitsLoss with reduced missing label effects, taking optional alpha smoothing parameter."""
"""Initializes a modified BCEWithLogitsLoss with reduced missing label effects, taking optional alpha smoothing
parameter.
"""
super().__init__()
self.loss_fcn = nn.BCEWithLogitsLoss(reduction="none") # must be nn.BCEWithLogitsLoss()
self.alpha = alpha

def forward(self, pred, true):
"""Computes modified BCE loss for YOLOv5 with reduced missing label effects, taking pred and true tensors, returns mean loss."""
"""Computes modified BCE loss for YOLOv5 with reduced missing label effects, taking pred and true tensors,
returns mean loss.
"""
loss = self.loss_fcn(pred, true)
pred = torch.sigmoid(pred) # prob from logits
dx = pred - true # reduce only missing label effects
Expand All @@ -35,7 +39,9 @@ def forward(self, pred, true):
class FocalLoss(nn.Module):
# Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
"""Initializes FocalLoss with specified loss function, gamma, and alpha values; modifies loss reduction to 'none'."""
"""Initializes FocalLoss with specified loss function, gamma, and alpha values; modifies loss reduction to
'none'.
"""
super().__init__()
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
self.gamma = gamma
Expand Down Expand Up @@ -76,7 +82,9 @@ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
self.loss_fcn.reduction = "none" # required to apply FL to each element

def forward(self, pred, true):
"""Computes the focal loss between `pred` and `true` using BCEWithLogitsLoss, adjusting for imbalance with `gamma` and `alpha`."""
"""Computes the focal loss between `pred` and `true` using BCEWithLogitsLoss, adjusting for imbalance with
`gamma` and `alpha`.
"""
loss = self.loss_fcn(pred, true)

pred_prob = torch.sigmoid(pred) # prob from logits
Expand Down Expand Up @@ -180,7 +188,9 @@ def __call__(self, p, targets): # predictions, targets
return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()

def build_targets(self, p, targets):
"""Prepares model targets from input targets (image,class,x,y,w,h) for loss computation, returning class, box, indices, and anchors."""
"""Prepares model targets from input targets (image,class,x,y,w,h) for loss computation, returning class, box,
indices, and anchors.
"""
na, nt = self.na, targets.shape[0] # number of anchors, targets
tcls, tbox, indices, anch = [], [], [], []
gain = torch.ones(7, device=self.device) # normalized to gridspace gain
Expand Down
4 changes: 3 additions & 1 deletion utils/segment/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,9 @@ def masks_iou(mask1, mask2, eps=1e-7):


def masks2segments(masks, strategy="largest"):
"""Converts binary (n,160,160) masks to polygon segments with options for concatenation or selecting the largest segment."""
"""Converts binary (n,160,160) masks to polygon segments with options for concatenation or selecting the largest
segment.
"""
segments = []
for x in masks.int().cpu().numpy().astype("uint8"):
c = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
Expand Down
8 changes: 6 additions & 2 deletions utils/segment/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
class ComputeLoss:
# Compute losses
def __init__(self, model, autobalance=False, overlap=False):
"""Initializes the compute loss function for YOLOv5 models with options for autobalancing and overlap handling."""
"""Initializes the compute loss function for YOLOv5 models with options for autobalancing and overlap
handling.
"""
self.sort_obj_iou = False
self.overlap = overlap
device = next(model.parameters()).device # get model device
Expand Down Expand Up @@ -116,7 +118,9 @@ def single_mask_loss(self, gt_mask, pred, proto, xyxy, area):
return (crop_mask(loss, xyxy).mean(dim=(1, 2)) / area).mean()

def build_targets(self, p, targets):
"""Prepares YOLOv5 targets for loss computation; inputs targets (image, class, x, y, w, h), output target classes/boxes."""
"""Prepares YOLOv5 targets for loss computation; inputs targets (image, class, x, y, w, h), output target
classes/boxes.
"""
na, nt = self.na, targets.shape[0] # number of anchors, targets
tcls, tbox, indices, anch, tidxs, xywhn = [], [], [], [], [], []
gain = torch.ones(8, device=self.device) # normalized to gridspace gain
Expand Down
4 changes: 3 additions & 1 deletion utils/segment/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,9 @@ def class_result(self, i):
return self.metric_box.class_result(i) + self.metric_mask.class_result(i)

def get_maps(self, nc):
"""Calculates and returns the sum of mean average precisions (mAPs) for both box and mask metrics for `nc` classes."""
"""Calculates and returns the sum of mean average precisions (mAPs) for both box and mask metrics for `nc`
classes.
"""
return self.metric_box.get_maps(nc) + self.metric_mask.get_maps(nc)

@property
Expand Down

0 comments on commit 5c4d857

Please sign in to comment.