学习深度学习目标检测的yolo模型有一段时间了,但是一直没有真正接触最底层的网络构建和训练,之前在Darknet官网上看到有关于训练yolo模型的方法,但是是基于linux操作系统的,那时候还没有接触虚拟机和双系统,于是就搁浅了。其实有不少深度学习框架都已经对yolo进行了复现,比如Tensorflow、Keras、Pytorch,Windows系统下也可以对Darknet框架下的yolo模型进行训练。
选择了Keras和Darknet进行了尝试,先把自己使用keras的方法记录下来,之后再记录Darknet。
一些参考资料:
Keras框架下训练yolo:
https://blog.csdn.net/u012746060/article/details/81183006
https://blog.csdn.net/Patrick_Lxc/article/details/80615433
https://blog.csdn.net/mingqi1996/article/details/83343289
https://blog.csdn.net/qq_39622065/article/details/86174142
windows系统,Darknet框架下训练yolo:
https://blog.csdn.net/maweifei/article/details/81137563
https://blog.csdn.net/kk123k/article/details/86696540
https://blog.csdn.net/syyyy712/article/details/79632016
https://blog.csdn.net/congcong7267/article/details/82981084
https://blog.csdn.net/HelloCode1900/article/details/80906141
1、Anaconda(Python 3.6)
内部需包含的库有:
(1)tensorflow-gpu
(2)keras
2、Pycharm
1、下载yolov3_keras版本的源代码:https://github.com/qqwweee/keras-yolo3
(解压得到keras-yolo3-master文件夹)
2、下载预训练权重yolov3.weights:https://pjreddie.com/media/files/yolov3.weights
(放入keras-yolo3-master文件夹中)
3、在Anaconda环境中执行如下命令,将权重文件weights转换为适用于keras的h5文件:
python convert.py yolov3.cfg yolov3.weights model_data/yolo.h5
4、h5文件转换完成后,在keras-yolo3-master文件夹中找到yolo.py文件,在该文件最后加上以上代码,并使用命令行运行:
def detect_img(yolo):
while True:
img = input('Input image filename:')
try:
image = Image.open(img)
except:
print('Open Error! Try again!')
continue
else:
r_image = yolo.detect_image(image)
r_image.show()
yolo.close_session()
if __name__ == '__main__':
detect_img(YOLO())
命令行:
python yolo.py
程序会提示你输入图片路径及名称,输入正确后即可显示模型的识别结果
1、创建文件结构目录
(1)在keras-yolo3-master文件夹中创建如下结构的文件夹:
JPEGImages用于存放你的图片;Annotations用于存放标注文件(xml格式,Darknet框架下需要转换为txt格式);ImageSets/Main用于存放自动生成的训练集、验证集和测试集的图片路径的txt文件;
(2)标注数据:
LabelImg软件下载:https://github.com/tzutalin/labelImg
(解压得到labelImg-master文件夹)
在Anaconda环境中切换到该文件夹目录,并且安装好依赖项:pyqt5和lxml;安装完成后执行如下命令即可打开软件使用:
pip install pyqt5
pip install lxml
pyrcc5 -0 resources.py resources.qrc (该句执行完后没有输出)
python labelImg.py
Open Dir打开图片文件夹目录,Create RectBox创建标注框,Ctrl-S保存xml文件至Annotations文件夹;
(3)在keras-yolo3-master文件夹中找到voc_annotation.py文件,将classes改为自己的类别:
(4)在创建的目录结构中创建一个makedataset.py文件,在ImageSets/Main/文件夹下添加trainval.txt,train.txt,val.txt,test.txt,添加以下代码,并运行,完成数据集的制作:
(关于训练集和验证集的划分比例应根据样本数据确定,如果样本较少,建议改为0.1和0.9)
import os
import random
trainval_percent = 0.2
train_percent = 0.8
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()
2、
在keras-yolo3-master文件夹中找到yolo3.cfg文件,搜索yolo,一共出现三次,对每个yolo块都作如下修改:
filter=(5+classes)*3 根据自己的类别情况进行计算
classes 根据自己的分类数设置
random 默认为1,如果显存小于4G建议改为0
3、
在keras-yolo3-master/model_data文件夹中找到voc_classes.txt文件,改为自己的类别:
以上所有准备工作全部完成后,就可以进行最后一步训练了。
1、在keras-yolo3-master文件夹下建立文件夹目录:logs/000,用于保存训练生成的模型;
2、在keras-yolo3-master文件夹下找到 train.py,替换为如下代码开始训练:
"""
Retrain the YOLO model for your own dataset.
"""
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping
from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss
from yolo3.utils import get_random_data
def _main():
annotation_path = '2007_train.txt'
log_dir = 'logs/000/'
classes_path = 'model_data/voc_classes.txt'
anchors_path = 'model_data/yolo_anchors.txt'
class_names = get_classes(classes_path)
anchors = get_anchors(anchors_path)
input_shape = (416,416) # multiple of 32, hw
model = create_model(input_shape, anchors, len(class_names) )
train(model, annotation_path, input_shape, anchors, len(class_names), log_dir=log_dir)
def train(model, annotation_path, input_shape, anchors, num_classes, log_dir='logs/'):
model.compile(optimizer='adam', loss={
'yolo_loss': lambda y_true, y_pred: y_pred})
logging = TensorBoard(log_dir=log_dir)
checkpoint = ModelCheckpoint(log_dir + "ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5",
monitor='val_loss', save_weights_only=True, save_best_only=True, period=1)
batch_size = 10
val_split = 0.1
with open(annotation_path) as f:
lines = f.readlines()
np.random.shuffle(lines)
num_val = int(len(lines)*val_split)
num_train = len(lines) - num_val
print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))
model.fit_generator(data_generator_wrap(lines[:num_train], batch_size, input_shape, anchors, num_classes),
steps_per_epoch=max(1, num_train//batch_size),
validation_data=data_generator_wrap(lines[num_train:], batch_size, input_shape, anchors, num_classes),
validation_steps=max(1, num_val//batch_size),
epochs=500,
initial_epoch=0)
model.save_weights(log_dir + 'trained_weights.h5')
def get_classes(classes_path):
with open(classes_path) as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names
def get_anchors(anchors_path):
with open(anchors_path) as f:
anchors = f.readline()
anchors = [float(x) for x in anchors.split(',')]
return np.array(anchors).reshape(-1, 2)
def create_model(input_shape, anchors, num_classes, load_pretrained=False, freeze_body=False,
weights_path='model_data/yolo_weights.h5'):
K.clear_session() # get a new session
image_input = Input(shape=(None, None, 3))
h, w = input_shape
num_anchors = len(anchors)
y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \
num_anchors//3, num_classes+5)) for l in range(3)]
model_body = yolo_body(image_input, num_anchors//3, num_classes)
print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))
if load_pretrained:
model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)
print('Load weights {}.'.format(weights_path))
if freeze_body:
# Do not freeze 3 output layers.
num = len(model_body.layers)-7
for i in range(num): model_body.layers[i].trainable = False
print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))
model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',
arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})(
[*model_body.output, *y_true])
model = Model([model_body.input, *y_true], model_loss)
return model
def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):
n = len(annotation_lines)
np.random.shuffle(annotation_lines)
i = 0
while True:
image_data = []
box_data = []
for b in range(batch_size):
i %= n
image, box = get_random_data(annotation_lines[i], input_shape, random=True)
image_data.append(image)
box_data.append(box)
i += 1
image_data = np.array(image_data)
box_data = np.array(box_data)
y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)
yield [image_data, *y_true], np.zeros(batch_size)
def data_generator_wrap(annotation_lines, batch_size, input_shape, anchors, num_classes):
n = len(annotation_lines)
if n==0 or batch_size<=0: return None
return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)
if __name__ == '__main__':
_main()
训练过程中可以看到gpu的运行情况:
由于只是以学习为目的,所以选取的样本较少(只有十几张图片),迭代次数只有500次,最后的loss有点大,预测结果很一般。
使用Darknet训练时,增大了样本数和迭代次数,loss变小了很多,预测结果相对而言好了很多。
其他参考文章:
标注数据软件使用:
https://blog.csdn.net/u012746060/article/details/81016993
https://www.cnblogs.com/Terrypython/p/9577657.html
Juliet 于 2019.4