Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/docstrings2' into docstrings2
Browse files Browse the repository at this point in the history
  • Loading branch information
glenn-jocher committed Feb 25, 2024
2 parents 6f0d1bf + fb1f6c7 commit 8276eef
Show file tree
Hide file tree
Showing 8 changed files with 59 additions and 12 deletions.
10 changes: 8 additions & 2 deletions models/experimental.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@

class Sum(nn.Module):
"""Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070."""

def __init__(self, n, weight=False):
"""Initializes a module to sum outputs of layers with number of inputs `n` and optional weighting, supporting 2+ inputs."""
"""Initializes a module to sum outputs of layers with number of inputs `n` and optional weighting, supporting 2+
inputs.
"""
super().__init__()
self.weight = weight # apply weights boolean
self.iter = range(n - 1) # iter object
Expand All @@ -34,8 +37,11 @@ def forward(self, x):

class MixConv2d(nn.Module):
"""Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595."""

def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
"""Initializes MixConv2d with mixed depth-wise convolutional layers, taking input and output channels (c1, c2), kernel sizes (k), stride (s), and channel distribution strategy (equal_ch)."""
"""Initializes MixConv2d with mixed depth-wise convolutional layers, taking input and output channels (c1, c2),
kernel sizes (k), stride (s), and channel distribution strategy (equal_ch).
"""
super().__init__()
n = len(k) # number of convolutions
if equal_ch: # equal c_ per group
Expand Down
10 changes: 8 additions & 2 deletions models/yolo.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,11 @@ def _clip_augmented(self, y):
return y

def _initialize_biases(self, cf=None):
"""Initializes biases for YOLOv5's Detect() module, optionally using class frequencies (cf). For details see https://arxiv.org/abs/1708.02002 section 3.3."""
"""
Initializes biases for YOLOv5's Detect() module, optionally using class frequencies (cf).
For details see https://arxiv.org/abs/1708.02002 section 3.3.
"""
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
m = self.model[-1] # Detect() module
for mi, s in zip(m.m, m.stride): # from
Expand All @@ -333,7 +337,9 @@ def __init__(self, cfg="yolov5s-seg.yaml", ch=3, nc=None, anchors=None):
class ClassificationModel(BaseModel):
# YOLOv5 classification model
def __init__(self, cfg=None, model=None, nc=1000, cutoff=10):
"""Initializes YOLOv5 model with config file `cfg`, input channels `ch`, number of classes `nc`, and `cuttoff` index."""
"""Initializes YOLOv5 model with config file `cfg`, input channels `ch`, number of classes `nc`, and `cuttoff`
index.
"""
super().__init__()
self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg)

Expand Down
6 changes: 5 additions & 1 deletion segment/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,11 @@


