资讯 小学 初中 高中 语言 会计职称 学历提升 法考 计算机考试 医护考试 建工考试 教育百科
栏目分类:
子分类:
返回
空麓网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
空麓网 > 计算机考试 > 软件开发 > 后端开发 > Python

Yolov8训练调试简单教程

Python 更新时间: 发布时间: 计算机考试归档 最新发布

文章目录

  • 参考
  • 前言
  • YOLO: A Brief History
  • 官方使用指南引导
  • YOLOV8训练调试使用
    • 训练
    • 验证
    • 预测

参考

YOLOv8自用训练教程——训练、测试、推理
代码下载地址

前言

YOLOV5跟YOLOV8的项目都是ultralytics发布的,刚下载YOLOV8的时候发现V8的项目跟V5变化还是挺大的,看了一下README同时看了看别人写的。大致是搞懂了V8具体使用。这一篇笔记,大部分都是项目里的文档内容。建议直接去看项目里的文档。
首先在V8中需要先安装pip install ultralytics,这是作者ultralytics出的第三方python库。
ultralytics在V8中提供两种使用模式:CLI跟python,CLI模式可以直接在命令行界面使用,如下:

yolo predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg'

也可以在python的环境中使用,因为看这个项目,有时候需要debug去看每个环节的输出,所以还是更习惯用python环境,这一篇笔记主要也是记录python模式下的使用。先简单举个例子:

from ultralytics import YOLO# 加载模型model = YOLO("yolov8n.yaml")  # 从头开始构建新模型model = YOLO("yolov8n.pt")  # 加载预训练模型(建议用于训练)# 使用模型model.train(data="coco128.yaml", epochs=3)  # 训练模型metrics = model.val()  # 在验证集上评估模型性能results = model("http://www.quxuehao.com/file/tupian/20230516/bus.jpg")  # 对图像进行预测success = model.export(format="onnx")  # 将模型导出为 ONNX 格式

YOLO: A Brief History

这是文档里的介绍,简单总结就这东西很好。

YOLO (You Only Look Once), a popular object detection and image segmentation model, was developed by Joseph Redmon and Ali Farhadi at the University of Washington. Launched in 2015, YOLO quickly gained popularity for its high speed and accuracy.

  • YOLOv5 further improved the model’s performance and added new features such as hyperparameter optimization, integrated experiment tracking and automatic export to popular export formats.

  • YOLOv8 is the latest version of the YOLO object detection and image segmentation model. As a cutting-edge, state-of-the-art (SOTA) model, YOLOv8 builds on the success of previous versions, introducing new features and improvements for enhanced performance, flexibility, and efficiency.

YOLOv8的设计非常注重速度、尺寸和精度,使其成为各种视觉人工智能任务的令人注目的选择。它通过整合新的骨干网、新的无锚分头和新的损失函数等创新,超越了以前的版本。这些改进使YOLOv8能够提供卓越的结果,同时保持紧凑的尺寸和卓越的速度。

官方使用指南引导

官方的快速使用指南帮助文档地址如下:

这个文件里简单的列举了安装、用CLI使用V8、用python环境使用V8。
如下是用python环境使用V8,想要看具体怎么用python环境调试,直接点我画红框部分(ctrl+鼠标左键)。

当然自己点进去这个文档也行。

YOLOV8训练调试使用

文档里内容很多,以下仅介绍这三部分,有精力还是建议去读帮助文档。
自己创建一个python文件,例如我创建了个叫train的文件:


然后把需要的代码写到这个文件里,直接run或者debug都行,这样子你就可以去看代码一步步是怎么进行了的。

训练

训练模式用于在自定义数据集上训练YOLOv8模型。在这种模式下,使用指定的数据集和超参数训练模型。训练过程包括优化模型的参数,使其能够准确预测图像中物体的类别和位置。

=== "From pretrained(recommended)"    ```python    #有预训练模型,默认使用coco数据集。    from ultralytics import YOLO	#加载了预训练模型,然后再进行5轮训练。    model = YOLO('yolov8n.pt') # pass any model type    model.train(epochs=5)    ```=== "From scratch"    ```python    #从0开始训练,没有预训练模型    from ultralytics import YOLO	#根据yolov8n.yaml的这文件重新搭建一个新的模型。    model = YOLO('yolov8n.yaml')    #然后从头开始训练。    model.train(data='coco128.yaml', epochs=5)    ```=== "Resume"    ```python    #因为一些原因(停电等等)中断了之前的训练,然后想继续之前的训练,用resume。    model = YOLO("last.pt")    model.train(resume=True)    ```

