DetectionDataModule¶
Lightning data module for object detection datasets in COCO format.
Overview¶
DetectionDataModule is a PyTorch Lightning data module for object detection that supports:
- COCO format datasets with automatic annotation loading
- Torchvision and albumentations transform backends
- Built-in augmentation presets optimized for detection
- Efficient collation for variable-sized objects per image
- Multi-worker data loading with prefetching
API Reference¶
autotimm.DetectionDataModule ¶
Bases: LightningDataModule
Lightning data module for object detection.
Supports two modes:
-
COCO mode (default) -- expects COCO-style directory structure::
data_dir/ train2017/ # Training images val2017/ # Validation images annotations/ instances_train2017.json instances_val2017.json
-
CSV mode -- provide
train_csvpointing to a CSV file with columnsimage_path,x_min,y_min,x_max,y_max,label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dir
|
str | Path
|
Root directory containing images and annotations. |
'./coco'
|
train_images_dir
|
str | Path | None
|
Path to training images. Defaults to data_dir/train2017. |
None
|
val_images_dir
|
str | Path | None
|
Path to validation images. Defaults to data_dir/val2017. |
None
|
train_ann_file
|
str | Path | None
|
Path to train annotations. Defaults to data_dir/annotations/instances_train2017.json. |
None
|
val_ann_file
|
str | Path | None
|
Path to val annotations. Defaults to data_dir/annotations/instances_val2017.json. |
None
|
test_images_dir
|
str | Path | None
|
Optional path to test images. |
None
|
test_ann_file
|
str | Path | None
|
Optional path to test annotations. |
None
|
train_csv
|
str | Path | None
|
Path to training CSV file (CSV mode). |
None
|
val_csv
|
str | Path | None
|
Path to validation CSV file (CSV mode). |
None
|
test_csv
|
str | Path | None
|
Path to test CSV file (CSV mode). |
None
|
image_dir
|
str | Path | None
|
Root directory for resolving image paths in CSV mode. |
None
|
image_column
|
str
|
CSV column name for image paths. |
'image_path'
|
bbox_columns
|
list[str] | None
|
CSV column names for bbox coordinates. |
None
|
label_column
|
str
|
CSV column name for class labels. |
'label'
|
image_size
|
int
|
Target image size (square). |
640
|
batch_size
|
int
|
Batch size for all dataloaders. |
16
|
num_workers
|
int
|
Number of data-loading workers. Defaults to |
min(cpu_count() or 4, 4)
|
train_transforms
|
Callable | None
|
Custom training transforms. Must include bbox_params. |
None
|
eval_transforms
|
Callable | None
|
Custom eval transforms. Must include bbox_params. |
None
|
augmentation_preset
|
str
|
Preset name ( |
'default'
|
transform_config
|
TransformConfig | None
|
Optional :class: |
None
|
backbone
|
str | Module | None
|
Optional backbone name or module. Used with |
None
|
pin_memory
|
bool
|
Pin memory for GPU transfer. |
True
|
persistent_workers
|
bool
|
Keep worker processes alive between epochs. |
False
|
prefetch_factor
|
int | None
|
Number of batches prefetched per worker. |
None
|
min_bbox_area
|
float
|
Minimum bbox area to include in training. |
0.0
|
class_ids
|
list[int] | None
|
Optional list of class IDs to filter. |
None
|
Source code in src/autotimm/data/detection_datamodule.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | |
__init__ ¶
__init__(data_dir: str | Path = './coco', train_images_dir: str | Path | None = None, val_images_dir: str | Path | None = None, train_ann_file: str | Path | None = None, val_ann_file: str | Path | None = None, test_images_dir: str | Path | None = None, test_ann_file: str | Path | None = None, train_csv: str | Path | None = None, val_csv: str | Path | None = None, test_csv: str | Path | None = None, image_dir: str | Path | None = None, image_column: str = 'image_path', bbox_columns: list[str] | None = None, label_column: str = 'label', image_size: int = 640, batch_size: int = 16, num_workers: int = min(os.cpu_count() or 4, 4), train_transforms: Callable | None = None, eval_transforms: Callable | None = None, augmentation_preset: str = 'default', transform_config: TransformConfig | None = None, backbone: str | Module | None = None, pin_memory: bool = True, persistent_workers: bool = False, prefetch_factor: int | None = None, min_bbox_area: float = 0.0, class_ids: list[int] | None = None)
Source code in src/autotimm/data/detection_datamodule.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
setup ¶
train_dataloader ¶
val_dataloader ¶
test_dataloader ¶
Source code in src/autotimm/data/detection_datamodule.py
Usage Examples¶
Basic COCO Dataset¶
from autotimm import DetectionDataModule
data = DetectionDataModule(
data_dir="./coco",
image_size=640,
batch_size=16,
)
With Augmentation Preset¶
data = DetectionDataModule(
data_dir="./coco",
image_size=640,
batch_size=16,
augmentation_preset="strong", # Enhanced augmentation
)
With Albumentations¶
data = DetectionDataModule(
data_dir="./coco",
image_size=640,
batch_size=16,
transform_backend="albumentations",
augmentation_preset="strong",
)
With Custom Transforms¶
from torchvision import transforms as T
custom_train = T.Compose([
T.RandomHorizontalFlip(p=0.5),
T.ColorJitter(brightness=0.2, contrast=0.2),
T.ToTensor(),
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
data = DetectionDataModule(
data_dir="./coco",
image_size=640,
batch_size=16,
train_transforms=custom_train,
)
Performance Optimization¶
data = DetectionDataModule(
data_dir="./coco",
image_size=640,
batch_size=16,
num_workers=8,
pin_memory=True,
persistent_workers=True,
prefetch_factor=4,
)
With TransformConfig (Model-Specific Normalization)¶
Use TransformConfig with a backbone to get model-specific normalization:
from autotimm import DetectionDataModule, TransformConfig
# Create shared config
config = TransformConfig(
preset="default",
image_size=640,
use_timm_config=True, # Use model's pretrained mean/std
)
data = DetectionDataModule(
data_dir="./coco",
transform_config=config,
backbone="resnet50", # Required for model-specific normalization
)
Shared Config Between Model and Data¶
from autotimm import ObjectDetector, DetectionDataModule, TransformConfig, MetricConfig
# Shared config ensures same preprocessing
config = TransformConfig(preset="default", image_size=640)
backbone_name = "resnet50"
# DataModule uses model's normalization
data = DetectionDataModule(
data_dir="./coco",
transform_config=config,
backbone=backbone_name,
)
data.setup("fit")
# Model uses same config for inference preprocessing
metrics = [MetricConfig(
name="mAP",
backend="torchmetrics",
metric_class="MeanAveragePrecision",
params={"box_format": "xyxy"},
stages=["val"],
)]
model = ObjectDetector(
backbone=backbone_name,
num_classes=data.num_classes,
metrics=metrics,
transform_config=config,
)
Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
data_dir |
str \| Path |
"./coco" |
Root directory |
image_size |
int |
640 |
Target image size |
batch_size |
int |
16 |
Batch size |
num_workers |
int |
4 |
Data loading workers |
train_transforms |
Callable \| None |
None |
Custom train transforms |
val_transforms |
Callable \| None |
None |
Custom validation transforms |
augmentation_preset |
str \| None |
"default" |
Preset name |
transform_backend |
str |
"torchvision" |
"torchvision" or "albumentations" |
pin_memory |
bool |
True |
Pin memory for GPU |
persistent_workers |
bool |
False |
Keep workers alive |
prefetch_factor |
int \| None |
None |
Prefetch batches |
transform_config |
TransformConfig \| None |
None |
Unified transform configuration |
backbone |
str \| nn.Module \| None |
None |
Backbone for model-specific normalization |
Attributes¶
| Attribute | Type | Description |
|---|---|---|
num_classes |
int \| None |
Number of object classes (after setup) |
train_dataset |
Dataset \| None |
Training dataset (after setup) |
val_dataset |
Dataset \| None |
Validation dataset (after setup) |
test_dataset |
Dataset \| None |
Test dataset (after setup) |
COCO Format¶
The data directory should follow this structure:
coco/
├── annotations/
│ ├── instances_train2017.json
│ ├── instances_val2017.json
│ └── instances_test2017.json # Optional
├── train2017/
│ ├── 000000000001.jpg
│ ├── 000000000002.jpg
│ └── ...
├── val2017/
│ ├── 000000000001.jpg
│ └── ...
└── test2017/ # Optional
└── ...
Annotation Format¶
COCO annotations should have this structure:
{
"images": [
{
"id": 1,
"file_name": "000000000001.jpg",
"height": 480,
"width": 640
}
],
"annotations": [
{
"id": 1,
"image_id": 1,
"category_id": 1,
"bbox": [x, y, width, height],
"area": 12345,
"iscrowd": 0
}
],
"categories": [
{
"id": 1,
"name": "person",
"supercategory": "person"
}
]
}
Augmentation Presets¶
Torchvision¶
| Preset | Description |
|---|---|
default |
RandomHorizontalFlip, ColorJitter, ToTensor |
strong |
Default + RandomPhotometricDistort |
Albumentations¶
| Preset | Description |
|---|---|
default |
HorizontalFlip, ColorJitter |
strong |
HorizontalFlip, RandomBrightnessContrast, HueSaturationValue, Blur, Noise |
Data Output¶
Each batch contains:
batch = {
"image": Tensor, # Shape: (B, 3, H, W)
"boxes": List[Tensor], # List of (N, 4) tensors in [x1, y1, x2, y2] format
"labels": List[Tensor], # List of (N,) tensors with class indices
}
See Also¶
- CSV Data Loading API - CSV dataset for object detection
- ObjectDetector - Object detection model
- TransformConfig - Unified transform configuration
- Object Detection Data Guide - Complete data loading guide
- Object Detection Example - End-to-end detection example