欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Ubuntu16.04下实现darknet-yolov3训练自己的数据(含loss图、mAP计算)

程序员文章站 2022-09-14 13:20:58
记录一下本地编译darknet并用自己的数据集来训练yolov3的过程,最后补充了mAP的计算方法。1.环境配置首先CUDA和Cudnn是必备的,安装有很多教程就不多写了,opencv安装比较麻烦可以不用装2.本地编译darknet从github获取darknetgit clone https://github.com/pjreddie/darknetcd darknet修改Makefile文件GPU=1 #如果使用GPU设置为1,CPU设置为0CUDNN=1 #如果使...

记录一下本地编译darknet并用自己的数据集来训练yolov3的过程,最后补充了mAP的计算方法。

1.环境配置

首先CUDA和Cudnn是必备的,安装有很多教程就不多写了,opencv安装比较麻烦可以不用装

2.本地编译darknet

从github获取darknet

git clone https://github.com/pjreddie/darknet
cd darknet

修改Makefile文件

GPU=1 #如果使用GPU设置为1,CPU设置为0
CUDNN=1  #如果使用CUDNN设置为1,否则为0
OPENCV=0 #如果调用摄像头,还需要设置OPENCV为1,否则为0
OPENMP=0  #如果使用OPENMP设置为1,否则为0
DEBUG=0  #如果使用DEBUG设置为1,否则为0

在darknet文件夹下编译

make

下载yolov3的预训练模型

wget https://pjreddie.com/media/files/yolov3.weights

测试是否编译成功

./darknet detector test cfg/coco.data cfg/yolov3.cfg yolov3.weights data/dog.jpg

3.准备数据集

一般是先准备VOC格式的数据集,然后通过一些脚本文件转化成可用于训练的版本

在darknet文件夹下创建dateset文件夹,内部结构为:

dataset
  ---JPEGImages#存放原图像(名字只要和xml对应就行,不用规范化)
 
  ---Annotations#存放图像对应的xml文件
 
  ---ImageSets/Main # 存放训练/验证图像的txt文件(脚本生成)

将图像数据放入JPEGImages,xml的标注文件放入Annotations,然后新建一个py文件,随便命名(如:maketxt.py)

import os
import random

trainval_percent = 0.1
train_percent = 0.9
xmlfilepath = 'Annotations'
txtsavepath = 'ImageSets\Main'
total_xml = os.listdir(xmlfilepath)
num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)

ftrainval = open('ImageSets/Main/trainval.txt', 'w')
ftest = open('ImageSets/Main/test.txt', 'w')
ftrain = open('ImageSets/Main/train.txt', 'w')
fval = open('ImageSets/Main/val.txt', 'w')

for i in list:
    name = total_xml[i][:-4] + '\n'
    if i in trainval:
        ftrainval.write(name)
        if i in train:
            ftest.write(name)
        else:
            fval.write(name)
    else:
        ftrain.write(name)

ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

运行后会在ImageSets/Main路径下生成train.txt,val.txt,test.txt和trainval.txt四个必备的txt文件