先来看YOLO这个类,这个类提供了两种方法,一个是_new(cfg:str),读取的是一个cfg的配置文件,其实就是yaml文件,另一个方法是_load(weights:str)直接读取模型。这两个方法都可以用来生成一个新的模型,用以后续的训练。:

代码也很简单不管是model = YOLO('yolov8n.yaml')还是model = YOLO('yolov8n.pt')读进来的都是字符串,首先先获取读进来的字符串的后缀,然后判断后缀是yaml还是pt,然后对应的直接生成新模型。:

在帮助文档里还举了另一个例子,告诉我们,怎么把预训练权值加载到新建的模型里,如下代码所示model = YOLO('yolov8n.yaml').load('yolov8n.pt')这一句就是将yolov8n.pt这个预训练模型加载到通过yolov8n.yaml文件创建的新模型中。
在V5中很多参数(例如epochs, imgsz等等)在parser中可以直观的设置。
在v8中直接封装到train函数中,例如下列代码model.train(data='coco128.yaml', epochs=100, imgsz=640)我们需要将我们所需的设置传参给train函数。

    from ultralytics import YOLO        # Load a model    model = YOLO('yolov8n.yaml')  # build a new model from YAML       model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)    model = YOLO('yolov8n.yaml').load('yolov8n.pt')  # build from YAML and transfer weights        # Train the model    model.train(data='coco128.yaml', epochs=100, imgsz=640)

下列是可传入train参数:

