【YOLO】YOLOv8怎么调参及配置文件如何调用?(持续更新)

图片取自:https://github.com/ultralytics/ultralytics

YOLOv8源码(旧版本的,大家可以拿去学习)

放在这里啦,请自取!!!点个赞吧

【免费】YOLOv8源码(之前版本的,大家可以拿去学习)资源-CSDN文库

YOLO训练方式

先了解一下几种训练方式,为了方便调参和学习各个参数,我们使用调用配置文件的方式

这次使用第3种方式!!!

1. 使用命令行接口

YOLOv8提供了用户友好的命令行接口,允许用户通过简单的命令来训练、验证和预测模型。这种方式特别适用于那些喜欢使用终端或脚本进行自动化操作的用户。

示例命令

训练模型:yolo task=detect mode=train model=yolov8n.pt data=my_dataset.yaml epochs=100 imgsz=640
验证模型:yolo task=detect mode=val model=best.pt data=my_dataset.yaml
预测图像:yolo task=detect mode=predict model=best.pt source=image.jpg

2. 使用代码

示例代码

from ultralytics import YOLO 


# 加载预训练模型(和train.py同一文件夹下)
model = YOLO("yolov8n.pt")


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

当然也可以这样写:

# Yolo预训练模型
model = "yolov8n.pt"
YOLO(model).train(data=data,
                  device=device,
                  epochs=300,
                  batch=-1)

3. 调用配置文件(.yaml文件)

1.打开yolov8源码,可见配置文件地址在ultralytics/yolo/cfg/default.yaml

2.复制一份一样的下来,改成自己项目需要的名字(用于自己的调参),我这里是train_beetle.yaml(当然也可以在default.yaml下改)

3.修改train.py(路径:ultralytics/yolo/v8/detect/train.py)

可以把train函数修改成如下:

def train(cfg=DEFAULT_CFG, use_python=True):
    """
    用cfg配置文件(地址:ultralytics/yolo/cfg/default.yaml)
    """

    # 配置文件(改成你自己的)
    cfg = "train_beetle.yaml"
    model = 'yolov8x.pt'  # 加载预训练模型 (推荐)

    # data = 'data.yaml'  # or yolo.ClassificationDataset("mnist")
    # device = 'cuda:0'  # or "cpu"
    # args = dict(model=model, data=data, device=device)

    if use_python:
        from ultralytics import YOLO
        YOLO(model).train(cfg=cfg)
    else:
        pass
        # trainer = DetectionTrainer(overrides=args)
        # trainer.train()

目前我只发现一个warning,解决方法我放在另一篇博客上了,大家可自行查看

【报错解决】ERROR:albumentations.check_version:Error fetching version info-CSDN博客

为防止出现warning,修改如下

if __name__ == '__main__':
    # 忽略更新,解决:ERROR:albumentations.check_version:Error fetching version info
    os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1'
    # 忽略 UserWarning
    warnings.filterwarnings("ignore", category=UserWarning)
    # train()
    # 用cfg配置文件(地址:ultralytics/yolo/cfg/train_beetle.yaml)
    train()

YOLOv8配置文件(default.yaml)

# Ultralytics YOLO 🚀, GPL-3.0 license
# Default training settings and hyperparameters for medium-augmentation COCO training

task: detect  # inference task, i.e. detect, segment, classify
mode: train  # YOLO mode, i.e. train, val, predict, export

# Train settings -------------------------------------------------------------------------------------------------------
model:  # path to model file, i.e. yolov8n.pt, yolov8n.yaml
data:  # path to data file, i.e. i.e. coco128.yaml
epochs: 100  # number of epochs to train for
patience: 50  # epochs to wait for no observable improvement for early stopping of training
batch: 16  # number of images per batch (-1 for AutoBatch)
imgsz: 640  # size of input images as integer or w,h
save: True  # save train checkpoints and predict results
save_period: -1 # Save checkpoint every x epochs (disabled if < 1)
cache: False  # True/ram, disk or False. Use cache for data loading
device:  # device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu
workers: 8  # number of worker threads for data loading (per RANK if DDP)
project:  # project name
name:  # experiment name
exist_ok: False  # whether to overwrite existing experiment
pretrained: False  # whether to use a pretrained model
optimizer: SGD  # optimizer to use, choices=['SGD', 'Adam', 'AdamW', 'RMSProp']
verbose: True  # whether to print verbose output
seed: 0  # random seed for reproducibility
deterministic: True  # whether to enable deterministic mode
single_cls: False  # train multi-class data as single-class
image_weights: False  # use weighted image selection for training
rect: False  # support rectangular training if mode='train', support rectangular evaluation if mode='val'
cos_lr: False  # use cosine learning rate scheduler
close_mosaic: 10  # disable mosaic augmentation for final 10 epochs
resume: False  # resume training from last checkpoint
min_memory: False  # minimize memory footprint loss function, choices=[False, True, <roll_out_thr>]
# Segmentation
overlap_mask: True  # masks should overlap during training (segment train only)
mask_ratio: 4  # mask downsample ratio (segment train only)
# Classification
dropout: 0.0  # use dropout regularization (classify train only)

