参考:
0.背景
最近做了一个机器学习的大作业,接触了YOLOv3的学习框架,折腾了好长时间,分享下拿轮子直接用的流程。
1.环境准备
我的环境:Anancanda+Pycharm+TensorFlow(CPU)+Keras+YOLOv3,win10系统。
Anacanda:可以视作一个下载了很多包的Python,常用作数据处理与分析。我的版本:2019.10版本(到官网下载最新版即可)。
官网https://www.anaconda.com/
网盘链接:https://pan.baidu.com/s/1-AAAhOxB5gheO9jN4CG32w
提取码:40oi
Pycharm:经典PythonIDE(集成开发环境),功能全面。
官网https://www.jetbrains.com/pycharm/ 下载即可
网盘链接:https://pan.baidu.com/s/1cSRbZUSNCA8_ont_oKwvVQ
提取码:vczz
TensorFlow:最广泛的经典机器学习系统,谷爹开发维护。我的版本1.13.1。
Keras:基于Python的深度学习库。Keras是一个用Python编写的高级神经网络API,它能够以TensorFlow作为后端运行。我的版本:2.2.4。keras和TensorFlow框架要对应上,不然可能报错.
参考网站:https://docs.floydhub.com/guides/environments/
YOLOv3:深度学习框架.
下载地址:https://github.com/qqwweee/keras-yolo3。
说说为啥用YOLOv3,就一个字:快!
第二象限的曲线简直就是对其他框架的嘲讽233
2.环境搭建
Anaconda一路next就可以了,最后开始界面如下:
’
只会用到Anaconda Navigator和Prompt(主要),Prompt类似命令行,用来安装Python包。
Pycharm一般也一路next,勾选时参考下面选项:
在创建Pycharm项目时,打开setting
在Project Interpreter中选择Anaconda的Python即可
TensorFlow安装:Anaconda Prompt中直接pip install tensorflow==1.13.1
Keras安装:Anaconda Prompt中直接pip install keras==2.2.4
3.开始学习
1)建立VOC2007文件夹结构,建立多个空文件夹如下,外面再包一层VOCdevkit文件夹,放在keras-yolo3-master文件夹内,非常easy。
2)把所有文件夹放入JPEGImages里面。
3)给想要做的数据打标签,推荐LabelImg工具,链接:https://pan.baidu.com/s/1GJFYcFm5Zlb-c6tIJ2N4hw 密码:h0i5。生成的xml文件与图片文件名相同。xml文件放入Annatations文件夹中。
4)VOC文件夹下建立test.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()
用pycharm打开YOLO3的项目,接下来都在pycharm内操作。运行test.py,生成文件4个txt文件,这里面整理你的标签信息,这样VOC2007数据集就做完了。但是,YOLO框架不直接用这个数据集(惊不惊喜意不意外)。
5)生成YOLO需要的txt文件。keras-yolo3-master目录下有一个voc_annotation.py的程序,修改它,把classes改为你要分的类别。YOLO本身带有80个类别,如果你要训练的恰好在这里吗,直接用吧,去YOLO官网https://pjreddie.com/darknet/yolo/下载配置的权重文件yolo3.weight。这里是训练自己的模型,就需要自行分类。
运行之后,会在主目录下多生成三个txt文件
有3个2007开头的txt文件:007_train.txt,2007_test.txt,2007_val.txt。删除的是这3个txt文件文件名中的“2007_”这部分,而不是其他。也就变成了:train.txt,test.txt,val.txt
6)修改参数文件yolo3.cfg,有三处yolo。
filter改成3*(5+类别数),classes改成类别数,random改成0(电脑烂的话)
所以如果分两类,改为:
filters=21,classes=2,random=0
7)修改model_data下的voc和coco文件,放入自己的类别名,与voc_annotation.py类别保持一致。
8)修改train.py,生成权重文件。train代码如下,epoch是循环次数,input_shape是图片尺寸,可以修改,但一定要是32的整倍数,logs_dir是权重文件生成的路径,换成别的地方也可以。运行后loss结果达到十几就可以了。(嗯,一开始我电脑稀烂,就循环了10次,loss达到100+,结果是能检测出来大部分,但精准度稀烂)
"""
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 = '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 = 8
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=300,
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()
9)把生成的trained_weights.h5文件复制黏贴到keras-yolo3-master/model_data文件夹下,改名为yolo.h5。pycharm终端Terminal输入python yolo_video.py --image,开始训练。理想效果:
10)回顾下来,打标签(必须的)和训练权重(电脑原因)花时间最长。最后只想说一句,GPU加速他不香吗?
大年初一了,开始正式写些自己学过用过的知识,梳理自己的知识脉络,也检查检查自己的抖动,教学相长,欢迎大家多多批评指正~
最后,我今天收到红包了,开心哭了~