跳至内容

参考资料 ultralytics/utils/callbacks/dvc.py

备注

该文件可从https://github.com/ultralytics/ultralytics/blob/main/ ultralytics/utils/callbacks/dvc .py 获取。如果您发现问题,请通过提交 Pull Request🛠️ 帮助修复。谢谢🙏!



ultralytics.utils.callbacks.dvc._log_images(path, prefix='')

使用 DVCLive 在指定路径下记录图像,可选前缀。

源代码 ultralytics/utils/callbacks/dvc.py
def _log_images(path, prefix=""):
    """Logs images at specified path with an optional prefix using DVCLive."""
    if live:
        name = path.name

        # Group images by batch to enable sliders in UI
        if m := re.search(r"_batch(\d+)", name):
            ni = m[1]
            new_stem = re.sub(r"_batch(\d+)", "_batch", path.stem)
            name = (Path(new_stem) / ni).with_suffix(path.suffix)

        live.log_image(os.path.join(prefix, name), path)



ultralytics.utils.callbacks.dvc._log_plots(plots, prefix='')

如果之前未对图像进行处理,则记录绘图图像的训练进度。

源代码 ultralytics/utils/callbacks/dvc.py
def _log_plots(plots, prefix=""):
    """Logs plot images for training progress if they have not been previously processed."""
    for name, params in plots.items():
        timestamp = params["timestamp"]
        if _processed_plots.get(name) != timestamp:
            _log_images(name, prefix)
            _processed_plots[name] = timestamp



ultralytics.utils.callbacks.dvc._log_confusion_matrix(validator)

使用 DVCLive 记录给定验证器的混淆矩阵。

源代码 ultralytics/utils/callbacks/dvc.py
def _log_confusion_matrix(validator):
    """Logs the confusion matrix for the given validator using DVCLive."""
    targets = []
    preds = []
    matrix = validator.confusion_matrix.matrix
    names = list(validator.names.values())
    if validator.confusion_matrix.task == "detect":
        names += ["background"]

    for ti, pred in enumerate(matrix.T.astype(int)):
        for pi, num in enumerate(pred):
            targets.extend([names[ti]] * num)
            preds.extend([names[pi]] * num)

    live.log_sklearn_plot("confusion_matrix", targets, preds, name="cf.json", normalized=True)



ultralytics.utils.callbacks.dvc.on_pretrain_routine_start(trainer)

在训练前例行程序中为训练元数据初始化 DVCLive 记录器。

源代码 ultralytics/utils/callbacks/dvc.py
def on_pretrain_routine_start(trainer):
    """Initializes DVCLive logger for training metadata during pre-training routine."""
    try:
        global live
        live = dvclive.Live(save_dvc_exp=True, cache_images=True)
        LOGGER.info("DVCLive is detected and auto logging is enabled (run 'yolo settings dvc=False' to disable).")
    except Exception as e:
        LOGGER.warning(f"WARNING ⚠️ DVCLive installed but not initialized correctly, not logging this run. {e}")



ultralytics.utils.callbacks.dvc.on_pretrain_routine_end(trainer)

在预训练结束时,记录与训练过程有关的情节。

源代码 ultralytics/utils/callbacks/dvc.py
def on_pretrain_routine_end(trainer):
    """Logs plots related to the training process at the end of the pretraining routine."""
    _log_plots(trainer.plots, "train")



ultralytics.utils.callbacks.dvc.on_train_start(trainer)

如果 DVCLive 日志处于激活状态,则记录训练参数。

源代码 ultralytics/utils/callbacks/dvc.py
def on_train_start(trainer):
    """Logs the training parameters if DVCLive logging is active."""
    if live:
        live.log_params(trainer.args)



ultralytics.utils.callbacks.dvc.on_train_epoch_start(trainer)

在每次训练开始时,将全局变量 _training_epoch 设置为 True。

源代码 ultralytics/utils/callbacks/dvc.py
def on_train_epoch_start(trainer):
    """Sets the global variable _training_epoch value to True at the start of training each epoch."""
    global _training_epoch
    _training_epoch = True



ultralytics.utils.callbacks.dvc.on_fit_epoch_end(trainer)

记录训练指标和模型信息,并在每个拟合历元结束时进入下一步。

源代码 ultralytics/utils/callbacks/dvc.py
def on_fit_epoch_end(trainer):
    """Logs training metrics and model info, and advances to next step on the end of each fit epoch."""
    global _training_epoch
    if live and _training_epoch:
        all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr}
        for metric, value in all_metrics.items():
            live.log_metric(metric, value)

        if trainer.epoch == 0:
            from ultralytics.utils.torch_utils import model_info_for_loggers

            for metric, value in model_info_for_loggers(trainer).items():
                live.log_metric(metric, value, plot=False)

        _log_plots(trainer.plots, "train")
        _log_plots(trainer.validator.plots, "val")

        live.next_step()
        _training_epoch = False



ultralytics.utils.callbacks.dvc.on_train_end(trainer)

如果 DVCLive 处于激活状态,则在训练结束时记录最佳指标、绘图和混淆矩阵。

源代码 ultralytics/utils/callbacks/dvc.py
def on_train_end(trainer):
    """Logs the best metrics, plots, and confusion matrix at the end of training if DVCLive is active."""
    if live:
        # At the end log the best metrics. It runs validator on the best model internally.
        all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr}
        for metric, value in all_metrics.items():
            live.log_metric(metric, value, plot=False)

        _log_plots(trainer.plots, "val")
        _log_plots(trainer.validator.plots, "val")
        _log_confusion_matrix(trainer.validator)

        if trainer.best.exists():
            live.log_artifact(trainer.best, copy=True, type="model")

        live.end()





创建于 2023-11-12,更新于 2023-11-25
作者:glenn-jocher(3),Laughing-q(1)