# Val/Test settings ----------------------------------------------------------------------------------------------------
val: True  # validate/test during training
split: val  # dataset split to use for validation, i.e. 'val', 'test' or 'train'
save_json: False  # save results to JSON file
save_hybrid: False  # save hybrid version of labels (labels + additional predictions)
conf:  # object confidence threshold for detection (default 0.25 predict, 0.001 val)
iou: 0.7  # intersection over union (IoU) threshold for NMS
max_det: 300  # maximum number of detections per image
half: False  # use half precision (FP16)
dnn: False  # use OpenCV DNN for ONNX inference
plots: True  # save plots during train/val

# Prediction settings --------------------------------------------------------------------------------------------------
source:  # source directory for images or videos
show: False  # show results if possible
save_txt: False  # save results as .txt file
save_conf: False  # save results with confidence scores
save_crop: False  # save cropped images with results
hide_labels: False  # hide labels
hide_conf: False  # hide confidence scores
vid_stride: 1  # video frame-rate stride
line_thickness: 3  # bounding box thickness (pixels)
visualize: False  # visualize model features
augment: False  # apply image augmentation to prediction sources
agnostic_nms: False  # class-agnostic NMS
classes:  # filter results by class, i.e. class=0, or class=[0,2,3]
retina_masks: False  # use high-resolution segmentation masks
boxes: True  # Show boxes in segmentation predictions

# Export settings ------------------------------------------------------------------------------------------------------
format: torchscript  # format to export to
keras: False  # use Keras
optimize: False  # TorchScript: optimize for mobile
int8: False  # CoreML/TF INT8 quantization
dynamic: False  # ONNX/TF/TensorRT: dynamic axes
simplify: False  # ONNX: simplify model
opset:  # ONNX: opset version (optional)
workspace: 4  # TensorRT: workspace size (GB)
nms: False  # CoreML: add NMS

# Hyperparameters ------------------------------------------------------------------------------------------------------
lr0: 0.01  # initial learning rate (i.e. SGD=1E-2, Adam=1E-3)
lrf: 0.01  # final learning rate (lr0 * lrf)
momentum: 0.937  # SGD momentum/Adam beta1
weight_decay: 0.0005  # optimizer weight decay 5e-4
warmup_epochs: 3.0  # warmup epochs (fractions ok)
warmup_momentum: 0.8  # warmup initial momentum
warmup_bias_lr: 0.1  # warmup initial bias lr
box: 7.5  # box loss gain
cls: 0.5  # cls loss gain (scale with pixels)
dfl: 1.5  # dfl loss gain
fl_gamma: 0.0  # focal loss gamma (efficientDet default gamma=1.5)
label_smoothing: 0.0  # label smoothing (fraction)
nbs: 64  # nominal batch size
hsv_h: 0.015  # image HSV-Hue augmentation (fraction)
hsv_s: 0.7  # image HSV-Saturation augmentation (fraction)
hsv_v: 0.4  # image HSV-Value augmentation (fraction)
degrees: 0.0  # image rotation (+/- deg)
translate: 0.1  # image translation (+/- fraction)
scale: 0.5  # image scale (+/- gain)
shear: 0.0  # image shear (+/- deg)
perspective: 0.0  # image perspective (+/- fraction), range 0-0.001
flipud: 0.0  # image flip up-down (probability)
fliplr: 0.5  # image flip left-right (probability)
mosaic: 1.0  # image mosaic (probability)
mixup: 0.0  # image mixup (probability)
copy_paste: 0.0  # segment copy-paste (probability)

