You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
162 lines
6.7 KiB
162 lines
6.7 KiB
2 years ago
|
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
||
2 years ago
|
|
||
2 years ago
|
import torch
|
||
2 years ago
|
import torchvision
|
||
2 years ago
|
|
||
1 year ago
|
from ultralytics.data import ClassificationDataset, build_dataloader
|
||
|
from ultralytics.engine.trainer import BaseTrainer
|
||
|
from ultralytics.models import yolo
|
||
2 years ago
|
from ultralytics.nn.tasks import ClassificationModel, attempt_load_one_weight
|
||
1 year ago
|
from ultralytics.utils import DEFAULT_CFG, LOGGER, RANK, colorstr
|
||
|
from ultralytics.utils.plotting import plot_images, plot_results
|
||
|
from ultralytics.utils.torch_utils import is_parallel, strip_optimizer, torch_distributed_zero_first
|
||
2 years ago
|
|
||
|
|
||
2 years ago
|
class ClassificationTrainer(BaseTrainer):
|
||
2 years ago
|
|
||
2 years ago
|
def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
|
||
2 years ago
|
"""Initialize a ClassificationTrainer object with optional configuration overrides and callbacks."""
|
||
2 years ago
|
if overrides is None:
|
||
|
overrides = {}
|
||
2 years ago
|
overrides['task'] = 'classify'
|
||
2 years ago
|
if overrides.get('imgsz') is None:
|
||
2 years ago
|
overrides['imgsz'] = 224
|
||
2 years ago
|
super().__init__(cfg, overrides, _callbacks)
|
||
2 years ago
|
|
||
2 years ago
|
def set_model_attributes(self):
|
||
2 years ago
|
"""Set the YOLO model's class names from the loaded dataset."""
|
||
2 years ago
|
self.model.names = self.data['names']
|
||
2 years ago
|
|
||
2 years ago
|
def get_model(self, cfg=None, weights=None, verbose=True):
|
||
2 years ago
|
"""Returns a modified PyTorch model configured for training YOLO."""
|
||
2 years ago
|
model = ClassificationModel(cfg, nc=self.data['nc'], verbose=verbose and RANK == -1)
|
||
2 years ago
|
if weights:
|
||
|
model.load(weights)
|
||
2 years ago
|
|
||
|
for m in model.modules():
|
||
2 years ago
|
if not self.args.pretrained and hasattr(m, 'reset_parameters'):
|
||
2 years ago
|
m.reset_parameters()
|
||
|
if isinstance(m, torch.nn.Dropout) and self.args.dropout:
|
||
|
m.p = self.args.dropout # set dropout
|
||
|
for p in model.parameters():
|
||
|
p.requires_grad = True # for training
|
||
2 years ago
|
return model
|
||
|
|
||
2 years ago
|
def setup_model(self):
|
||
|
"""
|
||
|
load/create/download model for any task
|
||
|
"""
|
||
2 years ago
|
# Classification models require special handling
|
||
2 years ago
|
|
||
|
if isinstance(self.model, torch.nn.Module): # if model is loaded beforehand. No setup needed
|
||
|
return
|
||
|
|
||
2 years ago
|
model = str(self.model)
|
||
2 years ago
|
# Load a YOLO model locally, from torchvision, or from Ultralytics assets
|
||
2 years ago
|
if model.endswith('.pt'):
|
||
2 years ago
|
self.model, _ = attempt_load_one_weight(model, device='cpu')
|
||
2 years ago
|
for p in self.model.parameters():
|
||
2 years ago
|
p.requires_grad = True # for training
|
||
2 years ago
|
elif model.endswith('.yaml'):
|
||
2 years ago
|
self.model = self.get_model(cfg=model)
|
||
|
elif model in torchvision.models.__dict__:
|
||
2 years ago
|
self.model = torchvision.models.__dict__[model](weights='IMAGENET1K_V1' if self.args.pretrained else None)
|
||
2 years ago
|
else:
|
||
2 years ago
|
FileNotFoundError(f'ERROR: model={model} not found locally or online. Please check model name.')
|
||
2 years ago
|
ClassificationModel.reshape_outputs(self.model, self.data['nc'])
|
||
2 years ago
|
|
||
|
return # dont return ckpt. Classification doesn't support resume
|
||
2 years ago
|
|
||
2 years ago
|
def build_dataset(self, img_path, mode='train', batch=None):
|
||
2 years ago
|
return ClassificationDataset(root=img_path, args=self.args, augment=mode == 'train')
|
||
2 years ago
|
|
||
2 years ago
|
def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode='train'):
|
||
2 years ago
|
"""Returns PyTorch DataLoader with transforms to preprocess images for inference."""
|
||
2 years ago
|
with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
|
||
|
dataset = self.build_dataset(dataset_path, mode)
|
||
|
|
||
|
loader = build_dataloader(dataset, batch_size, self.args.workers, rank=rank)
|
||
2 years ago
|
# Attach inference transforms
|
||
2 years ago
|
if mode != 'train':
|
||
2 years ago
|
if is_parallel(self.model):
|
||
|
self.model.module.transforms = loader.dataset.torch_transforms
|
||
|
else:
|
||
|
self.model.transforms = loader.dataset.torch_transforms
|
||
2 years ago
|
return loader
|
||
2 years ago
|
|
||
|
def preprocess_batch(self, batch):
|
||
2 years ago
|
"""Preprocesses a batch of images and classes."""
|
||
2 years ago
|
batch['img'] = batch['img'].to(self.device)
|
||
|
batch['cls'] = batch['cls'].to(self.device)
|
||
2 years ago
|
return batch
|
||
2 years ago
|
|
||
2 years ago
|
def progress_string(self):
|
||
2 years ago
|
"""Returns a formatted string showing training progress."""
|
||
2 years ago
|
return ('\n' + '%11s' * (4 + len(self.loss_names))) % \
|
||
|
('Epoch', 'GPU_mem', *self.loss_names, 'Instances', 'Size')
|
||
2 years ago
|
|
||
2 years ago
|
def get_validator(self):
|
||
2 years ago
|
"""Returns an instance of ClassificationValidator for validation."""
|
||
2 years ago
|
self.loss_names = ['loss']
|
||
1 year ago
|
return yolo.classify.ClassificationValidator(self.test_loader, self.save_dir)
|
||
2 years ago
|
|
||
2 years ago
|
def label_loss_items(self, loss_items=None, prefix='train'):
|
||
2 years ago
|
"""
|
||
|
Returns a loss dict with labelled training loss items tensor
|
||
|
"""
|
||
|
# Not needed for classification but necessary for segmentation & detection
|
||
2 years ago
|
keys = [f'{prefix}/{x}' for x in self.loss_names]
|
||
2 years ago
|
if loss_items is None:
|
||
2 years ago
|
return keys
|
||
2 years ago
|
loss_items = [round(float(loss_items), 5)]
|
||
|
return dict(zip(keys, loss_items))
|
||
2 years ago
|
|
||
2 years ago
|
def resume_training(self, ckpt):
|
||
2 years ago
|
"""Resumes training from a given checkpoint."""
|
||
2 years ago
|
pass
|
||
|
|
||
2 years ago
|
def plot_metrics(self):
|
||
|
"""Plots metrics from a CSV file."""
|
||
2 years ago
|
plot_results(file=self.csv, classify=True, on_plot=self.on_plot) # save results.png
|
||
2 years ago
|
|
||
2 years ago
|
def final_eval(self):
|
||
2 years ago
|
"""Evaluate trained model and save validation results."""
|
||
2 years ago
|
for f in self.last, self.best:
|
||
|
if f.exists():
|
||
|
strip_optimizer(f) # strip optimizers
|
||
|
# TODO: validate best.pt after training completes
|
||
|
# if f is self.best:
|
||
2 years ago
|
# LOGGER.info(f'\nValidating {f}...')
|
||
2 years ago
|
# self.validator.args.save_json = True
|
||
|
# self.metrics = self.validator(model=f)
|
||
|
# self.metrics.pop('fitness', None)
|
||
|
# self.run_callbacks('on_fit_epoch_end')
|
||
2 years ago
|
LOGGER.info(f"Results saved to {colorstr('bold', self.save_dir)}")
|
||
2 years ago
|
|
||
2 years ago
|
def plot_training_samples(self, batch, ni):
|
||
|
"""Plots training samples with their annotations."""
|
||
|
plot_images(images=batch['img'],
|
||
|
batch_idx=torch.arange(len(batch['img'])),
|
||
|
cls=batch['cls'].squeeze(-1),
|
||
2 years ago
|
fname=self.save_dir / f'train_batch{ni}.jpg',
|
||
|
on_plot=self.on_plot)
|
||
2 years ago
|
|
||
2 years ago
|
|
||
2 years ago
|
def train(cfg=DEFAULT_CFG, use_python=False):
|
||
2 years ago
|
"""Train the YOLO classification model."""
|
||
2 years ago
|
model = cfg.model or 'yolov8n-cls.pt' # or "resnet18"
|
||
|
data = cfg.data or 'mnist160' # or yolo.ClassificationDataset("mnist")
|
||
2 years ago
|
device = cfg.device if cfg.device is not None else ''
|
||
2 years ago
|
|
||
2 years ago
|
args = dict(model=model, data=data, device=device)
|
||
2 years ago
|
if use_python:
|
||
|
from ultralytics import YOLO
|
||
|
YOLO(model).train(**args)
|
||
|
else:
|
||
2 years ago
|
trainer = ClassificationTrainer(overrides=args)
|
||
2 years ago
|
trainer.train()
|
||
2 years ago
|
|
||
|
|
||
2 years ago
|
if __name__ == '__main__':
|
||
2 years ago
|
train()
|