开始使用

使用 Ultralytics YOLO 训练模型

Ultralytics YOLO ecosystem and integrations

简介#

训练深度学习模型时,需要向模型输入数据并调整其参数,使其能够做出准确预测。Ultralytics YOLO26 的 Train 模式可在现代硬件上高效训练对象检测及其他视觉任务模型。本指南介绍如何开始使用 YOLO26训练你自己的模型。如果你还没有安装 Ultralytics,请先查看快速入门指南。

查看尚未发布的 YOLO27 预览版,了解计划中的训练示例。



观看: 如何在 Google Colab 中使用自定义数据集训练 YOLO 模型。

为什么选择 Ultralytics YOLO 进行训练?#

使用 YOLO26 Train 模式的理由:

  • 效率:充分利用硬件资源,无论你使用的是单 GPU 配置,还是扩展到多 GPU。
  • 多功能性:除了使用现成的数据集,还可以在自定义数据集上训练,例如 COCO、VOC 和 ImageNet。
  • 易于使用:提供简单而强大的 CLI 和 Python 接口,让训练过程更加顺畅。
  • 超参数灵活性:提供丰富的可自定义超参数,用于微调模型性能。如需更精细的控制,你还可以自定义训练器。
  • 云端训练:通过 Ultralytics Platform 使用云 GPU 进行训练,并实时查看指标和自动保存检查点。

训练模式的主要功能#

以下是 YOLO26 训练模式的一些主要功能:

  • 自动下载数据集:首次使用时,会自动下载配置中指定了下载源的数据集,例如 yolo train data=coco8.yaml。有关支持的格式和数据集,请参阅数据集概览。
  • 多 GPU 支持:通过在多个 GPU 上扩展训练来缩短训练时间。
  • 超参数配置:可以通过 YAML 配置文件或 CLI 参数修改超参数。
  • 可视化与监控:实时跟踪训练指标并可视化学习过程,以便更好地了解训练情况。

使用示例#

在 COCO8 数据集上训练 YOLO26n,训练 100 个轮次,图像尺寸为 640。可以使用 device 参数指定训练设备。如果未传入参数,则在可用时使用 GPU device=0;否则使用 device='cpu'。

Windows 多进程错误

在 Windows 上以脚本方式启动训练时,可能会收到 RuntimeError。在训练代码前添加 if __name__ == "__main__": 块即可解决此问题。

单 GPU 和 CPU 训练示例

设备会自动确定。如果有可用 GPU,就会使用该 GPU(默认 CUDA 设备 0);否则将在 CPU 上开始训练。

from ultralytics import YOLO

# 加载模型
model = YOLO("yolo26n.yaml")  # 从 YAML 构建新模型
model = YOLO("yolo26n.pt")  # 加载预训练模型(推荐用于训练)
model = YOLO("yolo26n.yaml").load("yolo26n.pt")  # 从 YAML 构建模型并迁移权重

# 训练模型
results = model.train(data="coco8.yaml", epochs=100, imgsz=640)

多 GPU 训练#

多 GPU 训练通过在多个 GPU 之间分配训练负载,更充分地利用可用硬件。此功能可通过 Python API 和命令行界面使用。要启用多 GPU 训练,请指定要使用的 GPU 设备 ID。

多 GPU 训练示例

要使用 2 个 GPU(CUDA 设备 0 和 1)进行训练,请使用以下命令。根据需要扩展到更多 GPU。

from ultralytics import YOLO

# 加载模型
model = YOLO("yolo26n.pt")  # 加载预训练模型(推荐用于训练)

# 使用 2 块 GPU 训练模型
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device=[0, 1])

# 使用当前最空闲的两块 GPU 训练模型
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device=[-1, -1])
Windows 多 GPU 支持

在 Windows 上,使用官方 PyTorch wheel 的 torch>=2.4 无法进行多 GPU 训练。Ultralytics 通过 torch.distributed.run 启动 DDP,其会合步骤会构建一个 TCPStore;自 PyTorch 2.4 起,该对象默认使用 libuv 后端,而官方 Windows wheel 编译时未包含 libuv。训练会立即退出,并显示:

RuntimeError: use_libuv was requested but PyTorch was built without libuv support

设置 USE_LIBUV=0 无法解决此问题,因为会合过程会直接构建 TCPStore,而该代码路径不会读取此变量。要使用多块 GPU,请在 Linux 或 WSL2 上训练;或者在 Windows 上使用 device=0 进行单 GPU 训练。

使用自定义代码进行多 GPU 训练

指定多个设备(例如 device=[0, 1])时,Ultralytics 会在内部启动一个新的训练器实例,并在后台执行 torch.distributed.run。这适用于标准 CLI 用法和未经修改的 Python 脚本。

但是,如果脚本包含自定义组件(例如自定义训练器、验证器、数据集或数据增强流程),这些对象就无法自动序列化并传递给 DDP 子进程。在这种情况下,你必须直接使用 torch.distributed.run 启动脚本:

python -m torch.distributed.run --nproc_per_node 2 your_training_script.py

AMD GPU 训练使用 PyTorch ROCm 构建版本,并采用标准的 device=0 或 device=cuda:0 语法。有关 ROCm 安装、多 GPU 训练、AMP 注意事项以及导出模型的 MIGraphX 推理,请参阅 AMD 集成指南。

Intel GPU 训练使用 device=xpu:0,也可以使用提供 XCCL 的 PyTorch 构建版本指定多个 XPU ID。

华为昇腾 NPU 训练#

Ultralytics 通过 torch_npu 支持在华为昇腾 NPU 上进行训练和验证。请按照适用于 PyTorch 的昇腾扩展安装指南安装相互兼容的 CANN、PyTorch 和 torch_npu 版本,然后在启动 Ultralytics 前加载 CANN 环境:

source /usr/local/Ascend/ascend-toolkit/set_env.sh
昇腾 NPU 训练示例
from ultralytics import YOLO

model = YOLO("yolo26n.pt")

# 在一块昇腾 NPU 上训练
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device="npu:0")

# 使用 HCCL 在两块昇腾 NPU 上训练
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device="npu:0,1")

包括 AMP、验证、检查点保存和恢复训练在内的标准训练功能均使用当前启用的 NPU。单 NPU 训练支持 AutoBatch;多个 NPU ID 则会通过 HCCL 启动分布式训练。有关训练后模型导出和部署的信息,请参阅华为昇腾集成指南。

使用空闲 GPU 训练#