# Custom config.yaml ---------------------------------------------------------------------------------------------------
cfg:  # for overriding defaults.yaml

# Debug, do not modify -------------------------------------------------------------------------------------------------
v5loader: False  # use legacy YOLOv5 dataloader

# Tracker settings ------------------------------------------------------------------------------------------------------
tracker: botsort.yaml  # tracker type, ['botsort.yaml', 'bytetrack.yaml']

YOLOv8参数详解

训练设置 (Train settings)

  • task: 设定任务类型,如detect(检测)、segment(分割)、classify(分类)。
  • mode: YOLO的工作模式,如train(训练)、val(验证)、predict(预测)、export(导出)。
  • model: 模型文件的路径。
  • data: 数据文件的路径。
  • epochs: 训练的总轮次。
  • patience: 早停训练的等待轮次,如果在指定轮次内没有观察到改进,则停止训练。
  • batch: 每批次的图像数量。
  • imgsz: 输入图像的尺寸。
  • save: 是否保存训练检查点和预测结果。
  • save_period: 每隔多少轮次保存一次检查点(如果小于1,则禁用)。
  • cache: 是否使用缓存来加载数据,可以是True(使用RAM)、diskFalse
  • device: 运行设备的指定,如cuda:0cpu
  • workers: 数据加载的工作线程数。
  • project 和 name: 项目和实验的名称。
  • exist_ok: 是否覆盖现有的实验。
  • pretrained: 是否使用预训练模型。
  • optimizer: 优化器的选择,如SGDAdamAdamWRMSProp
  • verbose: 是否打印详细输出。
  • seed: 随机种子,用于结果的可复现性。
  • deterministic: 是否启用确定性模式。
  • single_cls: 是否将多类数据作为单类数据进行训练。
  • image_weights: 是否使用加权图像选择进行训练。
  • rect: 是否支持矩形训练/验证。
  • cos_lr: 是否使用余弦学习率调度器。
  • close_mosaic: 禁用马赛克增强的最后几个轮次。
  • resume: 是否从最后的检查点恢复训练。
  • min_memory: 最小化内存占用损失函数的选项。

验证/测试设置 (Val/Test settings)

  • val: 是否在训练期间进行验证/测试。
  • split: 用于验证的数据集分割,如valtesttrain
  • save_json 和 save_hybrid: 是否保存结果到JSON文件或混合版本。
  • conf: 检测的对象置信度阈值。
  • iou: NMS(非极大值抑制)的交并比阈值。
  • max_det: 每张图像的最大检测数。
  • half: 是否使用半精度(FP16)。
  • dnn: 是否使用OpenCV DNN进行ONNX推理。
  • plots: 是否保存训练/验证过程中的图表。

预测设置 (Prediction settings)

  • source: 图像或视频源的目录。
  • show: 是否显示结果。
  • save_txtsave_confsave_crop: 是否保存结果为.txt文件、带置信度的结果或裁剪后的图像。
  • hide_labels 和 hide_conf: 是否隐藏标签或置信度分数。
  • vid_stride: 视频帧率的步长。
  • line_thickness: 边界框的厚度(像素)。
  • visualize: 是否可视化模型特征。
  • augment: 是否对预测源应用图像增强。
  • agnostic_nms: 是否使用类不可知的NMS。
  • classes: 过滤结果按类别。
  • retina_masks: 是否使用高分辨率分割掩码。
  • boxes: 是否在分割预测中显示边界框。

导出设置 (Export settings)

  • format: 导出格式,如torchscript
  • kerasoptimizeint8dynamicsimplifyopsetworkspacenms: 与不同导出格式相关的选项。

超参数 (Hyperparameters)

例如使用Adam时,lr0: 0.001

lr0: 0.01  # initial learning rate (i.e. SGD=1E-2, Adam=1E-3)

这些参数定义了训练过程中的学习率、动量、权重衰减等。还包括了图像增强相关的参数,如HSV调整、旋转、平移、缩放等。(后续更新如何使用

自定义配置 (Custom config.yaml)

允许通过cfg键覆盖默认设置。

调试和跟踪器设置

  • v5loader: 是否使用YOLOv5的旧版数据加载器。
  • tracker: 跟踪器的类型,如botsort.yamlbytetrack.yaml

持续更新,尽情期待!!!

  • 18
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值