YOLOv8第Y7周:训练自己的数据集

一、下载YOLOv8

官网地址:【YOLOv8开源地址

二、准备工作

在主目录下创建paper_data文件夹,将自己的数据集放入此文件夹。
在这里插入图片描述
数据集:
在这里插入图片描述
在paper_data文件夹下创建一个包含main空文件夹的ImageSets文件夹。
在这里插入图片描述
在paper_data下创建一个split_train_val.py文件,其内容如下:

import os
import random
import argparse

parser = argparse.ArgumentParser()
# xml文件的地址,根据自己的数据进行修改 xml一般存放在Annotations下
parser.add_argument('--xml_path', default='E:/BaiduNetdiskDownload/ultralytics-main/paper_data/Annotations', type=str,
                    help='input txt label path')
# 数据集的划分,地址选择自己数据下的ImageSets/Main
parser.add_argument('--txt_path', default='E:/BaiduNetdiskDownload/ultralytics-main/paper_data/ImageSets/Main', type=str,
                    help='output txt label path')
opt = parser.parse_args()

trainval_percent = 1.0
train_percent = 8 / 9
xmlfilepath = opt.xml_path
txtsavepath = opt.txt_path
total_xml = os.listdir(xmlfilepath)
if not os.path.exists(txtsavepath):
    os.makedirs(txtsavepath)

num = len(total_xml)
list_index = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list_index, tv)
train = random.sample(trainval, tr)

file_trainval = open(txtsavepath + '/trainval.txt', 'w')
file_test = open(txtsavepath + '/test.txt', 'w')
file_train = open(txtsavepath + '/train.txt', 'w')
file_val = open(txtsavepath + '/val.txt', 'w')

for i in list_index:
    name = total_xml[i][:-4] + '\n'
    if i in trainval:
        file_trainval.write(name)
        if i in train:
            file_train.write(name)
        else:
            file_val.write(name)
    else:
        file_test.write(name)

file_trainval.close()
file_train.close()
file_val.close()
file_test.close()

运行后生成.txt文件。
再创建一个voc_label.py文件,其内容如下:

import xml.etree.ElementTree as ET
import os
from os import getcwd

sets = ['train', 'val', 'test']
classes = ["banana", "snake fruit", "dragon fruit", "pineapple"]
abs_path = os.getcwd()
print(abs_path)


def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return x, y, w, h


def convert_annotation(image_id):
    in_file = open('E:/BaiduNetdiskDownload/ultralytics-main/paper_data/Annotations/%s.xml' % (image_id), encoding='UTF-8')
    out_file = open('E:/BaiduNetdiskDownload/ultralytics-main/paper_data/labels/%s.txt' % (image_id), 'w')
    tree = ET.parse(in_file)
    root = tree.getroot()

    filename = root.find('filename').text
    filenameFormat = filename.split(".")[1]

    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)
    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classes or int(difficult) == 1:
            continue

        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
             float(xmlbox.find('ymax').text))
        b1, b2, b3, b4 = b
        # 标注越界修正
        if b2 > w:
            b2 = w
        if b4 > h:
            b4 = h
        b = (b1, b2, b3, b4)
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
    return filenameFormat


wd = getcwd()
for image_set in sets:
    if not os.path.exists('E:/BaiduNetdiskDownload/ultralytics-main/paper_data/labels/'):
        os.makedirs('E:/BaiduNetdiskDownload/ultralytics-main/paper_data/labels/')
    image_ids = open(
        'E:/BaiduNetdiskDownload/ultralytics-main/paper_data/ImageSets/Main/%s.txt' % (image_set)).read().strip().split()
    list_file = open('E:/BaiduNetdiskDownload/ultralytics-main/paper_data/%s.txt' % (image_set), 'w')
    for image_id in image_ids:
        filenameFormat = convert_annotation(image_id)
        list_file.write('E:/BaiduNetdiskDownload/ultralytics-main/paper_data/images/%s.%s\n' % (image_id, filenameFormat))
    list_file.close()

运行。
最后生成一个ab.yaml文件,内容如下:

train: ./train.txt
val: ./val.txt

nc: 4
names: ["banana", "snake fruit", "dragon fruit", "pineapple"]

三、运行

在此文件夹下打开cmd,激活环境后在cmd中输入:

yolo task=detect mode =train model=yolov8s.yaml data=E:\BaiduNetdiskDownload\ultralytics-main\paper_data\ab.yaml epochs=100 batch=4

打印如下:

Microsoft Windows [版本 10.0.22621.3007]
(c) Microsoft Corporation。保留所有权利。

E:\BaiduNetdiskDownload\ultralytics-main>conda activate pytorch_env