空闲 GPU 训练会在多 GPU 系统中自动选择利用率最低的 GPU,因此你无需手动挑选设备。它会根据利用率和可用 VRAM 对可用 GPU 排序。

使用空闲 GPU 训练示例

要自动选择并使用最空闲的 GPU 进行训练,请使用 -1 设备参数。这在共享计算环境或多用户服务器中特别有用。

from ultralytics import YOLO

# 加载模型
model = YOLO("yolo26n.pt")  # 加载预训练模型(推荐用于训练)

# 使用当前最空闲的一块 GPU 进行训练
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device=-1)

# 使用当前最空闲的两块 GPU 进行训练
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device=[-1, -1])

自动选择算法会优先选择具有以下特征的 GPU:

  1. 当前利用率较低
  2. 可用内存较多(空闲 VRAM 较大)

这在共享计算环境或同时运行多个训练任务时尤其有用,因为每次运行启动时,系统都会根据当前情况选择设备。

Apple Silicon MPS 训练#

Ultralytics YOLO 模型可以通过 Metal Performance Shaders (MPS) 框架在 Apple 芯片上训练,该框架使用 Apple 定制的 GPU 执行计算和图像处理任务。

要在 Apple 芯片上训练,请在 Python 或命令行启动训练时将 mps 指定为设备:

MPS 训练示例
from ultralytics import YOLO

# 加载模型
model = YOLO("yolo26n.pt")  # 加载预训练模型(推荐用于训练)

# 使用 MPS 训练模型
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device="mps")

恢复中断的训练#

如果训练意外中断,或者你想使用新数据或增加训练轮次继续训练模型,从已保存的检查点恢复训练会很有用。

恢复训练时,Ultralytics YOLO 会加载上次保存模型的权重,并恢复优化器状态、学习率调度器、轮次编号和数据集。随后训练会从中断处继续。若要改用其他数据集而非检查点中的数据集,请同时传入明确的 data= 和 resume。

在 Ultralytics YOLO 中恢复训练时,调用 train 方法时将 resume 参数设为 True,并指定包含部分训练模型权重的 .pt 文件路径。

要在 Python 或命令行中恢复已中断的训练:

恢复训练示例
from ultralytics import YOLO

# 加载模型
model = YOLO("path/to/last.pt")  # 加载部分训练过的模型

# 恢复训练
results = model.train(resume=True)

设置 resume=True 后,train 函数会使用 path/to/last.pt 文件中存储的状态,从中断处继续训练。如果省略 resume 参数或将其设为 False,train 函数就会启动新的训练会话。恢复运行时,若训练数据流式传输到 Ultralytics Platform,则会继续使用同一个 Platform 模型。

请注意,检查点默认在每轮训练结束时保存,也可以通过 save_period 参数按固定间隔保存,因此至少必须完成 1 轮训练才能恢复训练。

训练设置#

YOLO 模型的训练设置包括训练过程中使用的各种超参数和配置。这些设置会影响模型的性能、速度和准确性。关键训练设置包括批次大小、学习率、动量和权重衰减。此外,优化器、损失函数以及训练数据集的组成也会影响训练过程。仔细调整并试验这些设置,是优化性能的关键。

MuSGD 优化器#

在 YOLO26 中,MuSGD 是一种混合优化器,结合了标准的 SGD 更新和 Muon 风格的正交化更新。

对于较长的 YOLO26 训练任务和较大的数据集,建议使用该优化器;正交化的 Muon 更新有助于稳定优化过程。

只有二维线性权重和四维卷积滤波器(重塑为二维后)会与 SGD 一起接受 Muon 风格的更新;其他所有参数(例如批归一化权重和偏置项)仍使用标准 SGD。

使用 optimizer=auto 时,Ultralytics 会自动为较长的训练任务选择 MuSGD(通常是迭代次数 > 10000)。对于较短的训练任务,训练器会改用 AdamW。在 auto 模式下,训练器也会选择学习率,因此用户提供的 lr0 会被忽略。若要手动控制这些设置,请明确选择优化器,例如 optimizer=AdamW lr0=0.001。

用法示例:

yolo train model=yolo26n.pt data=coco8.yaml optimizer=MuSGD

请参阅 ultralytics/optim/muon.py 中的实现,以及 BaseTrainer.build_optimizer 中的优化器自动选择逻辑。

