跳至内容

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

备注

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



ultralytics.utils.callbacks.wb._custom_table(x, y, classes, title='Precision Recall Curve', x_title='Recall', y_title='Precision')

创建自定义度量可视化并记录到 wandb.plot.pr_curve 中。

该函数制作了一个自定义度量可视化图表,模仿 wandb 默认的精确度-调用曲线的行为,同时允许增强自定义功能。 曲线的行为,同时允许增强自定义。该可视化指标可用于监控不同类的模型性能。 不同类的模型性能。

参数

名称 类型 说明 默认值
x List

x 轴的值,预计长度为 N。

所需
y List

y 轴的对应值;预计长度也是 N。

所需
classes List

标识每个点类别的标签;长度 N。

所需
title str

图表标题;默认为 "精确度召回曲线"。

'Precision Recall Curve'
x_title str

x 轴的标签;默认为 "Recall"。

'Recall'
y_title str

Y 轴的标签;默认为 "精度"。

'Precision'

返回:

类型 说明
Object

适合记录日志的 wandb 对象,展示精心制作的指标可视化。

源代码 ultralytics/utils/callbacks/wb.py
def _custom_table(x, y, classes, title="Precision Recall Curve", x_title="Recall", y_title="Precision"):
    """
    Create and log a custom metric visualization to wandb.plot.pr_curve.

    This function crafts a custom metric visualization that mimics the behavior of wandb's default precision-recall
    curve while allowing for enhanced customization. The visual metric is useful for monitoring model performance across
    different classes.

    Args:
        x (List): Values for the x-axis; expected to have length N.
        y (List): Corresponding values for the y-axis; also expected to have length N.
        classes (List): Labels identifying the class of each point; length N.
        title (str, optional): Title for the plot; defaults to 'Precision Recall Curve'.
        x_title (str, optional): Label for the x-axis; defaults to 'Recall'.
        y_title (str, optional): Label for the y-axis; defaults to 'Precision'.

    Returns:
        (wandb.Object): A wandb object suitable for logging, showcasing the crafted metric visualization.
    """
    df = pd.DataFrame({"class": classes, "y": y, "x": x}).round(3)
    fields = {"x": "x", "y": "y", "class": "class"}
    string_fields = {"title": title, "x-axis-title": x_title, "y-axis-title": y_title}
    return wb.plot_table(
        "wandb/area-under-curve/v0", wb.Table(dataframe=df), fields=fields, string_fields=string_fields
    )



ultralytics.utils.callbacks.wb._plot_curve(x, y, names=None, id='precision-recall', title='Precision Recall Curve', x_title='Recall', y_title='Precision', num_x=100, only_mean=False)

记录可视化度量曲线

该函数根据输入数据生成一条度量曲线,并将可视化结果记录到 wandb 中。 根据 "only_mean "标志的不同,曲线可以表示汇总数据(平均值),也可以表示单个类别的数据。

参数

名称 类型 说明 默认值
x ndarray

长度为 N 的 x 轴数据点。

所需
y ndarray

y 轴上的相应数据点,其形状为 CxN,其中 C 为类别数。

所需
names list

与 Y 轴数据相对应的类别名称;长度为 C,默认为[]。

None
id str

wandb 中记录数据的唯一标识符。默认为 "precision-recall"。

'precision-recall'
title str

可视化图表的标题。默认为 "精确度召回曲线"。

'Precision Recall Curve'
x_title str

x 轴的标签。默认为 "Recall"。

'Recall'
y_title str

y 轴的标签。默认为 "精度"。

'Precision'
num_x int

用于可视化的内插数据点数。默认为 100。

100
only_mean bool

指示是否只绘制平均值曲线的标志。默认为 True。

False
备注

该函数利用"_custom_table "函数生成实际的可视化效果。