(pytorch_env) E:\BaiduNetdiskDownload\ultralytics-main>yolo task=detect mode =train model=yolov8s.yaml data=E:\BaiduNetdiskDownload\ultralytics-main\paper_data\ab.yaml epochs=10 batch=4

                   from  n    params  module                                       arguments
  0                  -1  1       928  ultralytics.nn.modules.conv.Conv             [3, 32, 3, 2]
  1                  -1  1     18560  ultralytics.nn.modules.conv.Conv             [32, 64, 3, 2]
  2                  -1  1     29056  ultralytics.nn.modules.block.C2f             [64, 64, 1, True]
  3                  -1  1     73984  ultralytics.nn.modules.conv.Conv             [64, 128, 3, 2]
  4                  -1  2    197632  ultralytics.nn.modules.block.C2f             [128, 128, 2, True]
  5                  -1  1    295424  ultralytics.nn.modules.conv.Conv             [128, 256, 3, 2]
  6                  -1  2    788480  ultralytics.nn.modules.block.C2f             [256, 256, 2, True]
  7                  -1  1   1180672  ultralytics.nn.modules.conv.Conv             [256, 512, 3, 2]
  8                  -1  1   1838080  ultralytics.nn.modules.block.C2f             [512, 512, 1, True]
  9                  -1  1    656896  ultralytics.nn.modules.block.SPPF            [512, 512, 5]
 10                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']
 11             [-1, 6]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 12                  -1  1    591360  ultralytics.nn.modules.block.C2f             [768, 256, 1]
 13                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']
 14             [-1, 4]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 15                  -1  1    148224  ultralytics.nn.modules.block.C2f             [384, 128, 1]
 16                  -1  1    147712  ultralytics.nn.modules.conv.Conv             [128, 128, 3, 2]
 17            [-1, 12]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 18                  -1  1    493056  ultralytics.nn.modules.block.C2f             [384, 256, 1]
 19                  -1  1    590336  ultralytics.nn.modules.conv.Conv             [256, 256, 3, 2]
 20             [-1, 9]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 21                  -1  1   1969152  ultralytics.nn.modules.block.C2f             [768, 512, 1]
 22        [15, 18, 21]  1   2147008  ultralytics.nn.modules.head.Detect           [80, [128, 256, 512]]
YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients, 28.8 GFLOPs

New https://pypi.org/project/ultralytics/8.1.2 available 😃 Update with 'pip install -U ultralytics'
Ultralytics YOLOv8.0.221 🚀 Python-3.8.17 torch-2.1.2+cpu CPU (12th Gen Intel Core(TM) i7-12700H)
engine\trainer: task=detect, mode=train, model=yolov8s.yaml, data=E:\BaiduNetdiskDownload\ultralytics-main\paper_data\ab.yaml, epochs=10, patience=50, batch=4, imgsz=640, save=True, save_period=-1, cache=False, device=None, workers=8, project=None, name=train7, exist_ok=False, pretrained=True, optimizer=auto, verbose=True, seed=0, deterministic=True, single_cls=False, rect=False, cos_lr=False, close_mosaic=10, resume=False, amp=True, fraction=1.0, profile=False, freeze=None, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, split=val, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, vid_stride=1, stream_buffer=False, visualize=False, augment=False, agnostic_nms=False, classes=None, retina_masks=False, show=False, save_frames=False, save_txt=False, save_conf=False, save_crop=False, show_labels=True, show_conf=True, show_boxes=True, line_width=None, format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=None, workspace=4, nms=False, lr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=7.5, cls=0.5, dfl=1.5, pose=12.0, kobj=1.0, label_smoothing=0.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0, cfg=None, tracker=botsort.yaml, save_dir=runs\detect\train7
Overriding model.yaml nc=80 with nc=4

                   from  n    params  module                                       arguments
  0                  -1  1       928  ultralytics.nn.modules.conv.Conv             [3, 32, 3, 2]
  1                  -1  1     18560  ultralytics.nn.modules.conv.Conv             [32, 64, 3, 2]
  2                  -1  1     29056  ultralytics.nn.modules.block.C2f             [64, 64, 1, True]
  3                  -1  1     73984  ultralytics.nn.modules.conv.Conv             [64, 128, 3, 2]
  4                  -1  2    197632  ultralytics.nn.modules.block.C2f             [128, 128, 2, True]
  5                  -1  1    295424  ultralytics.nn.modules.conv.Conv             [128, 256, 3, 2]
  6                  -1  2    788480  ultralytics.nn.modules.block.C2f             [256, 256, 2, True]
  7                  -1  1   1180672  ultralytics.nn.modules.conv.Conv             [256, 512, 3, 2]
  8                  -1  1   1838080  ultralytics.nn.modules.block.C2f             [512, 512, 1, True]
  9                  -1  1    656896  ultralytics.nn.modules.block.SPPF            [512, 512, 5]
 10                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']
 11             [-1, 6]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 12                  -1  1    591360  ultralytics.nn.modules.block.C2f             [768, 256, 1]
 13                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']
 14             [-1, 4]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 15                  -1  1    148224  ultralytics.nn.modules.block.C2f             [384, 128, 1]
 16                  -1  1    147712  ultralytics.nn.modules.conv.Conv             [128, 128, 3, 2]
 17            [-1, 12]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 18                  -1  1    493056  ultralytics.nn.modules.block.C2f             [384, 256, 1]
 19                  -1  1    590336  ultralytics.nn.modules.conv.Conv             [256, 256, 3, 2]
 20             [-1, 9]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 21                  -1  1   1969152  ultralytics.nn.modules.block.C2f             [768, 512, 1]
 22        [15, 18, 21]  1   2117596  ultralytics.nn.modules.head.Detect           [4, [128, 256, 512]]
