Pytorch使用yolov3训练自己的数据进阶

多classes的训练

接上一次的博文,这两天我又进行了自己更复杂一点的数据集的制作和训练,算是对上一篇博文的补充,这次讲一讲对于多目标的目标检测的一些重要步骤。

  1. 多目标数据集的准备Pytorch使用yolov3训练自己的数据进阶_第1张图片voc_label.py
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
 
sets = ['train', 'test','val']
 
classes = ["car","ad", "bus", "chair", "didi", "group", "hello", "mobike", "motorbike","other", "outdoor", "rider", "shed", "stall", "table", "tricycle", "truck"]
 
 
def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    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('data/Annotations/%s.xml' % (image_id))
    out_file = open('data/labels/%s.txt' % (image_id), 'w')
    tree = ET.parse(in_file)
    root = tree.getroot()
    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))
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
 
 
wd = getcwd()
print(wd)
for image_set in sets:
    if not os.path.exists('data/labels/'):
        os.makedirs('data/labels/')
    image_ids = open('data/ImageSets/Main/%s.txt' % (image_set)).read().strip().split()
    list_file = open('data/%s.txt' % (image_set), 'w')
    for image_id in image_ids:
        list_file.write('data/images/%s.jpg\n' % (image_id))
        convert_annotation(image_id)
    list_file.close()

在liunx下运行py文件的方法:python voc_label.py

多目标检测的关键点就在于脚本文件的classes处,需要检测多少个目标对象就要设置多少个分类,这里我们进行17个目标对象的目标检测。
2. 开始训练
2.1训练参数修改
在开始训练之前需要修改train的参数,尤其是cfg文件,如果不做修改,则会报错误,一般情况下yolo默认的是spp的cfg文件,所以会报不匹配的错误,这里我们需要将weights更改为与之对应的,因为本人的显卡内存不足,而且spp是一个三层yolo的模型,我无法使用,所以我一直使用的是tiny模型。tiny虽然轻量便捷快速,但是精度还是不够高的。Pytorch使用yolov3训练自己的数据进阶_第2张图片
tip1:有一个要注意的点,如果是使用服务器跑深度学习,那么很可能出现cuda out of memory的错误,那么就要注意gpu的内存使用情况,可以使用:

nvidia-smi

查看显卡内存使用情况,如果有一些没有退出存储的进程,我们可以使用:

kill -9 pid

杀死这些进程,释放空间
2.2训练文件准备
yolo.names:
这里就是和单class训练区别很大的地方,这个文件一定要注意格式,这里我把我的names文件贴在这里供大家参考:

ad
bus
car
chair
didi
group
hello
mobike
motorbike
other
outdoor
rider
shed
stall
table
tricycle
truck

yolo.data:

classes=17
train=data/train.txt
valid=data/val.txt
names=data/yolo.names
backup=backup/

我们需要对应names文件,修改data文件中的classes和names属性。
yolo-tiny.cfg:
这里我们最为重要的就是对于yolo层的classes还有yolo上层的卷积层的filters值的修改:
filters=66 #3(class + 4 + 1)
我在这里训练了17个类,那就是class=17,在做运算得到filters=66

[net]
batch=1
subdivisions=1
width=416
height=416
channels=3
momentum=0.9
decay=0.0005
angle=0
saturation = 1.5
exposure = 1.5
hue=.1
learning_rate=0.001
burn_in=1000
max_batches = 500200
policy=steps
steps=400000,450000
scales=.1,.1 
[convolutional]
batch_normalize=1
filters=16
size=3
stride=1
pad=1
activation=leaky 
[maxpool]
size=2
stride=2 
[convolutional]
batch_normalize=1
filters=32
size=3
stride=1
pad=1
activation=leaky 
[maxpool]
size=2
stride=2 
[convolutional]
batch_normalize=1
filters=64
size=3
stride=1
pad=1
activation=leaky 
[maxpool]
size=2
stride=2 
[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky 
[maxpool]
size=2
stride=2 
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky 
[maxpool]
size=2
stride=2 
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky 
[maxpool]
size=2
stride=1 
[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky 
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky 
[convolutional]
size=1
stride=1
pad=1
filters=66
activation=linear 
[yolo]
mask = 3,4,5
anchors = 10,14,  23,27,  37,58,  81,82,  135,169,  344,319
classes=17
num=6
jitter=.3
ignore_thresh = .7
truth_thresh = 1
random=1 
[route]
layers = -4 
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky 
[upsample]
stride=2 
[route]
layers = -1, 8 
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky 
[convolutional]
size=1
stride=1
pad=1
filters=66
activation=linear 
[yolo]
mask = 0,1,2
anchors = 10,14,  23,27,  37,58,  81,82,  135,169,  344,319
classes=17
num=6
jitter=.3
ignore_thresh = .7
truth_thresh = 1
random=1

如果我们使用yolov3-spp.cfg文件进行训练,那么spp这里有三层yolo,那就要修改三层的卷积层[convolutional],对应公式也不同:
(classes + 5)* anchors_of_this_yolo
anchors_of_this_yolo代表该层yolo的anchor数目,anchors两个逗号为一个anchor。
在我们调整完成后,就可以开始训练了,训练完成的模型best.pt就会放在yolov3的weights文件夹下,以方便我们detect时使用。
tip2:这里还要提及一下,voc_label.py中的classes要和names中的classes对应顺序,要不会出现标记错误的问题。
3.训练结果
将待检测的图片放入data\sample文件夹下,基于训练获得的weights文件夹下的best.pt模型文件,运行detect.py即可完成检测。

python detect.py --names data/yolo.names --source data/samples/ --cfg cfg/yolov3-tiny.cfg --weights weights/best.pt

Pytorch使用yolov3训练自己的数据进阶_第3张图片
4.总结
这就是本次多目标的检测成果,精度还是可以的,epochs了150次,精度是有提升的,大家可以在训练时注意Giou,cls和obj参数,基本都是越低越精确的。
最后的最后要感谢对我提供了帮助的师姐@ToLiveXX
和让我获益匪浅的文章如何使用Pytorch实现YOLOv3训练自己的数据集(详尽版)

你可能感兴趣的:(目标检测,人工智能,深度学习,深度学习,神经网络,python,人工智能,计算机视觉)