参数类型默认值说明
modelstrNone指定用于训练的模型文件。接受指向.pt预训练模型或.yaml配置文件的路径。这是定义模型结构或初始化权重的必要设置。
datastrNone数据集 YAML 文件的路径(例如 coco8.yaml),其中包含训练和验证数据的路径、类别名称和类别数量。分类任务则使用数据集目录或内置数据集名称(例如 imagenet10)。
epochsint100训练总轮数。每个轮次都表示完整遍历整个数据集一次。调整此值会影响训练时长和模型性能。
timefloatNone最长训练时间(小时)。如果设置此项,它会覆盖epochs参数,让训练在达到指定时长后自动停止。适用于训练时间受限的情况。
patienceint100验证指标未改善时,等待多少轮后提前停止训练。性能趋于平稳时停止训练,有助于防止过拟合。
batchint 或 float16批次大小有三种模式:设为整数(例如 batch=16)、自动模式(使用可用 GPU 内存的 60%,batch=-1),或自动模式(使用指定比例的可用 GPU 内存,batch=0.70)。
imgszint640训练时的目标图像尺寸。图像会被缩放为边长等于指定值的正方形(如果是rect=False),YOLO 模型会保持宽高比,但 RT-DETR 不会。这会影响模型准确率和计算复杂度。
saveboolTrue启用训练检查点和最终模型权重的保存功能。适用于恢复训练或模型部署。
save_periodint-1保存模型检查点的频率,以轮数指定。值为 -1 时会禁用此功能。适合在长时间训练过程中保存中间模型。
cachebool 或 strFalse启用数据集图像缓存:缓存到内存(True/ram)、磁盘(disk),或禁用缓存(False)。通过减少磁盘 I/O 提高训练速度,但会增加内存使用量。
tilebool 或 intFalse将每张源图像扩展为固定大小的训练切片,并裁剪标签、保留负样本窗口。True 使用 imgsz;正整数用于设置切片大小。参见 高分辨率切片。
deviceint 或 str 或 listNone指定训练使用的计算设备:单个 GPU(device=0)、多个 GPU(device=[0,1])、CPU(device=cpu)、Apple 芯片上的 MPS(device=mps)、华为昇腾 NPU(device=npu:0 或 device=npu:0,1)、Intel XPU(device=xpu:0)、自动选择空闲 GPU(device=-1)或多个空闲 GPU(device=[-1,-1])。
workersint8用于数据加载的工作线程数(多 GPU 训练时为每个RANK配置)。此设置会影响数据预处理和输入模型的速度,在多 GPU 配置中尤其有用。
projectstrNone保存训练输出的项目目录名称。相对路径会置于 runs_dir/<task> 下,绝对路径则按原样使用。
namestrNone训练运行名称。用于在项目文件夹中创建子目录,以存储训练日志和输出。
exist_okboolFalse如果为 True,则允许覆盖已有的项目/名称目录。适用于迭代实验,无需手动清理之前的输出。
save_dirstrNone指定保存运行输出的确切目录,覆盖project/name组合。路径会按原样使用,不会自动递增,因此连续运行会复用同一目录。
pretrainedbool 或 strTrue指定是否从预训练权重开始训练。可以是布尔值,也可以是要加载的权重文件路径字符串。pretrained=False会使用随机初始化的权重训练,同时保留模型架构。
cls_remapboolTrue跨数据集微调时,只要类别名称匹配,就会将预训练分类头的行复制到新模型中,让重叠类别保留已学习的偏置;如果分类头宽度不变,也会保留权重。无论类别数量是否相同,或类别顺序是否不同,都会应用此设置。
optimizerstr'auto'选择训练使用的优化器。选项包括 SGD、MuSGD、Adam、Adamax、AdamW、NAdam、RAdam、RMSProp 或 auto,可根据训练迭代次数选择 AdamW 或 MuSGD。这会影响收敛速度和稳定性。
seedint0设置训练的随机种子,确保使用相同配置进行多次运行时结果可复现。
deterministicboolTrue强制使用确定性算法,确保结果可复现;但由于限制使用非确定性算法,可能会影响性能和速度。
verboseboolTrue启用训练过程中的详细输出,在控制台显示进度条、每轮指标及其他训练信息。
single_clsboolFalse训练时将多类别数据集中的所有类别视为一个类别。适用于二分类任务,或关注对象是否存在而非类别的情况。
classeslist[int]None指定要参与训练的类别 ID 列表。适用于筛选并仅关注训练中的特定类别。
rectboolFalse启用最小填充策略——批次中的图像只进行最少填充,以达到统一尺寸,且最长边等于 imgsz。这可以提升效率和速度,但可能影响模型精度。无论此设置如何,标准 YOLO 训练器在检测、分割、姿态和 OBB 验证中都会使用 rect=True。
multi_scalefloat0.0每个批次随机调整imgsz,变化范围为 +/- multi_scale(例如,0.25 -> 0.75x 到 1.25x),并四舍五入到模型步幅的倍数;0.0会禁用多尺度训练。
cos_lrboolFalse使用余弦学习率调度器,在各轮训练中按余弦曲线调整学习率。这有助于管理学习率,从而更好地收敛。
close_mosaicint10在最后 N 轮训练中禁用马赛克数据增强,以便在训练结束前稳定模型。设为 0 可禁用此功能。
resumeboolFalse从上次保存的检查点恢复训练。自动加载模型权重、优化器状态和 epoch 计数,并从中断处继续训练。
ampbool 或 strTrue设置训练精度:True 或 "fp16" 使用 FP16,"bf16" 在支持的 CUDA 设备上使用 BF16,False 或 "fp32" 使用 FP32。
quantizeint 或 strNone设为8(或"int8")以启用 INT8 量化感知训练(QAT)。该训练会在循环中进行伪量化微调,使权重能够适应 INT8 导出。请参阅量化感知训练。
fractionfloat、int 或 list1.0数据集子集,可按比例/数量或[train, val, test]列表指定。1表示完整划分;大于1的整数表示图像数量;只有可选的 test 项接受0/0.0来表示无测试集。包含两项的列表会保留完整测试集。
profileboolFalse启用训练期间对 ONNX 和 TensorRT 速度的性能分析,适用于优化模型部署。
freezeint 或 listNone冻结模型的前 N 层,或按索引或模块名称冻结指定层(23.cv2,不带前导model.),以减少可训练参数数量。适用于微调或迁移学习。
lr0float0.01初始学习率(例如 SGD=1E-2、Adam=1E-3)。使用默认的 optimizer='auto' 时会忽略此项;若要使用该值,请明确指定优化器名称。
lrffloat0.01最终学习率与初始学习率的比值 = (lr0 * lrf),与调度器配合使用,以便随时间调整学习率。
momentumfloat0.937SGD/MuSGD 的动量,或 Adam 优化器的 beta1。使用 optimizer=auto 时,AdamW 使用 0.9;MuSGD 从 0.9 开始,然后预热会在 warmup_momentum 和 momentum 之间进行插值。不进行预热时,自动 MuSGD 保持在 0.9。
weight_decayfloat0.0005L2 正则化项,用于惩罚较大的权重以防止过拟合。
warmup_epochsfloat3.0预热轮数(允许小数),并设置上限以确保最后一个 epoch 不进行预热。学习率从 0(偏置项来自 warmup_bias_lr)线性上升到计划值,动量从 warmup_momentum 线性上升到 momentum,梯度累积则从 1 个批次增加到标称值(参见 nbs);所有参数都会在预热结束时达到目标值。
warmup_momentumfloat0.8对于带有动量项的优化器(SGD、MuSGD、RMSprop),这是起始动量,并会在预热结束时线性升至 momentum。Adam 系列优化器的 beta1 不参与预热。
warmup_bias_lrfloat0.1预热阶段偏置参数的学习率,有助于稳定训练初期的模型。使用默认optimizer='auto'时会自动设为0.0;要使用此设置,请明确指定优化器。
distill_modelstrNone用于知识蒸馏的教师模型检查点路径(例如 yolo26x.pt)。设置后,学生模型会在冻结教师模型的指导下,通过额外的蒸馏损失进行训练。
disfloat6.0添加到标准检测损失中的蒸馏损失权重。值越大,教师模型特征指导的影响越大。
boxfloat7.5损失函数中边界框损失分量的权重,影响模型对准确预测边界框坐标的重视程度。
clsfloat0.5总损失函数中分类损失的权重,影响相对于其他分量而言正确类别预测的重要性。
cls_pwfloat0.0用于处理类别不平衡的类别权重指数,按类别频率的倒数加权。0.0会禁用类别加权,1.0会应用完整的逆频率加权。介于 0 和 1 之间的值可进行部分加权。
dflfloat1.5边界框距离回归项的权重:检测头使用reg_max > 1时为分布焦点损失(DFL);不使用 DFL 的 YOLO26(reg_max: 1)则采用归一化边界框距离的 L1 损失。
posefloat12.0姿态估计模型中姿态损失的权重,影响模型对准确预测姿态关键点的重视程度。
kobjfloat1.0姿态估计模型中关键点目标置信度损失的权重,用于平衡检测置信度与姿态准确率。
rlefloat1.0姿态估计模型中残差对数似然估计损失的权重,会影响关键点定位的精度。
anglefloat1.0OBB 模型中角度损失的权重,会影响有向边界框角度预测的精度。
dlogfloat1.0深度估计模型中尺度不变对数(SILog)损失的权重,是影响深度准确率的主要项。
dgradfloat0.5深度估计模型中梯度损失的权重,用于惩罚深度边缘误差并促使表面边界更加清晰。
dlamfloat1.0深度估计模型中 SILog 损失的方差聚焦因子。1.0会使损失完全具有尺度不变性,而0.0会将其简化为普通的对数 RMSE。
nbsint64标称批量大小。每次优化器更新前累积 round(nbs / batch) 个批次的梯度(至少为 1;除 time 模式外,不超过本次运行的批次数),并按 batch * accumulate / nbs 缩放 weight_decay 以使其匹配。
overlap_maskboolTrue确定训练时是否将所有对象掩码合并为单个掩码,或为每个对象分别保留掩码。合并时如果发生重叠,较小的掩码会叠加在较大的掩码之上。
mask_ratioint4分割掩码的下采样比例,会影响训练时所用掩码的分辨率,但不会改变预测掩码的分辨率。
dropoutfloat0.0分类任务中的正则化丢弃率,通过在训练期间随机丢弃单元来防止过拟合。
valboolTrue启用训练期间的验证,以便定期在单独的数据集上评估模型性能。
splitstr'val'训练期间用于验证的数据集划分:val、test 或 train。这些指标用于选择 best.pt 并触发提前停止。
nmsbool,可选None选择用于每轮验证、检查点选择和提前停止的推理头。None 或 True使用带 NMS 的一对多头;False在可用时使用无 NMS 头。两种头都会保留各自的训练损失。
plotsboolTrue生成并保存训练和验证指标图,以及预测示例,直观呈现模型性能和学习进度。
compilebool 或 strFalse使用backend='inductor'启用 PyTorch 2.x torch.compile图编译。接受True → "default"、False → 禁用,或"default"、"reduce-overhead"、"max-autotune-no-cudagraphs"等字符串模式。如果不受支持,则会发出警告并回退到即时执行模式。
channels_lastboolNone训练期间的卷积使用 channels_last (NHWC) 内存格式。None 会在 CUDA 和 PyTorch 1.11 或更高版本上自动启用该格式,但 Windows 和 AMD ROCm 除外,因为在这些环境中测得的速度较慢。False 会禁用该格式,而 True 会显式启用该格式。在 CPU 或 MPS 上训练时始终使用 NCHW(True 会被忽略,并显示警告)。
max_detint300训练验证期间每张图像的最大检测数量。对于 detect、segment、pose 和 OBB,默认值 300 仅在最大训练/验证标注对象数量超过 300 时才会增大到该数量。其他值保持不变;超出上限时会触发警告。
批次大小设置说明