KeyValueDescription
modelNone模型路径. yolov8n.pt, yolov8n.yaml
dataNone数据集路径, i.e. coco128.yaml
epochs100训练的总轮次
patience50等待没有明显的改善,尽早停止训练的轮次
batch16number of images per batch (-1 for AutoBatch)
imgsz640size of input images as integer or w,h
saveTruesave train checkpoints and predict results
save_period-1保存检查点每x个epoch ( (disabled if < 1)
cacheFalseTrue/ram, disk or False. 用于数据加载的Usle缓存
deviceNonedevice to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu
workers8number of worker threads for data loading (per RANK if DDP) 用于数据加载的工作线程数
projectNoneproject name 项目名称
nameNoneexperiment name 实验名称
exist_okFalsewhether to overwrite existing experiment 是否覆盖现有实验
pretrainedFalsewhether to use a pretrained model 是否使用预训练的模型
optimizer'SGD'optimizer to use, choices=[‘SGD’, ‘Adam’, ‘AdamW’, ‘RMSProp’] 使用优化器,
verboseFalsewhether to print verbose output 是否打印详细输出
seed0random seed for reproducibility 随机种子的重现性
deterministicTruewhether to enable deterministic mode 是否启用确定性模式
single_clsFalsetrain multi-class data as single-class 将多类数据训练为单类
image_weightsFalseuse weighted image selection for training 使用加权图像选择进行训练
rectFalserectangular training with each batch collated for minimum padding
cos_lrFalseuse cosine learning rate scheduler
close_mosaic0(int) disable mosaic augmentation for final epochs
resumeFalseresume training from last checkpoint
ampTrueAutomatic Mixed Precision (AMP) training, choices=[True, False]
lr00.01initial learning rate (i.e. SGD=1E-2, Adam=1E-3)
lrf0.01final learning rate (lr0 * lrf)
momentum0.937SGD momentum/Adam beta1
weight_decay0.0005optimizer weight decay 5e-4
warmup_epochs3.0warmup epochs (fractions ok)
warmup_momentum0.8warmup initial momentum
warmup_bias_lr0.1warmup initial bias lr
box7.5box loss gain
cls0.5cls loss gain (scale with pixels)
dfl1.5dfl loss gain
pose12.0pose loss gain (pose-only)
kobj2.0keypoint obj loss gain (pose-only)
label_smoothing0.0label smoothing (fraction)
nbs64nominal batch size
overlap_maskTruemasks should overlap during training (segment train only)
mask_ratio4mask downsample ratio (segment train only)
dropout0.0use dropout regularization (classify train only)
valTruevalidate/test during training

验证

Val模式用于YOLOv8模型训练后的验证。在这种模式下,模型在验证集上进行评估,以衡量其准确性和泛化性能。该模式可用于调优模型的超参数,以提高模型的性能。

=== "Val after training"	#训练后验证    ```python      from ultralytics import YOLO      model = YOLO('yolov8n.yaml')      model.train(data='coco128.yaml', epochs=5) #训练五轮      model.val() #训练完毕后进行验证集验证,会根据数据集的yaml文件寻找验证集 It'll automatically evaluate the data you trained.    ```=== "Val independently"	#独立验证    ```python      from ultralytics import YOLO      model = YOLO("model.pt") #先载入模型      # It'll use the data yaml file in model.pt if you don't set data.      model.val()# 如果不给验证函数val传参,他只验证模型里数据集yaml文件下的val数据。      # or you can set the data you want to val      model.val(data='coco128.yaml')#给验证函数传入数据集,模型对这个数据集进行验证。    ```

帮助文档里还有一个例子:
这里例子里通过metrics.box.map等去获得模型的map情况。

    ```python    from ultralytics import YOLO        # Load a model 加载模型    model = YOLO('yolov8n.pt')  # load an official model    model = YOLO('path/to/best.pt')  # load a custom model        # Validate the model 验证模型    metrics = model.val()  # no arguments needed, dataset and settings remembered    metrics.box.map    # map50-95    metrics.box.map50  # map50    metrics.box.map75  # map75    metrics.box.maps   # a list contains map50-95 of each category    ```

可传入val()函数的参数较训练模式少了一些,具体如下:

KeyValueDescription
dataNonepath to data file, i.e. coco128.yaml
imgsz640image size as scalar or (h, w) list, i.e. (640, 480)
batch16number of images per batch (-1 for AutoBatch)
save_jsonFalsesave results to JSON file
save_hybridFalsesave hybrid version of labels (labels + additional predictions)
conf0.001object confidence threshold for detection
iou0.6intersection over union (IoU) threshold for NMS
max_det300maximum number of detections per image
halfTrueuse half precision (FP16)
deviceNonedevice to run on, i.e. cuda device=0/1/2/3 or device=cpu
dnnFalseuse OpenCV DNN for ONNX inference
plotsFalseshow plots during training
rectFalserectangular val with each batch collated for minimum padding
splitvaldataset split to use for validation, i.e. ‘val’, ‘test’ or ‘train’

预测

预测模式用于使用经过训练的YOLOv8模型对新图像或视频进行预测。在这种模式下,从检查点文件加载模型,用户可以提供图像或视频来执行推断。该模型预测输入图像或视频中对象的类别和位置。
不同的数据源的处理方法不同:

=== "From source"    ```python    from ultralytics import YOLO    from PIL import Image    import cv2    model = YOLO("model.pt") #模型加载    # accepts all formats - image/dir/Path/URL/video/PIL/ndarray. 0 for webcam    #接受所有格式- image/dir/Path/URL/video/PIL/ndarray。0代表网络摄像头    results = model.predict(source="0")     results = model.predict(source="folder", show=True) # Display preds. Accepts all YOLO predict arguments    # from PIL    #通过PIL接受数据源    im1 = Image.open("bus.jpg")    results = model.predict(source=im1, save=True)  # save plotted images 保存绘制图片    # from ndarray    #通过opencv接受数据源    im2 = cv2.imread("bus.jpg")    results = model.predict(source=im2, save=True, save_txt=True)  # save predictions as labels    # from list of PIL/ndarray    #可以做列表接受两种数据源接受模式。    results = model.predict(source=[im1, im2])    ```
转载请注明:文章转载自 http://www.konglu.com/
本文地址:http://www.konglu.com/it/1097424.html
免责声明:

我们致力于保护作者版权,注重分享,被刊用文章【Yolov8训练调试简单教程】因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理,本文部分文字与图片资源来自于网络,转载此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请立即通知我们,情况属实,我们会第一时间予以删除,并同时向您表示歉意,谢谢!

我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2023 成都空麓科技有限公司

ICP备案号:蜀ICP备2023000828号-2