源代码 ultralytics/utils/callbacks/wb.py
def _plot_curve(
    x,
    y,
    names=None,
    id="precision-recall",
    title="Precision Recall Curve",
    x_title="Recall",
    y_title="Precision",
    num_x=100,
    only_mean=False,
):
    """
    Log a metric curve visualization.

    This function generates a metric curve based on input data and logs the visualization to wandb.
    The curve can represent aggregated data (mean) or individual class data, depending on the 'only_mean' flag.

    Args:
        x (np.ndarray): Data points for the x-axis with length N.
        y (np.ndarray): Corresponding data points for the y-axis with shape CxN, where C is the number of classes.
        names (list, optional): Names of the classes corresponding to the y-axis data; length C. Defaults to [].
        id (str, optional): Unique identifier for the logged data in wandb. Defaults to 'precision-recall'.
        title (str, optional): Title for the visualization plot. Defaults to 'Precision Recall Curve'.
        x_title (str, optional): Label for the x-axis. Defaults to 'Recall'.
        y_title (str, optional): Label for the y-axis. Defaults to 'Precision'.
        num_x (int, optional): Number of interpolated data points for visualization. Defaults to 100.
        only_mean (bool, optional): Flag to indicate if only the mean curve should be plotted. Defaults to True.

    Note:
        The function leverages the '_custom_table' function to generate the actual visualization.
    """
    # Create new x
    if names is None:
        names = []
    x_new = np.linspace(x[0], x[-1], num_x).round(5)

    # Create arrays for logging
    x_log = x_new.tolist()
    y_log = np.interp(x_new, x, np.mean(y, axis=0)).round(3).tolist()

    if only_mean:
        table = wb.Table(data=list(zip(x_log, y_log)), columns=[x_title, y_title])
        wb.run.log({title: wb.plot.line(table, x_title, y_title, title=title)})
    else:
        classes = ["mean"] * len(x_log)
        for i, yi in enumerate(y):
            x_log.extend(x_new)  # add new x
            y_log.extend(np.interp(x_new, x, yi))  # interpolate y to new x
            classes.extend([names[i]] * len(x_new))  # add class names
        wb.log({id: _custom_table(x_log, y_log, classes, title, x_title, y_title)}, commit=False)



ultralytics.utils.callbacks.wb._log_plots(plots, step)

如果在指定步骤中尚未记录输入字典中的图形,则记录这些图形。

源代码 ultralytics/utils/callbacks/wb.py
def _log_plots(plots, step):
    """Logs plots from the input dictionary if they haven't been logged already at the specified step."""
    for name, params in plots.items():
        timestamp = params["timestamp"]
        if _processed_plots.get(name) != timestamp:
            wb.run.log({name.stem: wb.Image(str(name))}, step=step)
            _processed_plots[name] = timestamp



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

如果存在模块,则启动并开始项目。

源代码 ultralytics/utils/callbacks/wb.py
def on_pretrain_routine_start(trainer):
    """Initiate and start project if module is present."""
    wb.run or wb.init(project=trainer.args.project or "YOLOv8", name=trainer.args.name, config=vars(trainer.args))



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

在一个历时结束时记录训练指标和模型信息。

源代码 ultralytics/utils/callbacks/wb.py
def on_fit_epoch_end(trainer):
    """Logs training metrics and model information at the end of an epoch."""
    wb.run.log(trainer.metrics, step=trainer.epoch + 1)
    _log_plots(trainer.plots, step=trainer.epoch + 1)
    _log_plots(trainer.validator.plots, step=trainer.epoch + 1)
    if trainer.epoch == 0:
        wb.run.log(model_info_for_loggers(trainer), step=trainer.epoch + 1)



ultralytics.utils.callbacks.wb.on_train_epoch_end(trainer)

在每次训练结束时记录指标并保存图像。

源代码 ultralytics/utils/callbacks/wb.py
def on_train_epoch_end(trainer):
    """Log metrics and save images at the end of each training epoch."""
    wb.run.log(trainer.label_loss_items(trainer.tloss, prefix="train"), step=trainer.epoch + 1)
    wb.run.log(trainer.lr, step=trainer.epoch + 1)
    if trainer.epoch == 1:
        _log_plots(trainer.plots, step=trainer.epoch + 1)



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

在训练结束时,将最佳模型保存为人工制品。

源代码 ultralytics/utils/callbacks/wb.py
def on_train_end(trainer):
    """Save the best model as an artifact at end of training."""
    _log_plots(trainer.validator.plots, step=trainer.epoch + 1)
    _log_plots(trainer.plots, step=trainer.epoch + 1)
    art = wb.Artifact(type="model", name=f"run_{wb.run.id}_model")
    if trainer.best.exists():
        art.add_file(trainer.best)
        wb.run.log_artifact(art, aliases=["best"])
    for curve_name, curve_values in zip(trainer.validator.metrics.curves, trainer.validator.metrics.curves_results):
        x, y, x_title, y_title = curve_values
        _plot_curve(
            x,
            y,
            names=list(trainer.validator.metrics.names.values()),
            id=f"curves/{curve_name}",
            title=curve_name,
            x_title=x_title,
            y_title=y_title,
        )
    wb.run.finish()  # required or run continues on dashboard





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