batch 参数接受三种类型的值,训练器还会添加两项安全措施:

  • 固定批次大小:设置一个整数值(例如 batch=16),直接指定每个批次包含的图像数量。多 GPU 训练会将全局批次均匀分配到各个 GPU,因此批次大小必须至少等于 GPU 数量;余数会被舍弃(例如,在 2 个 GPU 上使用 batch=15 时,每个 GPU 会训练 7 张图像)。
  • 自动模式(60% GPU 内存):使用 batch=-1,自动调整批次大小,使训练使用的 CUDA 内存约为可用内存的 60%。
  • 使用内存占用比例的自动模式:设置一个比例值(例如 batch=0.70),根据指定的可用 GPU 内存比例调整批次大小。
  • 显存不足时自动重试:如果第一轮训练期间发生 CUDA 显存溢出错误,训练器会自动将批次大小减半并重试(最多 3 次)。此功能仅适用于单 GPU 训练;多 GPU (DDP) 训练会立即报错。
  • 未找到合适值:如果没有候选批次大小能生成可用的性能分析结果,AutoBatch 会抛出明确的RuntimeError,而不会悄悄回退到无关的默认值。

数据增强设置和超参数#

数据增强技术通过增加训练数据的多样性,帮助模型更好地泛化到未见数据,因此对于提升 YOLO 模型的鲁棒性和性能至关重要。下表概述了每个增强参数的用途和效果:

