从0开始yolov8模型目标检测训练 验证和测试
1 大环境
首先有大环境,即已经准备好了python、nvidia驱动、cuda、cudnn等。
2 yolov8的虚拟环境
2.1 创建虚拟环境
conda create -n yolov8 python=3.10
2.2 激活虚拟环境
注意:激活虚拟环境的时候,需要清楚自己创建的虚拟环境(yolov8)是在root权限下,还是在user权限下,否则,当使用source activate yolov8激活环境的时候,可能一直会提示Could not find conda environment: yolov5s;You can list all discoverable environments with conda info --envs
source activate yolov8
# 如果是windows的话,使用
conda activate yolov8
# 关闭虚拟环境
source deactivate yolov8
# 删除虚拟环境
conda remove -n yolov8 --all
# 删除虚拟环境中的某个包
conda remove --name $yolov8 $package_name
# 添加conda的清华镜像源
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn
其它:普通用户和root用户权限相互切换的方法:
exit
或
su user(user是自己安装时的用户名)
2.3 在虚拟环境中安装yolov8的必要依赖项
进入yolov8项目的根目录下
cd MyTrain/ultralytics-main
然后,使用Pip在一个Python>=3.8环境中安装ultralytics包,此环境还需包含PyTorch>=1.7。同时也会安装所有必要的requirements.txt。
pip install ultralytics
3 准备数据集
3.1 数据集介绍
采用26058张图片,标签文件是之前用标注精灵标注导出的json文件。
3.2 标签统计
统计标注文件包含的标签类别及数量如下
'suv': 19843, 'car': 222010, 'van': 8538, 'bigtru': 11775, 'bus': 7733, 'tralight': 32538, 'tricycle': 9454, 'elec': 45199, 'pedes': 36552, 'smatru': 2281, 'bike': 7908, 'coach': 443, 'tank': 2659, 'pickup': 943, 'trailer': 438, 'mpv': 1839, ' car': 1354, ' ca r': 1, 'elec ': 12, 'moto': 843, 'crane': 173, 'warm': 151644, 'percycle': 127, 'engine': 157, 'polic': 398, 'coni': 9758, 'pedesd': 13, 'van ': 1, 'motopoli': 22, 'escort': 26, 'tralight ': 1, 'right': 78, 'left': 114, 'stopline': 4, 'zebraline': 78, 'bull': 19, 'excava': 4, 'suv ': 2, 'zebraliner': 1, 'car ': 3, ' ': 1, 'car ': 1, 'ambu': 168, 'sanJiaoWarm': 778, 'suLiaoDao': 506, 'zhiXiang': 1248, 'suLiaoDai': 414, 'lunTai': 643, 'yiZi': 20, 'ar': 1, ' car': 141, 'bus-c': 2, 'elerc': 1, 'pedes ': 1, 'pedesr': 3, 'carr': 1, 'bigtrur': 2, 'elecr': 12, 'suvr': 72,
上述标签类别解释:上述存在的一些奇怪标签,如’carr’、‘bigtrur’、'pedes ‘等很显然是由于误输入’r’或空格字符导致的,故在转换为yolov5的标注格式的时候,需考虑在内。故采用映射如下,得到标签及ID。其中标签’sanJiao Warm’, ‘suLiaoDao’, ‘zhiXiang’, ‘suLiaoDai’, ‘lunTai’, 'yiZi’等标签不作为训练。
{'suv': 1, 'car': 1, 'van': 1, 'bigtru': 3, 'bus': 2, 'tralight': 9, 'tricycle': 6, 'elec': 5, 'pedes': 0, 'smatru': 3, 'bike': 4, 'coach': 2, 'tank': 3, 'pickup': 1, 'trailer': 3, 'mpv': 1, ' car': 1, ' ca r': 1, 'elec ': 5, 'moto': 5, 'crane': 3, 'warm': 8, 'engine': 3, 'polic': 10, 'coni': 7, 'pedesd': 0, 'van ': 1, 'motopoli': 5, 'escort': 3, 'tralight ': 9, 'bull': 3, 'excava': 3, 'suv ': 1, 'car ': 1, 'car ': 1, 'ambu': 10, 'ar': 1, ' car': 1, 'bus-c': 2, 'elerc': 5, 'pedes ': 0, 'pedesr': 0, 'carr': 1, 'bigtrur': 3, 'elecr': 5, 'suvr': 1}
标签重新分配如下
pedes: 0, car: 1, bus: 2, truck: 3, bike: 4, elec: 5, tricycle: 6, coni: 7, warm: 8, tralight: 9, special_vehicles: 10
3.3 转为yolov8的txt
yolov8的标签文件和yolov5是一样的,需要归一化(0-1)的目标类型、 Box中心点坐标x、Box中心点坐标y、Box宽、Box高
--datasTrain
------train_list.txt # 包含训练每张图片的路径
------val_list.txt
------test_list.txt
------images
----------train # 存放训练数据集的图片(.jpg)
----------val
----------test
------labels
----------train # 存放训练图片对应的标签文件(.txt)
----------val
----------tes
datasTrain/labels/train目录下的文件示例,如下为data220829_0001.jpg对应的data220829_0001.txt的前6行内容。
2 0.29427 0.33842 0.19479 0.27685
3 0.11380 0.56111 0.22760 0.43703
3 0.39479 0.41064 0.11041 0.17314
1 0.39401 0.29490 0.02760 0.06759
1 0.40729 0.25833 0.05 0.07222
1 0.61875 0.16574 0.02604 0.04444
4 准备训练
4.1 模型的配置文件
修改路径下的配置文件 ultralytics-main/ultralytics/yolo/cfg/default.yaml 参数,以执行相应的操作(train、val、test)。
yolo/cfg/default.yaml 中如下参数需设置或查验与任务是否一致(包含训练模式示例值)
task: detect # inference task, i.e. detect, segment, classify
mode: train # YOLO mode, i.e. train, val, predict, export
# Train settings -------------------------------------------------
# model 使用.pt文件是通过预训练模型
# model: ./preDetectModel/yolov8s.pt
# model 使用.yaml文件是从头开始训练,使用COCO模型来预训练口罩检测不可取,必须从头训练
model: D:/yolov5train/yolov8_main/ultralytics/models/v8/yolov8s.yaml
# data: path to data file, i.e. coco128.yaml
data: D:/yolov5train/yolov8_main/ultralytics/yolo/v8/detect/data/my_yolov8.yaml
epochs: 300 # number of epochs to train for
patience: 50 # epochs to wait for no observable improvement for early stopping of training
batch: 2 # number of images per batch (-1 for AutoBatch)
imgsz: 960 # size of input images as integer or w,h
save: True # save train checkpoints and predict results
save_period: 10 # Save checkpoint every x epochs (disabled if < 1,设为-1则禁用保存检查点)
single_cls: False # train multi-class data as single-class
rect: True # support rectangular train/val if mode='train'/'val'
resume: False # resume training from last checkpoint
上述参数详解参考博客:https://blog.csdn.net/weixin_45277161/article/details/131047101
其中模型的配置文件位于ultralytics-main/ultralytics/models/v8/yolov8s.yaml ,该文件包含主要内容如下:
# Parameters
nc: 11 # number of classes
scales: # model compound scaling constants
# [depth, width, max_channels]
s: [0.33, 0.50, 1024] # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients, 28.8 GFLOPs
# YOLOv8.0n backbone
backbone:
# YOLOv8.0n head
head:
4.2 数据的配置文件
数据集的配置文件模仿ultralytics-main/ultralytics/datasets/coco.yaml文件的写法,记为my_yolov8.yaml,该文件包含内容如下
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: D:/yolov5train/datasTrain3_More # dataset root dir
train: D:/yolov5train/datasTrain3_More/train_list.txt # train images (relative to 'path')
val: D:/yolov5train/datasTrain3_More/val_list.txt # val images (relative to 'path')
test: D:/yolov5train/datasTrain3_More/test_list.txt
# Classes
names:
0: pedes
1: car
2: bus
3: truck
4: bike
5: elec
6: tricycle
7: coni
8: warm
9: tralight
10: specialVehicle
4.3 train的.py文件
其实train.py文件中的参数在ultralytics-main/ultralytics/yolo/cfg/default.yaml中如果设置好了的话,就可以不用管了。如果没有设置/yolo/cfg/default.yaml的话,采用如下方式启动训练,否则,采用4.4所述的方式启动训练命令。
ultralytics-main/ultralytics$yolo task=detect mode=train model=models/v8/yolov8s.yaml data=/ultralytics/yolo/v8/detect/data/my_yolov8.yaml imgsz=960 batch=-1 epochs=300 patience=50 workers=4
# 同时也尽可以正确设置/yolo/cfg/default.yaml中的参数
4.4 训练命令
cd ultralytics-main/ultralytics/
yolo cfg=./yolo/cfg/default.yaml
或
yolo cfg = ./yolo/cfg/default.yaml task=detect mode=train rect=True batch = 64 epochs = 300 imgsz=960 data=my_data.yaml
# my_data.yaml如下
path: home/MyTrain/datas/ # dataset root dir
train: images/train # train images (relative to 'path') 128 images
val: images/val # val images (relative to 'path') 128 images
names:
0: pedes
1: car
2: bus
3: truck
4: bike
5: moto
6: tricycle
7: coni
8: warn
9: tralight
10: specialVehicle
# names:
# 0: 行人
# 1: 轿车
# 2: 公交
# 3: 货车
# 4: 自行车
# 5: 摩托车
# 6: 三轮车
# 7: 锥桶
# 8: 警示标志
# 9: 信号灯
# 10: 特殊车辆
【问题1】
300轮的正常训练结束了,但是仍然报了一个pyplot的奇怪的问题如下
plt.switch_backend(original_backend)
File "/home/user/anaconda3/envs/yolov8/lib/python3.10/site-packages/matplotlib/pyplot.py", line 279, in switch_backend
raise ImportError(
ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running
matplotlib版本过高导致的,卸载环境中matplotlib版本,重新安装。
pip uninstall matplotlib
pip install matplotlib==3.2.1
# 由于 v8在训练的时候,大环境ultralytics 8.0.155 requires matplotlib>=3.2.2。
# 所以又重新卸载了 装了一个刚好大于等于3.2.2版本的matplotlib
# 如下
pip install matplotlib==3.3.0
5 验证和测试
5.1 验证
修改路径下的配置文件 ultralytics-main/ultralytics/yolo/cfg/default.yaml 参数如下,要验证验证集,需将Val/Test settings下的split: val设置为val
mode: val
——————————————————————————
# Val/Test settings ----------------------------------
val: True # (bool) validate/test during training
split: val # (str) dataset split to use for validation
save_json: False # (bool) save results to JSON file
save_hybrid: False # (bool) save (labels + additional predictions)
conf: 0.25 # (float, optional) (default 0.25 predict, 0.001 val)
iou: 0.5 # (float) intersection over union (IoU) threshold for NMS
max_det: 300 # (int) maximum number of detections per image
half: False # (bool) use half precision (FP16)
dnn: False # (bool) use OpenCV DNN for ONNX inference
plots: True # (bool) save plots during train/val
执行
cd ultralytics-main/ultralytics/
yolo cfg=./yolo/cfg/default.yaml
5.2 测试
修改路径下的配置文件 ultralytics-main/ultralytics/yolo/cfg/default.yaml 参数如下,要验证测试集,需将Val/Test settings下的split: val改设置为test文章来源:https://www.toymoban.com/news/detail-662559.html
mode: val
——————————————————————————
# Val/Test settings ----------------------------------
val: True # (bool) validate/test during training
split: test # (str) dataset split to use for validation
执行文章来源地址https://www.toymoban.com/news/detail-662559.html
cd ultralytics-main/ultralytics/
yolo cfg=./yolo/cfg/default.yaml
或
yolo cfg = ./yolo/cfg/default.yaml task=detect mode=predict source=/home/mydata/ save_txt=True
到了这里,关于从0开始yolov8模型目标检测训练的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!