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.
436 lines
19 KiB
436 lines
19 KiB
2 years ago
|
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
||
2 years ago
|
|
||
2 years ago
|
import sys
|
||
2 years ago
|
from pathlib import Path
|
||
2 years ago
|
from typing import Union
|
||
2 years ago
|
|
||
1 year ago
|
from ultralytics.cfg import get_cfg
|
||
|
from ultralytics.engine.exporter import Exporter
|
||
|
from ultralytics.models import yolo # noqa
|
||
2 years ago
|
from ultralytics.nn.tasks import (ClassificationModel, DetectionModel, PoseModel, SegmentationModel,
|
||
|
attempt_load_one_weight, guess_model_task, nn, yaml_model_load)
|
||
1 year ago
|
from ultralytics.utils import (DEFAULT_CFG, DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, RANK, ROOT, callbacks,
|
||
|
is_git_dir, yaml_load)
|
||
|
from ultralytics.utils.checks import check_file, check_imgsz, check_pip_update_available, check_yaml
|
||
|
from ultralytics.utils.downloads import GITHUB_ASSET_STEMS
|
||
|
from ultralytics.utils.torch_utils import smart_inference_mode
|
||
2 years ago
|
|
||
2 years ago
|
# Map head to model, trainer, validator, and predictor classes
|
||
2 years ago
|
TASK_MAP = {
|
||
2 years ago
|
'classify': [
|
||
1 year ago
|
ClassificationModel, yolo.classify.ClassificationTrainer, yolo.classify.ClassificationValidator,
|
||
|
yolo.classify.ClassificationPredictor],
|
||
|
'detect':
|
||
|
[DetectionModel, yolo.detect.DetectionTrainer, yolo.detect.DetectionValidator, yolo.detect.DetectionPredictor],
|
||
2 years ago
|
'segment': [
|
||
1 year ago
|
SegmentationModel, yolo.segment.SegmentationTrainer, yolo.segment.SegmentationValidator,
|
||
|
yolo.segment.SegmentationPredictor],
|
||
|
'pose': [PoseModel, yolo.pose.PoseTrainer, yolo.pose.PoseValidator, yolo.pose.PosePredictor]}
|
||
2 years ago
|
|
||
|
|
||
|
class YOLO:
|
||
2 years ago
|
"""
|
||
2 years ago
|
YOLO (You Only Look Once) object detection model.
|
||
|
|
||
|
Args:
|
||
|
model (str, Path): Path to the model file to load or create.
|
||
2 years ago
|
task (Any, optional): Task type for the YOLO model. Defaults to None.
|
||
2 years ago
|
|
||
|
Attributes:
|
||
|
predictor (Any): The predictor object.
|
||
|
model (Any): The model object.
|
||
|
trainer (Any): The trainer object.
|
||
|
task (str): The type of model task.
|
||
|
ckpt (Any): The checkpoint object if the model loaded from *.pt file.
|
||
|
cfg (str): The model configuration if loaded from *.yaml file.
|
||
|
ckpt_path (str): The checkpoint file path.
|
||
|
overrides (dict): Overrides for the trainer object.
|
||
2 years ago
|
metrics (Any): The data for metrics.
|
||
2 years ago
|
|
||
|
Methods:
|
||
|
__call__(source=None, stream=False, **kwargs):
|
||
|
Alias for the predict method.
|
||
|
_new(cfg:str, verbose:bool=True) -> None:
|
||
|
Initializes a new model and infers the task type from the model definitions.
|
||
|
_load(weights:str, task:str='') -> None:
|
||
|
Initializes a new model and infers the task type from the model head.
|
||
|
_check_is_pytorch_model() -> None:
|
||
|
Raises TypeError if the model is not a PyTorch model.
|
||
|
reset() -> None:
|
||
|
Resets the model modules.
|
||
|
info(verbose:bool=False) -> None:
|
||
|
Logs the model info.
|
||
|
fuse() -> None:
|
||
|
Fuses the model for faster inference.
|
||
1 year ago
|
predict(source=None, stream=False, **kwargs) -> List[ultralytics.engine.results.Results]:
|
||
2 years ago
|
Performs prediction using the YOLO model.
|
||
|
|
||
|
Returns:
|
||
1 year ago
|
list(ultralytics.engine.results.Results): The prediction results.
|
||
2 years ago
|
"""
|
||
2 years ago
|
|
||
2 years ago
|
def __init__(self, model: Union[str, Path] = 'yolov8n.pt', task=None) -> None:
|
||
2 years ago
|
"""
|
||
2 years ago
|
Initializes the YOLO model.
|
||
2 years ago
|
|
||
2 years ago
|
Args:
|
||
2 years ago
|
model (Union[str, Path], optional): Path or name of the model to load or create. Defaults to 'yolov8n.pt'.
|
||
|
task (Any, optional): Task type for the YOLO model. Defaults to None.
|
||
2 years ago
|
"""
|
||
2 years ago
|
self.callbacks = callbacks.get_default_callbacks()
|
||
2 years ago
|
self.predictor = None # reuse predictor
|
||
2 years ago
|
self.model = None # model object
|
||
|
self.trainer = None # trainer object
|
||
|
self.task = None # task type
|
||
2 years ago
|
self.ckpt = None # if loaded from *.pt
|
||
|
self.cfg = None # if loaded from *.yaml
|
||
2 years ago
|
self.ckpt_path = None
|
||
2 years ago
|
self.overrides = {} # overrides for trainer object
|
||
2 years ago
|
self.metrics = None # validation/training metrics
|
||
2 years ago
|
self.session = None # HUB session
|
||
|
model = str(model).strip() # strip spaces
|
||
|
|
||
|
# Check if Ultralytics HUB model from https://hub.ultralytics.com
|
||
2 years ago
|
if self.is_hub_model(model):
|
||
2 years ago
|
from ultralytics.hub.session import HUBTrainingSession
|
||
2 years ago
|
self.session = HUBTrainingSession(model)
|
||
|
model = self.session.model_file
|
||
2 years ago
|
|
||
2 years ago
|
# Load or create new YOLO model
|
||
2 years ago
|
suffix = Path(model).suffix
|
||
2 years ago
|
if not suffix and Path(model).stem in GITHUB_ASSET_STEMS:
|
||
|
model, suffix = Path(model).with_suffix('.pt'), '.pt' # add suffix, i.e. yolov8n -> yolov8n.pt
|
||
2 years ago
|
if suffix == '.yaml':
|
||
2 years ago
|
self._new(model, task)
|
||
2 years ago
|
else:
|
||
2 years ago
|
self._load(model, task)
|
||
2 years ago
|
|
||
2 years ago
|
def __call__(self, source=None, stream=False, **kwargs):
|
||
2 years ago
|
"""Calls the 'predict' function with given arguments to perform object detection."""
|
||
2 years ago
|
return self.predict(source, stream, **kwargs)
|
||
2 years ago
|
|
||
2 years ago
|
def __getattr__(self, attr):
|
||
2 years ago
|
"""Raises error if object has no requested attribute."""
|
||
2 years ago
|
name = self.__class__.__name__
|
||
|
raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
|
||
|
|
||
2 years ago
|
@staticmethod
|
||
|
def is_hub_model(model):
|
||
2 years ago
|
"""Check if the provided model is a HUB model."""
|
||
2 years ago
|
return any((
|
||
2 years ago
|
model.startswith('https://hub.ultralytics.com/models/'), # i.e. https://hub.ultralytics.com/models/MODEL_ID
|
||
2 years ago
|
[len(x) for x in model.split('_')] == [42, 20], # APIKEY_MODELID
|
||
2 years ago
|
len(model) == 20 and not Path(model).exists() and all(x not in model for x in './\\'))) # MODELID
|
||
2 years ago
|
|
||
2 years ago
|
def _new(self, cfg: str, task=None, verbose=True):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Initializes a new model and infers the task type from the model definitions.
|
||
2 years ago
|
|
||
|
Args:
|
||
|
cfg (str): model configuration file
|
||
1 year ago
|
task (str | None): model task
|
||
2 years ago
|
verbose (bool): display model info on load
|
||
2 years ago
|
"""
|
||
2 years ago
|
cfg_dict = yaml_model_load(cfg)
|
||
|
self.cfg = cfg
|
||
2 years ago
|
self.task = task or guess_model_task(cfg_dict)
|
||
2 years ago
|
self.model = TASK_MAP[self.task][0](cfg_dict, verbose=verbose and RANK == -1) # build model
|
||
2 years ago
|
self.overrides['model'] = self.cfg
|
||
2 years ago
|
|
||
2 years ago
|
# Below added to allow export from yamls
|
||
|
args = {**DEFAULT_CFG_DICT, **self.overrides} # combine model and default args, preferring model args
|
||
|
self.model.args = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS} # attach args to model
|
||
|
self.model.task = self.task
|
||
|
|
||
2 years ago
|
def _load(self, weights: str, task=None):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Initializes a new model and infers the task type from the model head.
|
||
2 years ago
|
|
||
|
Args:
|
||
|
weights (str): model checkpoint to be loaded
|
||
1 year ago
|
task (str | None): model task
|
||
2 years ago
|
"""
|
||
2 years ago
|
suffix = Path(weights).suffix
|
||
|
if suffix == '.pt':
|
||
|
self.model, self.ckpt = attempt_load_one_weight(weights)
|
||
2 years ago
|
self.task = self.model.args['task']
|
||
2 years ago
|
self.overrides = self.model.args = self._reset_ckpt_args(self.model.args)
|
||
2 years ago
|
self.ckpt_path = self.model.pt_path
|
||
2 years ago
|
else:
|
||
2 years ago
|
weights = check_file(weights)
|
||
2 years ago
|
self.model, self.ckpt = weights, None
|
||
2 years ago
|
self.task = task or guess_model_task(weights)
|
||
2 years ago
|
self.ckpt_path = weights
|
||
2 years ago
|
self.overrides['model'] = weights
|
||
2 years ago
|
self.overrides['task'] = self.task
|
||
2 years ago
|
|
||
2 years ago
|
def _check_is_pytorch_model(self):
|
||
|
"""
|
||
|
Raises TypeError is model is not a PyTorch model
|
||
|
"""
|
||
2 years ago
|
pt_str = isinstance(self.model, (str, Path)) and Path(self.model).suffix == '.pt'
|
||
|
pt_module = isinstance(self.model, nn.Module)
|
||
|
if not (pt_module or pt_str):
|
||
2 years ago
|
raise TypeError(f"model='{self.model}' must be a *.pt PyTorch model, but is a different type. "
|
||
2 years ago
|
f'PyTorch models can be used to train, val, predict and export, i.e. '
|
||
2 years ago
|
f"'yolo export model=yolov8n.pt', but exported formats like ONNX, TensorRT etc. only "
|
||
|
f"support 'predict' and 'val' modes, i.e. 'yolo predict model=yolov8n.onnx'.")
|
||
|
|
||
2 years ago
|
@smart_inference_mode()
|
||
|
def reset_weights(self):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Resets the model modules parameters to randomly initialized values, losing all training information.
|
||
2 years ago
|
"""
|
||
2 years ago
|
self._check_is_pytorch_model()
|
||
2 years ago
|
for m in self.model.modules():
|
||
|
if hasattr(m, 'reset_parameters'):
|
||
|
m.reset_parameters()
|
||
|
for p in self.model.parameters():
|
||
|
p.requires_grad = True
|
||
2 years ago
|
return self
|
||
|
|
||
|
@smart_inference_mode()
|
||
|
def load(self, weights='yolov8n.pt'):
|
||
|
"""
|
||
|
Transfers parameters with matching names and shapes from 'weights' to model.
|
||
|
"""
|
||
|
self._check_is_pytorch_model()
|
||
|
if isinstance(weights, (str, Path)):
|
||
|
weights, self.ckpt = attempt_load_one_weight(weights)
|
||
|
self.model.load(weights)
|
||
|
return self
|
||
2 years ago
|
|
||
2 years ago
|
def info(self, detailed=False, verbose=True):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Logs model info.
|
||
2 years ago
|
|
||
|
Args:
|
||
2 years ago
|
detailed (bool): Show detailed information about model.
|
||
2 years ago
|
verbose (bool): Controls verbosity.
|
||
2 years ago
|
"""
|
||
2 years ago
|
self._check_is_pytorch_model()
|
||
2 years ago
|
return self.model.info(detailed=detailed, verbose=verbose)
|
||
2 years ago
|
|
||
|
def fuse(self):
|
||
2 years ago
|
"""Fuse PyTorch Conv2d and BatchNorm2d layers."""
|
||
2 years ago
|
self._check_is_pytorch_model()
|
||
2 years ago
|
self.model.fuse()
|
||
|
|
||
2 years ago
|
@smart_inference_mode()
|
||
2 years ago
|
def predict(self, source=None, stream=False, **kwargs):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Perform prediction using the YOLO model.
|
||
2 years ago
|
|
||
|
Args:
|
||
2 years ago
|
source (str | int | PIL | np.ndarray): The source of the image to make predictions on.
|
||
|
Accepts all source types accepted by the YOLO model.
|
||
|
stream (bool): Whether to stream the predictions or not. Defaults to False.
|
||
|
**kwargs : Additional keyword arguments passed to the predictor.
|
||
|
Check the 'configuration' section in the documentation for all available options.
|
||
|
|
||
|
Returns:
|
||
1 year ago
|
(List[ultralytics.engine.results.Results]): The prediction results.
|
||
2 years ago
|
"""
|
||
2 years ago
|
if source is None:
|
||
|
source = ROOT / 'assets' if is_git_dir() else 'https://ultralytics.com/images/bus.jpg'
|
||
|
LOGGER.warning(f"WARNING ⚠️ 'source' is missing. Using 'source={source}'.")
|
||
2 years ago
|
is_cli = (sys.argv[0].endswith('yolo') or sys.argv[0].endswith('ultralytics')) and any(
|
||
|
x in sys.argv for x in ('predict', 'track', 'mode=predict', 'mode=track'))
|
||
2 years ago
|
overrides = self.overrides.copy()
|
||
2 years ago
|
overrides['conf'] = 0.25
|
||
2 years ago
|
overrides.update(kwargs) # prefer kwargs
|
||
2 years ago
|
overrides['mode'] = kwargs.get('mode', 'predict')
|
||
|
assert overrides['mode'] in ['track', 'predict']
|
||
2 years ago
|
if not is_cli:
|
||
|
overrides['save'] = kwargs.get('save', False) # do not save by default if called in Python
|
||
2 years ago
|
if not self.predictor:
|
||
2 years ago
|
self.task = overrides.get('task') or self.task
|
||
2 years ago
|
self.predictor = TASK_MAP[self.task][3](overrides=overrides, _callbacks=self.callbacks)
|
||
2 years ago
|
self.predictor.setup_model(model=self.model, verbose=is_cli)
|
||
2 years ago
|
else: # only update args if predictor is already setup
|
||
2 years ago
|
self.predictor.args = get_cfg(self.predictor.args, overrides)
|
||
1 year ago
|
if 'project' in overrides or 'name' in overrides:
|
||
|
self.predictor.save_dir = self.predictor.get_save_dir()
|
||
2 years ago
|
return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)
|
||
2 years ago
|
|
||
2 years ago
|
def track(self, source=None, stream=False, persist=False, **kwargs):
|
||
|
"""
|
||
|
Perform object tracking on the input source using the registered trackers.
|
||
|
|
||
|
Args:
|
||
|
source (str, optional): The input source for object tracking. Can be a file path or a video stream.
|
||
|
stream (bool, optional): Whether the input source is a video stream. Defaults to False.
|
||
|
persist (bool, optional): Whether to persist the trackers if they already exist. Defaults to False.
|
||
2 years ago
|
**kwargs (optional): Additional keyword arguments for the tracking process.
|
||
2 years ago
|
|
||
|
Returns:
|
||
1 year ago
|
(List[ultralytics.engine.results.Results]): The tracking results.
|
||
2 years ago
|
|
||
|
"""
|
||
2 years ago
|
if not hasattr(self.predictor, 'trackers'):
|
||
1 year ago
|
from ultralytics.trackers import register_tracker
|
||
2 years ago
|
register_tracker(self, persist)
|
||
2 years ago
|
# ByteTrack-based method needs low confidence predictions as input
|
||
2 years ago
|
conf = kwargs.get('conf') or 0.1
|
||
2 years ago
|
kwargs['conf'] = conf
|
||
|
kwargs['mode'] = 'track'
|
||
|
return self.predict(source=source, stream=stream, **kwargs)
|
||
|
|
||
2 years ago
|
@smart_inference_mode()
|
||
2 years ago
|
def val(self, data=None, **kwargs):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Validate a model on a given dataset.
|
||
2 years ago
|
|
||
|
Args:
|
||
2 years ago
|
data (str): The dataset to validate on. Accepts all formats accepted by yolo
|
||
|
**kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs
|
||
2 years ago
|
"""
|
||
2 years ago
|
overrides = self.overrides.copy()
|
||
2 years ago
|
overrides['rect'] = True # rect batches as default
|
||
2 years ago
|
overrides.update(kwargs)
|
||
2 years ago
|
overrides['mode'] = 'val'
|
||
2 years ago
|
args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)
|
||
2 years ago
|
args.data = data or args.data
|
||
2 years ago
|
if 'task' in overrides:
|
||
|
self.task = args.task
|
||
|
else:
|
||
|
args.task = self.task
|
||
2 years ago
|
if args.imgsz == DEFAULT_CFG.imgsz and not isinstance(self.model, (str, Path)):
|
||
2 years ago
|
args.imgsz = self.model.args['imgsz'] # use trained imgsz unless custom value is passed
|
||
2 years ago
|
args.imgsz = check_imgsz(args.imgsz, max_dim=1)
|
||
2 years ago
|
|
||
2 years ago
|
validator = TASK_MAP[self.task][2](args=args, _callbacks=self.callbacks)
|
||
2 years ago
|
validator(model=self.model)
|
||
2 years ago
|
self.metrics = validator.metrics
|
||
2 years ago
|
|
||
2 years ago
|
return validator.metrics
|
||
2 years ago
|
|
||
2 years ago
|
@smart_inference_mode()
|
||
|
def benchmark(self, **kwargs):
|
||
|
"""
|
||
|
Benchmark a model on all export formats.
|
||
|
|
||
|
Args:
|
||
|
**kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs
|
||
|
"""
|
||
2 years ago
|
self._check_is_pytorch_model()
|
||
1 year ago
|
from ultralytics.utils.benchmarks import benchmark
|
||
2 years ago
|
overrides = self.model.args.copy()
|
||
|
overrides.update(kwargs)
|
||
2 years ago
|
overrides['mode'] = 'benchmark'
|
||
2 years ago
|
overrides = {**DEFAULT_CFG_DICT, **overrides} # fill in missing overrides keys with defaults
|
||
2 years ago
|
return benchmark(model=self, imgsz=overrides['imgsz'], half=overrides['half'], device=overrides['device'])
|
||
2 years ago
|
|
||
2 years ago
|
def export(self, **kwargs):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Export model.
|
||
2 years ago
|
|
||
|
Args:
|
||
2 years ago
|
**kwargs : Any other args accepted by the predictors. To see all args check 'configuration' section in docs
|
||
2 years ago
|
"""
|
||
2 years ago
|
self._check_is_pytorch_model()
|
||
2 years ago
|
overrides = self.overrides.copy()
|
||
|
overrides.update(kwargs)
|
||
2 years ago
|
overrides['mode'] = 'export'
|
||
2 years ago
|
if overrides.get('imgsz') is None:
|
||
|
overrides['imgsz'] = self.model.args['imgsz'] # use trained imgsz unless custom value is passed
|
||
1 year ago
|
if 'batch' not in kwargs:
|
||
2 years ago
|
overrides['batch'] = 1 # default to 1 if not modified
|
||
2 years ago
|
args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)
|
||
2 years ago
|
args.task = self.task
|
||
2 years ago
|
return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model)
|
||
2 years ago
|
|
||
2 years ago
|
def train(self, **kwargs):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Trains the model on a given dataset.
|
||
2 years ago
|
|
||
|
Args:
|
||
2 years ago
|
**kwargs (Any): Any number of arguments representing the training configuration.
|
||
2 years ago
|
"""
|
||
2 years ago
|
self._check_is_pytorch_model()
|
||
2 years ago
|
if self.session: # Ultralytics HUB session
|
||
|
if any(kwargs):
|
||
|
LOGGER.warning('WARNING ⚠️ using HUB training arguments, ignoring local training arguments.')
|
||
|
kwargs = self.session.train_args
|
||
2 years ago
|
check_pip_update_available()
|
||
2 years ago
|
overrides = self.overrides.copy()
|
||
2 years ago
|
if kwargs.get('cfg'):
|
||
2 years ago
|
LOGGER.info(f"cfg file passed. Overriding default params with {kwargs['cfg']}.")
|
||
2 years ago
|
overrides = yaml_load(check_yaml(kwargs['cfg']))
|
||
2 years ago
|
overrides.update(kwargs)
|
||
2 years ago
|
overrides['mode'] = 'train'
|
||
|
if not overrides.get('data'):
|
||
2 years ago
|
raise AttributeError("Dataset required but missing, i.e. pass 'data=coco128.yaml'")
|
||
2 years ago
|
if overrides.get('resume'):
|
||
|
overrides['resume'] = self.ckpt_path
|
||
2 years ago
|
self.task = overrides.get('task') or self.task
|
||
2 years ago
|
self.trainer = TASK_MAP[self.task][1](overrides=overrides, _callbacks=self.callbacks)
|
||
2 years ago
|
if not overrides.get('resume'): # manually set model only if not resuming
|
||
2 years ago
|
self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)
|
||
2 years ago
|
self.model = self.trainer.model
|
||
2 years ago
|
self.trainer.hub_session = self.session # attach optional HUB session
|
||
2 years ago
|
self.trainer.train()
|
||
2 years ago
|
# Update model and cfg after training
|
||
2 years ago
|
if RANK in (-1, 0):
|
||
2 years ago
|
self.model, _ = attempt_load_one_weight(str(self.trainer.best))
|
||
|
self.overrides = self.model.args
|
||
2 years ago
|
self.metrics = getattr(self.trainer.validator, 'metrics', None) # TODO: no metrics returned by DDP
|
||
2 years ago
|
|
||
2 years ago
|
def to(self, device):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Sends the model to the given device.
|
||
2 years ago
|
|
||
|
Args:
|
||
|
device (str): device
|
||
|
"""
|
||
2 years ago
|
self._check_is_pytorch_model()
|
||
2 years ago
|
self.model.to(device)
|
||
|
|
||
1 year ago
|
def tune(self, *args, **kwargs):
|
||
2 years ago
|
"""
|
||
1 year ago
|
Runs hyperparameter tuning using Ray Tune. See ultralytics.utils.tuner.run_ray_tune for Args.
|
||
2 years ago
|
|
||
|
Returns:
|
||
2 years ago
|
(dict): A dictionary containing the results of the hyperparameter search.
|
||
2 years ago
|
|
||
|
Raises:
|
||
|
ModuleNotFoundError: If Ray Tune is not installed.
|
||
|
"""
|
||
1 year ago
|
self._check_is_pytorch_model()
|
||
1 year ago
|
from ultralytics.utils.tuner import run_ray_tune
|
||
1 year ago
|
return run_ray_tune(self, *args, **kwargs)
|
||
2 years ago
|
|
||
2 years ago
|
@property
|
||
|
def names(self):
|
||
2 years ago
|
"""Returns class names of the loaded model."""
|
||
2 years ago
|
return self.model.names if hasattr(self.model, 'names') else None
|
||
2 years ago
|
|
||
2 years ago
|
@property
|
||
|
def device(self):
|
||
2 years ago
|
"""Returns device if PyTorch model."""
|
||
2 years ago
|
return next(self.model.parameters()).device if isinstance(self.model, nn.Module) else None
|
||
|
|
||
2 years ago
|
@property
|
||
|
def transforms(self):
|
||
2 years ago
|
"""Returns transform of the loaded model."""
|
||
2 years ago
|
return self.model.transforms if hasattr(self.model, 'transforms') else None
|
||
|
|
||
2 years ago
|
def add_callback(self, event: str, func):
|
||
2 years ago
|
"""Add a callback."""
|
||
2 years ago
|
self.callbacks[event].append(func)
|
||
2 years ago
|
|
||
2 years ago
|
def clear_callback(self, event: str):
|
||
|
"""Clear all event callbacks."""
|
||
|
self.callbacks[event] = []
|
||
|
|
||
2 years ago
|
@staticmethod
|
||
|
def _reset_ckpt_args(args):
|
||
2 years ago
|
"""Reset arguments when loading a PyTorch model."""
|
||
2 years ago
|
include = {'imgsz', 'data', 'task', 'single_cls'} # only remember these arguments when loading a PyTorch model
|
||
|
return {k: v for k, v in args.items() if k in include}
|
||
2 years ago
|
|
||
2 years ago
|
def _reset_callbacks(self):
|
||
2 years ago
|
"""Reset all registered callbacks."""
|
||
2 years ago
|
for event in callbacks.default_callbacks.keys():
|
||
2 years ago
|
self.callbacks[event] = [callbacks.default_callbacks[event][0]]
|