Add https://www.reddit.com/r/Ultralytics/ badge (#13284)
* Refactor code for speed and clarity * Update README.zh-CN.md Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> --------- Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> Co-authored-by: UltralyticsAssistant <web@ultralytics.com>
This commit is contained in:
1 parent
b40781b3e3
commit
c5ffbbf1c3
20 files changed
+164
-73
No files matched your search
+2
-1
@@ -12,7 +12,8 @@ def emojis(str=""):
|
||||
|
||||
|
||||
class TryExcept(contextlib.ContextDecorator):
|
||||
# YOLOv5 TryExcept class. Usage: @TryExcept() decorator or 'with TryExcept():' context manager
|
||||
"""A context manager and decorator for error handling that prints an optional message with emojis on exception."""
|
||||
|
||||
def __init__(self, msg=""):
|
||||
"""Initializes TryExcept with an optional message, used as a decorator or context manager for error handling."""
|
||||
self.msg = msg
|
||||
|
||||
@@ -7,6 +7,8 @@ import torch.nn.functional as F
|
||||
|
||||
|
||||
class SiLU(nn.Module):
|
||||
"""Applies the Sigmoid-weighted Linear Unit (SiLU) activation function, also known as Swish."""
|
||||
|
||||
@staticmethod
|
||||
def forward(x):
|
||||
"""
|
||||
@@ -18,6 +20,8 @@ class SiLU(nn.Module):
|
||||
|
||||
|
||||
class Hardswish(nn.Module):
|
||||
"""Applies the Hardswish activation function, which is efficient for mobile and embedded devices."""
|
||||
|
||||
@staticmethod
|
||||
def forward(x):
|
||||
"""
|
||||
@@ -38,7 +42,11 @@ class Mish(nn.Module):
|
||||
|
||||
|
||||
class MemoryEfficientMish(nn.Module):
|
||||
"""Efficiently applies the Mish activation function using custom autograd for reduced memory usage."""
|
||||
|
||||
class F(torch.autograd.Function):
|
||||
"""Implements a custom autograd function for memory-efficient Mish activation."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, x):
|
||||
"""Applies the Mish activation function, a smooth ReLU alternative, to the input tensor `x`."""
|
||||
|
||||
@@ -18,7 +18,8 @@ IMAGENET_STD = 0.229, 0.224, 0.225 # RGB standard deviation
|
||||
|
||||
|
||||
class Albumentations:
|
||||
# YOLOv5 Albumentations class (optional, only used if package is installed)
|
||||
"""Provides optional data augmentation for YOLOv5 using Albumentations library if installed."""
|
||||
|
||||
def __init__(self, size=640):
|
||||
"""Initializes Albumentations class for optional data augmentation in YOLOv5 with specified input size."""
|
||||
self.transform = None
|
||||
@@ -378,7 +379,8 @@ def classify_transforms(size=224):
|
||||
|
||||
|
||||
class LetterBox:
|
||||
# YOLOv5 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])
|
||||
"""Resizes and pads images to specified dimensions while maintaining aspect ratio for YOLOv5 preprocessing."""
|
||||
|
||||
def __init__(self, size=(640, 640), auto=False, stride=32):
|
||||
"""Initializes a LetterBox object for YOLOv5 image preprocessing with optional auto sizing and stride
|
||||
adjustment.
|
||||
@@ -405,7 +407,8 @@ class LetterBox:
|
||||
|
||||
|
||||
class CenterCrop:
|
||||
# YOLOv5 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])
|
||||
"""Applies center crop to an image, resizing it to the specified size while maintaining aspect ratio."""
|
||||
|
||||
def __init__(self, size=640):
|
||||
"""Initializes CenterCrop for image preprocessing, accepting single int or tuple for size, defaults to 640."""
|
||||
super().__init__()
|
||||
@@ -424,7 +427,8 @@ class CenterCrop:
|
||||
|
||||
|
||||
class ToTensor:
|
||||
# YOLOv5 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])
|
||||
"""Converts BGR np.array image from HWC to RGB CHW format, normalizes to [0, 1], and supports FP16 if half=True."""
|
||||
|
||||
def __init__(self, half=False):
|
||||
"""Initializes ToTensor for YOLOv5 image preprocessing, with optional half precision (half=True for FP16)."""
|
||||
super().__init__()
|
||||
|
||||
@@ -131,6 +131,8 @@ def seed_worker(worker_id):
|
||||
# Inherit from DistributedSampler and override iterator
|
||||
# https://github.com/pytorch/pytorch/blob/master/torch/utils/data/distributed.py
|
||||
class SmartDistributedSampler(distributed.DistributedSampler):
|
||||
"""A distributed sampler ensuring deterministic shuffling and balanced data distribution across GPUs."""
|
||||
|
||||
def __iter__(self):
|
||||
"""Yields indices for distributed data sampling, shuffled deterministically based on epoch and seed."""
|
||||
g = torch.Generator()
|
||||
@@ -259,7 +261,8 @@ class _RepeatSampler:
|
||||
|
||||
|
||||
class LoadScreenshots:
|
||||
# YOLOv5 screenshot dataloader, i.e. `python detect.py --source "screen 0 100 100 512 256"`
|
||||
"""Loads and processes screenshots for YOLOv5 detection from specified screen regions using mss."""
|
||||
|
||||
def __init__(self, source, img_size=640, stride=32, auto=True, transforms=None):
|
||||
"""
|
||||
Initializes a screenshot dataloader for YOLOv5 with specified source region, image size, stride, auto, and
|
||||
@@ -428,7 +431,8 @@ class LoadImages:
|
||||
|
||||
|
||||
class LoadStreams:
|
||||
# YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams`
|
||||
"""Loads and processes video streams for YOLOv5, supporting various sources including YouTube and IP cameras."""
|
||||
|
||||
def __init__(self, sources="file.streams", img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):
|
||||
"""Initializes a stream loader for processing video streams with YOLOv5, supporting various sources including
|
||||
YouTube.
|
||||
@@ -531,7 +535,8 @@ def img2label_paths(img_paths):
|
||||
|
||||
|
||||
class LoadImagesAndLabels(Dataset):
|
||||
# YOLOv5 train_loader/val_loader, loads images and labels for training and validation
|
||||
"""Loads images and their corresponding labels for training and validation in YOLOv5."""
|
||||
|
||||
cache_version = 0.6 # dataset labels *.cache version
|
||||
rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]
|
||||
|
||||
|
||||
+6
-3
@@ -188,7 +188,8 @@ CONFIG_DIR = user_config_dir() # Ultralytics settings dir
|
||||
|
||||
|
||||
class Profile(contextlib.ContextDecorator):
|
||||
# YOLOv5 Profile class. Usage: @Profile() decorator or 'with Profile():' context manager
|
||||
"""Context manager and decorator for profiling code execution time, with optional CUDA synchronization."""
|
||||
|
||||
def __init__(self, t=0.0, device: torch.device = None):
|
||||
"""Initializes a profiling context for YOLOv5 with optional timing threshold and device specification."""
|
||||
self.t = t
|
||||
@@ -213,7 +214,8 @@ class Profile(contextlib.ContextDecorator):
|
||||
|
||||
|
||||
class Timeout(contextlib.ContextDecorator):
|
||||
# YOLOv5 Timeout class. Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager
|
||||
"""Enforces a timeout on code execution, raising TimeoutError if the specified duration is exceeded."""
|
||||
|
||||
def __init__(self, seconds, *, timeout_msg="", suppress_timeout_errors=True):
|
||||
"""Initializes a timeout context/decorator with defined seconds, optional message, and error suppression."""
|
||||
self.seconds = int(seconds)
|
||||
@@ -239,7 +241,8 @@ class Timeout(contextlib.ContextDecorator):
|
||||
|
||||
|
||||
class WorkingDirectory(contextlib.ContextDecorator):
|
||||
# Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager
|
||||
"""Context manager/decorator to temporarily change the working directory within a 'with' statement or decorator."""
|
||||
|
||||
def __init__(self, new_dir):
|
||||
"""Initializes a context manager/decorator to temporarily change the working directory."""
|
||||
self.dir = new_dir # new dir
|
||||
|
||||
@@ -76,7 +76,8 @@ def _json_default(value):
|
||||
|
||||
|
||||
class Loggers:
|
||||
# YOLOv5 Loggers class
|
||||
"""Initializes and manages various logging utilities for tracking YOLOv5 training and validation metrics."""
|
||||
|
||||
def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS):
|
||||
"""Initializes loggers for YOLOv5 training and validation metrics, paths, and options."""
|
||||
self.save_dir = save_dir
|
||||
|
||||
+8
-3
@@ -14,7 +14,8 @@ def smooth_BCE(eps=0.1):
|
||||
|
||||
|
||||
class BCEBlurWithLogitsLoss(nn.Module):
|
||||
# BCEwithLogitLoss() with reduced missing label effects.
|
||||
"""Modified BCEWithLogitsLoss to reduce missing label effects in YOLOv5 training with optional alpha smoothing."""
|
||||
|
||||
def __init__(self, alpha=0.05):
|
||||
"""Initializes a modified BCEWithLogitsLoss with reduced missing label effects, taking optional alpha smoothing
|
||||
parameter.
|
||||
@@ -37,7 +38,8 @@ class BCEBlurWithLogitsLoss(nn.Module):
|
||||
|
||||
|
||||
class FocalLoss(nn.Module):
|
||||
# Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
|
||||
"""Applies focal loss to address class imbalance by modifying BCEWithLogitsLoss with gamma and alpha parameters."""
|
||||
|
||||
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'.
|
||||
@@ -71,7 +73,8 @@ class FocalLoss(nn.Module):
|
||||
|
||||
|
||||
class QFocalLoss(nn.Module):
|
||||
# Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
|
||||
"""Implements Quality Focal Loss to address class imbalance by modulating loss based on prediction confidence."""
|
||||
|
||||
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
|
||||
"""Initializes Quality Focal Loss with given loss function, gamma, alpha; modifies reduction to 'none'."""
|
||||
super().__init__()
|
||||
@@ -101,6 +104,8 @@ class QFocalLoss(nn.Module):
|
||||
|
||||
|
||||
class ComputeLoss:
|
||||
"""Computes the total loss for YOLOv5 model predictions, including classification, box, and objectness losses."""
|
||||
|
||||
sort_obj_iou = False
|
||||
|
||||
# Compute losses
|
||||
|
||||
+2
-1
@@ -122,7 +122,8 @@ def compute_ap(recall, precision):
|
||||
|
||||
|
||||
class ConfusionMatrix:
|
||||
# Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
|
||||
"""Generates and visualizes a confusion matrix for evaluating object detection classification performance."""
|
||||
|
||||
def __init__(self, nc, conf=0.25, iou_thres=0.45):
|
||||
"""Initializes ConfusionMatrix with given number of classes, confidence, and IoU threshold."""
|
||||
self.matrix = np.zeros((nc + 1, nc + 1))
|
||||
|
||||
+2
-1
@@ -29,7 +29,8 @@ matplotlib.use("Agg") # for writing to files only
|
||||
|
||||
|
||||
class Colors:
|
||||
# Ultralytics color palette https://ultralytics.com/
|
||||
"""Provides an RGB color palette derived from Ultralytics color scheme for visualization tasks."""
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
Initializes the Colors class with a palette derived from Ultralytics color scheme, converting hex codes to RGB.
|
||||
|
||||
@@ -83,6 +83,8 @@ def create_dataloader(
|
||||
|
||||
|
||||
class LoadImagesAndLabelsAndMasks(LoadImagesAndLabels): # for training/testing
|
||||
"""Loads images, labels, and segmentation masks for training and testing YOLO models with augmentation support."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
path,
|
||||
|
||||
@@ -12,7 +12,8 @@ from .general import crop_mask
|
||||
|
||||
|
||||
class ComputeLoss:
|
||||
# Compute losses
|
||||
"""Computes the YOLOv5 model's loss components including classification, objectness, box, and mask losses."""
|
||||
|
||||
def __init__(self, model, autobalance=False, overlap=False):
|
||||
"""Initializes the compute loss function for YOLOv5 models with options for autobalancing and overlap
|
||||
handling.
|
||||
|
||||
@@ -54,6 +54,8 @@ def ap_per_class_box_and_mask(
|
||||
|
||||
|
||||
class Metric:
|
||||
"""Computes performance metrics like precision, recall, F1 score, and average precision for model evaluation."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initializes performance metric attributes for precision, recall, F1 score, average precision, and class
|
||||
indices.
|
||||
|
||||
@@ -420,7 +420,8 @@ def smart_resume(ckpt, optimizer, ema=None, weights="yolov5s.pt", epochs=300, re
|
||||
|
||||
|
||||
class EarlyStopping:
|
||||
# YOLOv5 simple early stopper
|
||||
"""Implements early stopping to halt training when no improvement is observed for a specified number of epochs."""
|
||||
|
||||
def __init__(self, patience=30):
|
||||
"""Initializes simple early stopping mechanism for YOLOv5, with adjustable patience for non-improving epochs."""
|
||||
self.best_fitness = 0.0 # i.e. mAP
|
||||
|
||||
Reference in new issue
Block a user