YOLOv8s summary: 225 layers, 11137148 parameters, 11137132 gradients, 28.7 GFLOPs

TensorBoard: Start with 'tensorboard --logdir runs\detect\train7', view at http://localhost:6006/
Freezing layer 'model.22.dfl.conv.weight'
train: Scanning E:\BaiduNetdiskDownload\ultralytics-main\paper_data\labels... 177 images, 0 backgrounds, 0 corrupt: 100
train: New cache created: E:\BaiduNetdiskDownload\ultralytics-main\paper_data\labels.cache
val: Scanning E:\BaiduNetdiskDownload\ultralytics-main\paper_data\labels... 23 images, 0 backgrounds, 0 corrupt: 100%|█
val: New cache created: E:\BaiduNetdiskDownload\ultralytics-main\paper_data\labels.cache
Plotting labels to runs\detect\train7\labels.jpg...
optimizer: 'optimizer=auto' found, ignoring 'lr0=0.01' and 'momentum=0.937' and determining best 'optimizer', 'lr0' and 'momentum' automatically...
optimizer: AdamW(lr=0.00125, momentum=0.9) with parameter groups 57 weight(decay=0.0), 64 weight(decay=0.0005), 63 bias(decay=0.0)
Image sizes 640 train, 640 val
Using 0 dataloader workers
Logging results to runs\detect\train7
Starting training for 10 epochs...
Closing dataloader mosaic

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
       1/10         0G      2.987      4.406      4.395          2        640: 100%|██████████| 45/45 [00:59<00:00,  1.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69   0.000383     0.0278   0.000283   6.28e-05

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
       2/10         0G      3.041      3.887      4.048          3        640: 100%|██████████| 45/45 [00:58<00:00,  1.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69   0.000473     0.0139    0.00025    2.5e-05

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
       3/10         0G      2.812      3.653      3.851          3        640: 100%|██████████| 45/45 [00:58<00:00,  1.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69    0.00465      0.292     0.0793     0.0374

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
       4/10         0G      2.716      3.417      3.687          3        640: 100%|██████████| 45/45 [00:58<00:00,  1.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69     0.0418      0.323      0.105     0.0329

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
       5/10         0G      2.638      3.253      3.546          3        640: 100%|██████████| 45/45 [01:00<00:00,  1.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69     0.0551      0.213     0.0887     0.0242

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
       6/10         0G      2.479      2.913      3.448          3        640: 100%|██████████| 45/45 [01:00<00:00,  1.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69      0.261      0.434      0.364       0.15

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
       7/10         0G      2.373      2.639      3.285          3        640: 100%|██████████| 45/45 [00:57<00:00,  1.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69      0.698       0.47      0.494      0.169

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
       8/10         0G      2.271      2.438      3.179          3        640: 100%|██████████| 45/45 [00:57<00:00,  1.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69      0.666      0.348      0.459      0.176

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
       9/10         0G      2.194      2.293      3.013          3        640: 100%|██████████| 45/45 [00:56<00:00,  1.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69      0.467      0.679      0.638      0.307

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
      10/10         0G      2.092      2.183       2.91          3        640: 100%|██████████| 45/45 [00:56<00:00,  1.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69      0.605        0.6      0.701      0.364

10 epochs completed in 0.170 hours.
Optimizer stripped from runs\detect\train7\weights\last.pt, 22.5MB
Optimizer stripped from runs\detect\train7\weights\best.pt, 22.5MB

Validating runs\detect\train7\weights\best.pt...
Ultralytics YOLOv8.0.221 🚀 Python-3.8.17 torch-2.1.2+cpu CPU (12th Gen Intel Core(TM) i7-12700H)
YOLOv8s summary (fused): 168 layers, 11127132 parameters, 0 gradients, 28.4 GFLOPs
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:02<0
                   all         23         69      0.604        0.6      0.703      0.362
                banana         23         13       0.47      0.846      0.806       0.49
           snake fruit         23         23      0.678      0.275      0.404      0.139
          dragon fruit         23         15      0.721          1      0.987      0.566
             pineapple         23         18      0.548      0.278      0.615      0.254
Speed: 0.7ms preprocess, 78.0ms inference, 0.0ms loss, 1.8ms postprocess per image
Results saved to runs\detect\train7
💡 Learn more at https://docs.ultralytics.com/modes/train

在这里插入图片描述

(注:环境有些小异常,没有调用GPU,所以使用cpu时epoch数设的较小,见谅。)

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值