转换VOC格式的数据集为darknet的格式(点坐标进行归一化https://blog.csdn.net/hesongzefairy/article/details/104443573

在darknet文件夹中创建一个py文件,随便命名,需要修改的地方看注释(修改自darknet/scripts/voc_label.py)

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
 
#源代码sets=[('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
sets=[('dataset', 'train')]  # 改成自己建立的文件夹名字,若生成测试的train改成test
 
classes = ["person", "car"] # 改成自己的类别,和fastrcnn系不同,不用+1
 
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(year, image_id):
    in_file = open('myData/Annotations/%s.xml'%(image_id))  VOCdevkit/VOC%s/Annotations/%s.xml
    out_file = open('myData/labels/%s.txt'%(image_id), 'w')  VOCdevkit/VOC%s/labels/%s.txt
    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()
 
# for year, image_set in sets:
#    if not os.path.exists('/labels/'):  # 改成自己建立的myData
#       os.makedirs('myData/labels/')
#    image_ids = open('myData/ImageSets/Main/%s.txt'%(image_set)).read().strip().split()
#    list_file = open('myData/%s_%s.txt'%(year, image_set), 'w')
#    for image_id in image_ids:
#        list_file.write('%s/myData/JPEGImages/%s.jpg\n'%(wd, image_id))
#        convert_annotation(year, image_id)
#    list_file.close()

运行之后,会在dataset文件夹中生成dataset_train.txt(记录了训练数据的绝对路径)

4.修改配置文件

修改cfg/voc.data

classes= 2 #改为自己的分类个数

train  = /home/XXX/darknet/dataset/dataset_train.txt # 记录绝对路径的txt
names = /home/XXX/darknet/dataset/myData.names       # 自己创建,记录类别名称
backup = /home/XXX/darknet/dataset/weights           # 权重保存路径

修改cfg/yolov3-voc.cfg

通过vim打开,用/yolo搜索

对每个yolo搜索点上的conv层,修改filter为3*(5+len(classes)),yolo层修改classes即可

同时文件最上部分可修改一些训练参数

# Testing            ### 测试模式                                          
# batch=1
# subdivisions=1
# Training           ### 训练模式,每次前向的图片数目 = batch/subdivisions 
batch=64
subdivisions=16
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 = 50200  ### 迭代次数                                          
policy=steps         ### 学习率策略 
steps=40000,45000    ### 学习率变动步长

5.开始训练

准备darknet权重

wget https://pjreddie.com/media/files/darknet53.conv.74

启动训练(指定gpu)

./darknet detector train cfg/voc.data cfg/yolov3-voc.cfg darknet53.conv.74 -gpu 1

启动训练(保存训练log,用于后续画图)

./darknet detector train cfg/voc.data cfg/yolov3-voc.cfg darknet53.conv.74 -gpu 1 2>&1 | tee logs/train_yolov3.log

从停止处重新训练

./darknet detector train cfg/voc.data cfg/yolov3-voc.cfg darknet53.conv.74 -gups 0 myData/weights/my_yolov3.backup

6.训练完成后加载log文件画loss图和iou图

# coding=utf-8
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import logging
 
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
 
 
class Yolov3LogVisualization:
 
    def __init__(self, log_path, result_dir):
 
        self.log_path = log_path
        self.result_dir = result_dir
 
    def extract_log(self, save_log_path, key_word):
        with open(self.log_path, 'r') as f:
            with open(save_log_path, 'w') as train_log:
                next_skip = False
                for line in f:
                    if next_skip:
                        next_skip = False
                        continue
                    # 去除多gpu的同步log
                    if 'Syncing' in line:
                        continue
                    # 去除除零错误的log
                    if 'nan' in line:
                        continue
                    if 'Saving weights to' in line:
                        next_skip = True
                        continue
                    if key_word in line:
                        train_log.write(line)
        f.close()
        train_log.close()
 
    def parse_loss_log(self, log_path, line_num=2000):
        # 用于设置忽略前多少步,上千几百的太大了,所以从几一下开始。 
        result = pd.read_csv(log_path,skiprows=[x for x in range(line_num) if (x<1500)],
                             error_bad_lines=False, names=['loss', 'avg', 'rate', 'seconds', 'images'])
        result['loss'] = result['loss'].str.split(' ').str.get(1)
        result['avg'] = result['avg'].str.split(' ').str.get(1)
        result['rate'] = result['rate'].str.split(' ').str.get(1)
        result['seconds'] = result['seconds'].str.split(' ').str.get(1)
        result['images'] = result['images'].str.split(' ').str.get(1)
 
        result['loss'] = pd.to_numeric(result['loss'])
        result['avg'] = pd.to_numeric(result['avg'])
        result['rate'] = pd.to_numeric(result['rate'])
        result['seconds'] = pd.to_numeric(result['seconds'])
        result['images'] = pd.to_numeric(result['images'])
        return result
 
    def gene_loss_pic(self, pd_loss):
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        ax.plot(pd_loss['avg'].values, label='avg_loss')
        ax.legend(loc='best')
        ax.set_title('The loss curves')
        ax.set_xlabel('batches')
        fig.savefig(self.result_dir + '/avg_loss')
        logger.info('save iou loss done')
 
    def loss_pic(self):
        train_log_loss_path = os.path.join(self.result_dir, 'train_log_loss.txt')
        self.extract_log(train_log_loss_path, 'images')
        pd_loss = self.parse_loss_log(train_log_loss_path)
        self.gene_loss_pic(pd_loss)
 
    def parse_iou_log(self, log_path, line_num=2000):
        result = pd.read_csv(log_path, skiprows=[x for x in range(line_num) if (x % 10 == 0 or x % 10 == 9)],
                             error_bad_lines=False,
                             names=['Region Avg IOU', 'Class', 'Obj', 'No Obj', 'Avg Recall', 'count'])
        result['Region Avg IOU'] = result['Region Avg IOU'].str.split(': ').str.get(1)
        result['Class'] = result['Class'].str.split(': ').str.get(1)
        result['Obj'] = result['Obj'].str.split(': ').str.get(1)
        result['No Obj'] = result['No Obj'].str.split(': ').str.get(1)
        result['Avg Recall'] = result['Avg Recall'].str.split(': ').str.get(1)
        result['count'] = result['count'].str.split(': ').str.get(1)
 
        result['Region Avg IOU'] = pd.to_numeric(result['Region Avg IOU'])
        result['Class'] = pd.to_numeric(result['Class'])
        result['Obj'] = pd.to_numeric(result['Obj'])
        result['No Obj'] = pd.to_numeric(result['No Obj'])
        result['Avg Recall'] = pd.to_numeric(result['Avg Recall'])
        result['count'] = pd.to_numeric(result['count'])
        return result
 
    def gene_iou_pic(self, pd_loss):
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        ax.plot(pd_loss['Region Avg IOU'].values, label='Region Avg IOU')
        # ax.plot(result['Class'].values,label='Class')
        # ax.plot(result['Obj'].values,label='Obj')
        # ax.plot(result['No Obj'].values,label='No Obj')
        # ax.plot(result['Avg Recall'].values,label='Avg Recall')
        # ax.plot(result['count'].values,label='count')
        ax.legend(loc='best')
        ax.set_title('The Region Avg IOU curves')
        ax.set_xlabel('batches')
        fig.savefig(self.result_dir + '/region_avg_iou')
        logger.info('save iou pic done')
 
    def iou_pic(self):
        train_log_loss_path = os.path.join(self.result_dir, 'train_log_iou.txt')
        self.extract_log(train_log_loss_path, 'IOU')
        pd_loss = self.parse_iou_log(train_log_loss_path)
        self.gene_iou_pic(pd_loss)
 
 
if __name__ == '__main__':
    log_path = '/home/studieren/论文/darknet/log_analysis/train_yolov3.log'
    result_dir = '/home/studieren/论文/darknet/log_analysis'
    logVis = Yolov3LogVisualization(log_path, result_dir)
    logVis.loss_pic()
    logVis.iou_pic()

7.mAP计算

参考方法https://blog.csdn.net/Gentleman_Qin/article/details/84800188

这个代码运行需要python2.7,但是现在都是python3了,谁还用2

需要修改的地方:

1. print的用法,注释掉或者修改成python3格式都可以

2. 读写文件的方法,open仅用r或者w会报错,改成rb和wb(readline的位置不要改)

具体的根据报错来修改一下就行了,最终会输出AP值

 

本文地址:https://blog.csdn.net/hesongzefairy/article/details/107183162