参数类型默认值支持的任务范围说明
hsv_hfloat0.015detect, segment, semantic, depth, classify, pose, obb0.0 - 1.0按色轮的一定比例调整图像色调,增加颜色变化。帮助模型适应不同光照条件。对于 classify,仅在 auto_augment=None 时应用。
hsv_sfloat0.7detect, segment, semantic, depth, classify, pose, obb0.0 - 1.0按一定比例改变图像饱和度,从而影响颜色强度。适用于模拟不同的环境条件。对于 classify,仅在 auto_augment=None 时应用。
hsv_vfloat0.4detect, segment, semantic, depth, classify, pose, obb0.0 - 1.0按一定比例修改图像的明度(亮度),帮助模型在各种光照条件下保持良好表现。对于 classify,仅在 auto_augment=None 时应用。
degreesfloat0detect, segment, semantic, depth, pose, obb0.0 - 180在指定角度范围内随机旋转图像,提升模型识别不同朝向对象的能力。
translatefloat0.1detect, segment, semantic, depth, pose, obb0.0 - 1.0按图像尺寸的一定比例水平和垂直平移图像,帮助模型学会检测部分可见的对象。
scalefloat | tuple0.5detect, segment, semantic, depth, classify, pose, obb0 - 1,或显式指定的 (min, max) 元组(不适用于 classify)按增益系数缩放图像,模拟与摄像头距离不同的对象。
shearfloat0detect, segment, semantic, depth, pose, obb-180 - +180按指定角度剪切图像,模拟从不同角度观察对象的效果。
perspectivefloat0detect, segment, semantic, depth, pose, obb0.0 - 0.001对图像应用随机透视变换,增强模型理解 3D 空间中对象的能力。
flipudfloat0detect, segment, semantic, depth, classify, pose, obb0.0 - 1.0按指定概率将图像上下翻转,增加数据变化性,同时不影响对象特征。
fliplrfloat0.5detect, segment, semantic, depth, classify, pose, obb0.0 - 1.0按指定概率将图像左右翻转,适用于学习对称对象并提高数据集多样性。
bgrfloat0detect, segment, semantic, depth, pose, obb0.0 - 1.0按指定概率将图像通道从 RGB 翻转为 BGR,适用于提升模型对通道顺序错误的鲁棒性。
mosaicfloat1detect, segment, semantic, pose, obb0.0 - 1.0将四张训练图像合并为一张,模拟不同的场景构成和对象交互。适用于复杂场景理解。
mixupfloat0detect, segment, semantic, pose, obb0.0 - 1.0混合两张图像及其标签,生成一张合成图像。通过引入标签噪声和视觉变化,提升模型的泛化能力。
cutmixfloat0detect, segment, semantic, pose, obb0.0 - 1.0合并两张图像的部分区域,形成局部混合,同时保留清晰的区域边界。通过构造遮挡场景增强模型鲁棒性。
copy_pastefloat0segment, semantic, obb0.0 - 1.0粘贴符合条件对象的比例;flip 会在图像内镜像这些对象,而 mixup 还会将此值用作跨图像应用概率。
copy_paste_modestrflipsegment, semantic, obb-指定要使用的 copy-paste 策略。选项包括 'flip' 和 'mixup'。
auto_augmentstrrandaugmentclassify-应用预定义的增强策略('randaugment'、'autoaugment' 或 'augmix'),通过增加视觉多样性来提升模型性能。
erasingfloat0.4classify0.0 - 1.0训练期间随机擦除图像区域,促使模型关注不那么明显的特征。
augmentationslistNonedetect, segment, semantic, depth, pose, obb-用于高级数据增强的自定义 Albumentations 变换(仅限 Python API)。接受变换对象列表,以满足特定的增强需求。

你可以根据数据集和具体任务的需求调整这些设置。尝试不同的值有助于找到最佳的增强策略。

信息

有关训练数据增强操作的更多信息,请参阅参考章节。

日志记录#

训练指标、图表和检查点始终会写入运行目录,Ultralytics 也会将它们流式传输到你已安装并启用的任何实验跟踪器:Comet、ClearML、TensorBoard、MLflow、Weights & Biases 和 DVCLive。每个日志记录器都可通过 Ultralytics 设置切换,例如 yolo settings tensorboard=True。下面展示了三种最常见的配置。

Comet#

Comet 是一个平台,数据科学家和开发者可以用它跟踪、比较、解释和优化实验及模型。它提供实时指标、代码差异和超参数跟踪功能。

使用 Comet 的方法:

示例
# pip install comet_ml
import comet_ml

comet_ml.login()

请记得登录 Comet 网站上的账户并获取 API 密钥。你需要将该密钥添加到环境变量或脚本中,才能记录实验。

ClearML#

ClearML 是一个开源平台,可自动跟踪实验并帮助高效共享资源。它旨在帮助团队更高效地管理、执行和复现 ML 工作。

使用 ClearML 的方法:

示例
# pip install clearml
import clearml

clearml.browser_login()

运行此脚本后,你需要在浏览器中登录 ClearML 账户并验证会话。

TensorBoard#

TensorBoard 是用于 TensorFlow 的可视化工具包。你可以使用它可视化 TensorFlow 图、绘制图执行过程中的定量指标,并展示经过该图的图像等其他数据。

在 Google Colab 中使用 TensorBoard:

示例
%load_ext tensorboard
tensorboard --logdir ultralytics/runs # replace with 'runs' directory

要在本地使用 TensorBoard,请运行以下命令,并在 localhost:6006 查看结果。

示例
tensorboard --logdir ultralytics/runs # replace with 'runs' directory

此操作会启动 TensorBoard,并将其指向保存训练日志的目录。

设置好日志记录器后,照常开始训练。训练指标会自动记录到你选择的平台,你可以在那里持续监控性能、比较模型并找出需要改进的方面。

接下来做什么#

使用留出数据验证训练好的模型,检查其实际精度,然后将其导出为 ONNX、TensorRT 或其他部署格式。如果你使用自己的数据而不是 COCO8 进行训练,请先按照数据集指南设置数据格式。