def train(hyp, opt, device, callbacks):
"""Trains the YOLOv5 model on a dataset, managing hyperparameters, model optimization, logging, and validation. `hyp` is path/to/hyp.yaml or hyp dictionary."""
"""
Trains the YOLOv5 model on a dataset, managing hyperparameters, model optimization, logging, and validation.
`hyp` is path/to/hyp.yaml or hyp dictionary.
"""
(
save_dir,
epochs,
Expand Down
7 changes: 6 additions & 1 deletion train.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,12 @@


def train(hyp, opt, device, callbacks):
"""Trains YOLOv5 model with given hyperparameters, options, and device, managing datasets, model architecture, loss computation, and optimizer steps. `hyp` argument is path/to/hyp.yaml or hyp dictionary."""
"""
Trains YOLOv5 model with given hyperparameters, options, and device, managing datasets, model architecture, loss
computation, and optimizer steps.
`hyp` argument is path/to/hyp.yaml or hyp dictionary.
"""
save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = (
Path(opt.save_dir),
opt.epochs,
Expand Down
1 change: 1 addition & 0 deletions utils/activations.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def forward(self, x):

class FReLU(nn.Module):
"""FReLU activation https://arxiv.org/abs/2007.11824."""

def __init__(self, c1, k=3): # ch_in, kernel
"""Initializes FReLU activation with channel `c1` and kernel size `k`."""
super().__init__()
Expand Down
26 changes: 22 additions & 4 deletions utils/augmentations.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,12 @@ def mixup(im, labels, im2, labels2):


def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):
"""Filters bounding box candidates by minimum width-height threshold `wh_thr` (pixels), aspect ratio threshold `ar_thr`, and area ratio threshold `area_thr`. box1(4,n) is before augmentation, box2(4,n) is after augmentation."""
"""
Filters bounding box candidates by minimum width-height threshold `wh_thr` (pixels), aspect ratio threshold
`ar_thr`, and area ratio threshold `area_thr`.
box1(4,n) is before augmentation, box2(4,n) is after augmentation.
"""
w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
Expand Down Expand Up @@ -381,7 +386,11 @@ def __init__(self, size=(640, 640), auto=False, stride=32):
self.stride = stride # used with auto

def __call__(self, im):
"""Resizes and pads input image `im` (HWC format) to specified dimensions, maintaining aspect ratio. im = np.array HWC"""
"""
Resizes and pads input image `im` (HWC format) to specified dimensions, maintaining aspect ratio.
im = np.array HWC
"""
imh, imw = im.shape[:2]
r = min(self.h / imh, self.w / imw) # ratio of new/old
h, w = round(imh * r), round(imw * r) # resized image
Expand All @@ -400,7 +409,11 @@ def __init__(self, size=640):
self.h, self.w = (size, size) if isinstance(size, int) else size

def __call__(self, im):
"""Applies center crop to the input image and resizes it to a specified size, maintaining aspect ratio. im = np.array HWC"""
"""
Applies center crop to the input image and resizes it to a specified size, maintaining aspect ratio.
im = np.array HWC
"""
imh, imw = im.shape[:2]
m = min(imh, imw) # min dimension
top, left = (imh - m) // 2, (imw - m) // 2
Expand All @@ -415,7 +428,12 @@ def __init__(self, half=False):
self.half = half

def __call__(self, im):
"""Converts BGR np.array image from HWC to RGB CHW format, and normalizes to [0, 1], with support for FP16 if `half=True`. im = np.array HWC in BGR order"""
"""
Converts BGR np.array image from HWC to RGB CHW format, and normalizes to [0, 1], with support for FP16 if
`half=True`.
im = np.array HWC in BGR order
"""
im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1]) # HWC to CHW -> BGR to RGB -> contiguous
im = torch.from_numpy(im) # to torch
im = im.half() if self.half else im.float() # uint8 to fp16/32
Expand Down
7 changes: 6 additions & 1 deletion utils/dataloaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -1061,7 +1061,12 @@ def flatten_recursive(path=DATASETS_DIR / "coco128"):


def extract_boxes(path=DATASETS_DIR / "coco128"):
"""Converts a detection dataset to a classification dataset, creating a directory for each class and extracting bounding boxes. Example: from utils.dataloaders import *; extract_boxes()"""
"""
Converts a detection dataset to a classification dataset, creating a directory for each class and extracting
bounding boxes.
Example: from utils.dataloaders import *; extract_boxes()
"""
path = Path(path) # images dir
shutil.rmtree(path / "classification") if (path / "classification").is_dir() else None # remove existing
files = list(path.rglob("*.*"))
Expand Down
4 changes: 3 additions & 1 deletion utils/torch_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,9 @@ def model_info(model, verbose=False, imgsz=640):


def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
"""Scales an image tensor `img` of shape (bs,3,y,x) by `ratio`, optionally maintaining the original shape, padded to multiples of `gs`."""
"""Scales an image tensor `img` of shape (bs,3,y,x) by `ratio`, optionally maintaining the original shape, padded to
multiples of `gs`.
"""
if ratio == 1.0:
return img
h, w = img.shape[2:]
Expand Down

0 comments on commit 8276eef

Please sign in to comment.