常见问题#

  • 可以。Ultralytics Platform 云训练提供免费额度,供你开始使用。上传数据集,选择模型和 GPU,然后直接在浏览器中训练。

  • 使用 Ultralytics YOLO26 训练目标检测模型时,你可以使用 Python API 或 CLI。下面分别给出示例:

    单 GPU 和 CPU 训练示例
    from ultralytics import YOLO
    
    # 加载模型
    model = YOLO("yolo26n.pt")  # 加载预训练模型(推荐用于训练)
    
    # 训练模型
    results = model.train(data="coco8.yaml", epochs=100, imgsz=640)

    更多详情请参阅训练设置章节。

  • Ultralytics YOLO26 训练模式的主要功能包括:

    • 自动下载数据集:自动下载 COCO、VOC 和 ImageNet 等标准数据集。
    • 多 GPU 支持:将训练任务扩展到多个 GPU,以加快处理速度。
    • 超参数配置:通过 YAML 文件或 CLI 参数自定义超参数。
    • 可视化与监控:实时跟踪训练指标,以便深入了解训练情况。

    这些功能让训练既高效又能根据你的需求灵活定制。更多详情请参阅训练模式的主要功能章节。

  • 若要从中断的会话恢复训练,请将 resume 参数设为 True,并指定上次保存的检查点路径。

    恢复训练示例
    from ultralytics import YOLO
    
    # 加载部分训练过的模型
    model = YOLO("path/to/last.pt")
    
    # 恢复训练
    results = model.train(resume=True)

    更多信息请参阅恢复中断的训练章节。

  • 当训练数据中某些类别的样本数量明显少于其他类别时,就会出现类别不平衡。这可能导致模型在稀有类别上的表现不佳。Ultralytics YOLO 支持通过 cls_pw 参数设置类别权重,以解决此问题。损失加权最适合作为最后一步,在收集稀有类别样本并进行过采样之后再使用,具体方法见处理类别不平衡。

    cls_pw 参数根据类别频率的倒数控制类别加权强度:

    • cls_pw=0.0(默认值):禁用类别加权
    • cls_pw=1.0:应用完整的频率倒数加权
    • 介于 0.0 和 1.0 之间的值:对类别进行部分加权,以适应中度不平衡的情况

    类别权重按 (1.0 / class_counts) ^ cls_pw 计算,并进行归一化,使其均值等于 1.0。class_counts 是每个类别的标注对象数量;对于分类任务,则是每个类别的训练图像数量。没有训练标签的类别(例如被 classes= 排除的类别)会获得 1.0 的权重。语义分割则根据像素频率计算权重,计算方式为 (1.0 / ln(1.02 + p)) ^ cls_pw,其中 p 表示每个类别中带标注的训练像素所占比例,因此没有带标注像素的类别会获得最大的权重。

    在类别不平衡的数据集上训练
    from ultralytics import YOLO
    
    # 加载预训练模型
    model = YOLO("yolo26n.pt")
    
    # 对严重不平衡的数据应用完整的类别加权进行训练
    results = model.train(data="custom.yaml", epochs=100, imgsz=640, cls_pw=1.0)
    
    # 或者对中度不平衡的数据应用部分加权 (0.25)
    results = model.train(data="custom.yaml", epochs=100, imgsz=640, cls_pw=0.25)
    提示

    对于中度不平衡的数据集,可以先使用 cls_pw=0.25;如果少数类别的表现仍不理想,再将其提高到 1.0。你可以检查训练日志中计算出的类别权重,以确认权重分布。

  • 是的,Ultralytics YOLO26 支持使用 Metal Performance Shaders (MPS) 框架在 Apple 芯片上训练。将 mps 指定为训练设备即可。

    MPS 训练示例
    from ultralytics import YOLO
    
    # 加载预训练模型
    model = YOLO("yolo26n.pt")
    
    # 在 Apple 芯片 (M1/M2/M3/M4) 上训练模型
    results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device="mps")

    更多详情请参阅 Apple 芯片 MPS 训练章节。

  • Ultralytics YOLO26 允许你通过参数配置各种训练设置,例如批次大小、学习率、训练轮数等。以下是简要概述:

    参数默认值说明
    modelNone用于训练的模型文件路径。
    dataNone数据集 YAML 文件的路径(例如 coco8.yaml),或者用于分类的数据集目录或名称(例如 imagenet10)。
    epochs100训练总轮数。
    batch16批次大小,可设置为整数或自动模式。
    imgsz640训练目标图像尺寸。
    deviceNone用于训练的计算设备,例如 cpu、0、0,1 或 mps。
    saveTrue启用训练检查点和最终模型权重的保存功能。

    如需深入了解训练设置,请参阅训练设置章节。

评论1,074

提出问题、分享结果,或帮助其他人。

  1. drcosimoGitHub

    Hi there, I' m new to this field and I'm trying to train a YOLO model for detection and tracking of video streams for security.

    Until now I have managed to create my pipeline for training and I want to understand if it's a correct/possible approach:

    1. Load a pretrained model from yolo

    2. transfer learning with my custom dataset that possibly can focus on just some classes(person,car,truck,bus,bycicle)

    3. Validate model to see how it performs

    4. Operate a tuning with the custom best model and using my custom dataset

    5. Retrain the initial pretrained model with my custom dataset and the best hyperparameters found in the tuning process.

    6. Validate final model

    The questions are several:

    • The above approach is logically correct or it has flaws?
    • Is it correct to narrow the detected classes? Or it isn't crucial to the precision of the model?
    • When tuning(if its a correct approach) should i use my dataset or try the coco dataset to keep generalization?
    • When tuning should i specify the classes to detect?
    • When retraining should I use the first pretrained model or it is better to use my custom trained model?
    • In the final training am I using the correct parameters?

    Here the code of the pipeline:

    from ultralytics import YOLO import yaml

    load pretrained model from coco dataset

    model:YOLO = YOLO('yolov8n.yaml').load('yolov8n.pt')

    train_classes = []

    NOTE if you're using COCO format, the new dataset should also be in COCO format.

    operate transfer learning with my custom dataset, narrowing the classes to the ones I want to detect

    model.train(data='custom_data.yaml',classes=train_classes,epochs=200,imgsz=640,optimizer='AdamW',device=[0,1],augment=True,name='custom_model')

    load custom model

    custom_model = YOLO('path/to/best.pt')

    validate custom model

    custom_model.val()

    try tuning to find the best hyperparameters for my custom model

    custom_model.tune(data='custom_data.yaml', epochs=50, iterations=100,optimizer="AdamW", plots=True,save=True,val=True)

    load best hyperparameters

    cfg = yaml.load(open('path/to/best_hyperparameters.yaml'))

    retrain custom model from pretrained on coco with best hyperparameters

    model.train(data='custom_data.yaml',classes=train_classes,epochs=200,imgsz=640,device=[0,1],name='custom_model',exist_ok=True,optimizer='AdamW',**cfg)

    load and validate

    tuned_custom_model = YOLO('path/to/best.pt')

    tuned_custom_model.val()


    Thank you for your effort and time in this project!

    3
    1. Paula DerrengerUltralytics(已编辑)

      Hello,

      Your approach to training a YOLO model for detection and tracking is well-thought-out and mostly aligns with best practices. Here are some insights and answers to your questions:

      1. Approach Validity: Your steps are logically sound. Starting with a pretrained model and applying transfer learning to your specific classes is a recommended strategy. Validating and tuning based on the performance helps refine the model further.

      2. Narrowing Detected Classes: It's perfectly fine to focus on specific classes if those are the only ones relevant to your use case. This can help improve the model's performance by reducing the complexity of the problem it needs to solve.

      3. Dataset for Tuning: Use your custom dataset for tuning. This ensures that the hyperparameters are optimized for the specific characteristics of your data rather than the general characteristics of the COCO dataset.

      4. Specifying Classes During Tuning: When tuning, you should specify the classes if your dataset is a subset of the original classes used in the pretrained model. This helps in focusing the model’s learning and evaluation on relevant classes.

      5. Model for Retraining: Tuning only finds hyperparameters, so the usual practice is to train again from the original pretrained model with the best hyperparameters, as in your step 5. Continuing from the already fine-tuned model is also possible, but then it effectively trains for longer, which makes the result harder to compare with the tuning runs.

      6. Parameters for Final Training: The parameters should be chosen based on the results of your tuning. Ensure that they are the ones that gave the best validation performance during the tuning phase.

      Keep up the great work, and don't hesitate to reach out if you have more questions!

    2. drcosimoGitHub

      Thank you very much for you response. I adjusted my script to follow your insights. I have another question regarding transfer learning. The normal approach in transfer learning is to freeze the first n layers to preserve the more generic feature extraction properties of an already trained model and then it is retrained letting only the remaining layers update. I found the callback function to achieve this. My question is, applying the fine-tuning as specified by ultralytics documentation has the same effect? What I mean is: executing the train method again on a pretrained model changing the dataset causes the underlying library to execute the freeze automatically? If it isn't the case it is not clear to me why the fine-tuning is said to have the same effect as applying transfer learning.

      Another question is: it is useful to take a pretrained model from ultralytics and train it with the coco dataset? Because from what I know the pretrained model is already trained using coco dataset. Doing such a thing following the logic you provide for fine-tuning would be essentially the same as resuming a training / do the same train with more epochs?

      Thank you again for your time.

    3. Paula DerrengerUltralytics

      Hello,

      Thank you for your follow-up questions. Let's address each of them:

      1. Freezing Layers in Transfer Learning: The Ultralytics YOLO framework does not automatically freeze any layers when you initiate training, even if you're using a pretrained model. If you want to freeze the first N layers (common in transfer learning to preserve learned features), you must explicitly specify this in your training script. This is different from some other frameworks that might automate this aspect of transfer learning.

      2. Training on COCO Dataset with a Pretrained Model: If the pretrained model you are using was already trained on the COCO dataset, retraining it on the same dataset without significant changes or additional data might not yield substantial improvements. It could be beneficial for fine-tuning if you've made modifications to the model architecture or if you're using a significantly altered version of the dataset. However, generally, this approach would indeed be akin to simply extending the training duration.

      For fine-tuning and transfer learning, it's crucial to tailor the approach based on what changes you've made to the dataset or model and your specific goals (e.g., improving accuracy, adapting to new classes, etc.).

      I hope this clarifies your queries! If you have more questions or need further assistance, feel free to ask.

    1. Paula DerrengerUltralytics

      哈哈,确实,“train”翻译成“火车”听起来很有趣 😄。这里的“train”应该翻译为“训练”,指的是在机器学习中对模型进行训练,以提高其准确性和效率。感谢您指出这个问题,我们会尽快修正翻译错误。如果您有任何其他建议或问题,欢迎随时告诉我们!🚀

      2
  2. Syedshajib55GitHub

    Hi, does platform.ultralytics currently support using custom PyTorch modules directly via a YAML configuration without modifying tasks.py or the core source code? We are attempting to train a custom architecture (e.g., YOLO26) and want to know if there is an existing feature for dynamic module registration.

    1
    1. Muh-7GitHub

      Hi, As far as I know, not at the moment. Ultralytics doesn't seem to have a built-in dynamic registration system where you can define a custom PyTorch module outside the repo and then use it directly in the YAML.

      Usually, the custom module still needs to be imported/registered in tasks.py so that parse_model() can resolve it from the YAML.

      It would be really useful if Ultralytics added something like a register_module() API for this, though.

    2. Murat Raimbekov

      @Syedshajib55 @Muh-7 Platform can train any model that the ultralytics Python package can build, including custom architectures from a modified package or fork. The custom code runs on your own hardware; Platform receives real-time metrics, console and system logs, plots, and the final weights.

      There is no dynamic registration API. parse_model() resolves layer names from the ultralytics.nn.tasks namespace, so a name in your YAML must exist there. You don't need to edit tasks.py for that — expose the class from your own package before building the model:

      import ultralytics.nn.tasks as tasks
      from my_custom_package import MyBlock
      
      tasks.MyBlock = MyBlock  # now `[-1, 1, MyBlock, [...]]` resolves in the YAML

      Full local training with metric streaming to Platform:

      pip install "ultralytics>=8.4.120"
      export ULTRALYTICS_API_KEY="YOUR_API_KEY"
      import ultralytics.nn.tasks as tasks
      from my_custom_package import MyBlock
      from ultralytics import YOLO
      
      tasks.MyBlock = MyBlock
      
      model = YOLO("custom-model.yaml")  # YAML referencing MyBlock
      model.train(
          data="ul://username/datasets/my-dataset",
          epochs=100,
          project="username/my-project",
          name="custom-architecture",
      )

      project and name enable the Platform integration automatically; nothing else is required. Verified on 8.4.157 with a custom nn.Module inserted into a YOLO26n YAML: the model builds, trains, and appears on Platform as a completed run with weights and train args.

      One caveat: the saved .pt pickles the class by import path (my_custom_package.MyBlock), so any environment that loads it needs that package importable — otherwise loading fails with ModuleNotFoundError. That includes Platform-side features that load the uploaded weights with the stock package (Predict, Export, Deploy); local training and streaming are unaffected. Setup details: https://docs.ultralytics.com/platform/train/cloud-training/#remote-training

  3. RussellLee12345GitHub

    Hello all,

    I want my training images to rotate 360 degrees randomly. How do I set the hyper-parameter: degrees?

    Thanks a lot.

    1
    1. Glenn JocherUltralytics

      @RussellLee12345 to rotate your training images randomly up to 360 degrees, set the degrees parameter to 180 in your training configuration. This allows for rotations within the range of -180 to +180 degrees. For more details, see the augmentation settings in the Train Settings documentation.

  4. GKYofficeGitHub

    Please tell me how to set imgsz when I use the yolo11 model for training. Can it only be an integer (this means that the final input is a square)? After I modify this parameter, will the input interface of the network change the input of data? There are corresponding transformations, such as imgsz=1280, does it mean that my input data will be resized to 1280*1280 and input into the network for training?

    Thanks!

    1
    1. Glenn JocherUltralytics

      @GKYoffice when using the YOLO11 model, imgsz can be set as an integer, which resizes the input data to a square of that size (e.g., 1280x1280). This parameter adjusts the input dimensions for training. For more details, please visit the training documentation.

  5. IruhDegSetGitHub

    hi, I'm just wondering if yolov8 accepts class weights, in the data.yaml file:

    names: ['class 1', 'class 2', 'class 3']
    classes_weights: [c1_weight, c2_weight, c3_weight]

    if no how to incorpoorate wighted loss in yolov8 THX

    1
    1. Glenn JocherUltralytics

      @IruhDegSet yOLOv8 does not directly support class weights in the data.yaml file. To incorporate weighted loss, you can modify the loss function in the training script to apply different weights to each class. For more details, you might explore custom loss implementations in PyTorch.

    2. Glenn JocherUltralytics(已编辑)

      Yes, YOLO11 supports similar features, including training and hyperparameter customization. For specific details on YOLO11, please refer to the documentation or the relevant sections in the repository.

  6. User

    Dear author, how are the weights of these three losses set: box: 7.5, cls: 0.5, dfl: 1.5? Are they adjusted on the COCO validation, manually adjusted, or obtained through hyperparameter search? For the model I trained, the output confidence scores are very low. I directly increased the weight of cls by 10 times, but the effect did not improve. What other methods can I take?

    1
    1. Glenn JocherUltralytics

      @Stephen-Hao the weights for the box, cls, and dfl losses in YOLOv8 are typically set based on empirical results and fine-tuning on standard datasets like COCO. These values are chosen to balance the contributions of each loss component to the overall training process. If increasing the cls weight did not improve your model's performance, consider the following approaches:

      1. Hyperparameter Tuning: Experiment with other hyperparameters such as learning rate, batch size, and augmentation settings.
      2. Data Quality: Ensure your dataset is well-labeled and balanced. Poor quality data can significantly affect model performance.
      3. Training Duration: Increase the number of epochs to allow the model more time to learn.
      4. Validation: Regularly validate your model to monitor overfitting and adjust training strategies accordingly.

      For more detailed guidance, you can refer to the Ultralytics YOLO training documentation.

    2. Glenn JocherUltralytics

      @Stephen-Hao thank you for your question! The weights for box, cls, and dfl losses are typically set based on empirical results and fine-tuning on standard datasets like COCO. If increasing the cls weight didn't improve your model's performance, consider experimenting with other hyperparameters such as learning rate, batch size, and augmentation settings. Additionally, ensure your dataset is well-labeled and balanced. For more detailed guidance, you can refer to the Ultralytics YOLO training documentation.

    1. Glenn JocherUltralytics(已编辑)

      Hey there! 🙌 It's awesome that you're looking to further improve your model with new data. To re-train a pre-trained model on a new dataset, you can simply follow these steps:

      1. Make sure your new dataset is prepared in the same YOLO format as your initial training (a dataset YAML plus one .txt label file per image).

      2. Load your pre-trained model using the YOLO loading method, then specify your new dataset in the train method. Here's a quick code snippet for clarity:

        from ultralytics import YOLO
        
        # Load your pre-trained model
        model = YOLO('path/to/your/pretrained/model.pt') 
        
        # Start training on the new dataset
        results = model.train(data='path/to/your/new/dataset.yaml', epochs=50, imgsz=640)

      Just replace 'path/to/your/pretrained/model.pt' and 'path/to/your/new/dataset.yaml' with the actual paths to your model and new dataset config file, respectively. Adjust the epochs and imgsz (image size) to suit your needs. 🛠️

      That's it! Your model will now continue training on the new dataset. If you have any further questions or run into issues, feel free to ask. Happy training! 🚀

  7. songziang182GitHub

    谢谢你们开发了这么完善的 yolov8🙏, 我想问一下,这两种训练方式的区别 model = YOLO('yolov8n.pt') model = YOLO('yolov8n.yaml').load('yolov8n.pt') model.train(.........)

    1
    1. Paula DerrengerUltralytics

      Hello there! 😊

      The main difference between the two training methods you've mentioned:

      1. model = YOLO('yolov8n.pt'): This directly loads a pretrained YOLOv8n model. It's the simplest way to load a model that has already been trained, making it ready for further training, evaluation, or inference right away.

      2. model = YOLO('yolov8n.yaml').load('yolov8n.pt'): This approach builds a new model from the YAML configuration file and then transfers the weights from the pretrained .pt model. It's a two-step process, where the model is first constructed based on the architecture defined in the YAML file, and then the weights from a pretrained model are loaded. This method is useful when you want to customize the model architecture before loading the weights.

      Both methods ultimately get you to a similar starting point for continuing training or making predictions. The choice depends on whether you need to customize the model architecture as defined in the YAML file before applying the pretrained weights.

      Let me know if this helps or if you have more questions!

    2. songziang182GitHub

      Thank you for answering me. I find it very useful. I have another question, which is the configuration file yolov8n.yaml. I didn’t find where it is. Can I adjust the scale of the model, for example, n, s, m, l, etc., is this the case?

    3. Paula DerrengerUltralytics(已编辑)

      Hey! 😊 Thank you for your kind words, and I'm glad the information was helpful to you!

      Regarding the yolov8n.yaml configuration file, it defines the architecture for YOLOv8 models. All scales share one model file (yolov8.yaml) that contains a scales section mapping each letter to [depth, width, max_channels]; the letter in the name you load (yolov8n.yaml, yolov8s.yaml, ...) selects the scale:

      scales:
        n: [0.33, 0.25, 1024]
        s: [0.33, 0.50, 1024]

      To create or modify a model, copy the YAML from the Ultralytics GitHub repository, edit the layers or scales, then load it together with the pretrained weights as you mentioned:

      model = YOLO('path/to/custom_yolov8.yaml').load('yolov8n.pt')
      model.train(.........)

      Model changes can require a solid understanding of the network architecture to be effective.

      I hope this clarifies your question! Feel free to reach out if you have further queries or need more examples. 😊

  8. vonzoGitHub

    So, imgsz works different when training than when predicting?

    For train: if it's an int the ratio will be kept and the train function will take care of that (can't be a tuple). For predict: if it's an int the image will be resized as a square of size imgsz x imgsz, if it's a tuple the image will be resized using HxW and the user has to take care of the ratio and stride.

    Is this right? I would add a comment in the doc to avoid confusions

    1
    1. Paula DerrengerUltralytics(已编辑)

      You've got it mostly right! 👍 For training (train), imgsz is an int, the aspect ratio is maintained and resizing is handled internally. It can't be a tuple. For prediction (predict), an int imgsz resizes the longest side to imgsz while keeping the aspect ratio, with padding only up to a multiple of the model stride (so the image is not forced into a square), and a [h, w] list sets the size explicitly.

      Great suggestion on the documentation comment – clarity is key! If you have any more questions or need further examples, feel free to ask. 😊