我首先尝试一下keras-yolo3的可靠性,我首先下载了keras-yolo3的官方训练好的权重文件,附链接:https://pjreddie.com/media/files/yolov3.weights,而后将darknet的yolo转换为可以用于keras的h5文件,生成的h5被保存在model_data下。命令及结果如下:
从训练文件的源代码可以看出,yolov3.weights中只训练了aeroplane, bicycle, bird,boat, bottle, bus, car, cat, chair, cow, diningtable, dog, horse, motorbike,person, pottedplant, sheep, sofa,train, tvmonitor,下面我们拿一张汽车car图片作为例子试验一下,由于目标是图片,执行命令为pythno3 yolo_video.py --image:
效果十分出众,那么我们自己训练的数据集会不会也可以达到这样的效果呢?
我们下面开始训练自己的数据集:
1.首先对自己的少量数据进性增强(数据多的就不用了)
只要写代码对图像进行操作即可,参考文章:https://www.cnblogs.com/siyuan1998/p/10686616.html,我这里主要是进行了翻转、拉伸和裁剪,从100多张图片扩充到了900多张,拉伸的效果像这样:
2.然后对得到的数据集进行标注,这里用了GitHub上的一个开源工具LabelImg进行了快速标注,不够900多张图片自己一个人标注也是要一天的,再标注的过程中,主要是为了生成xml文件,对应每一张被标注的图片,内含信息是目标的位置坐标,以及目标的标签(比如:tank):
3.生成对应配置文件:
首先在keras-yolo3文件夹中新建VOCdevkit文件夹,在VOCdevkit中再新建VOC2007文件夹,最后在VOC2007文件夹中再新建Annotations、ImageSets、JPEGImages、SegmentationClass、SegmentationObject文件夹,路径很重要,具体见图:
然后把训练用的数据集放入JPEGImages,把xml文件放入Annotations,然后在ImageSets中再新建三个文件夹:
然后执行下面代码使在Main文件中生成图像的配置文件:
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()
下一步,打开keras-yolo3文件夹中的voc_annotation.py文件,classes类改写我们刚刚写的标签:
运行voc_annotation.py,将生成三个txt文本文件,手动删除文件头前缀2007_。
4.修改参数文件yolo3.cfg:
打开keras-yolo3文件夹中的yolov3.cfg文件,搜索[yolo]关键词,共有三处位置,分别修改其下3个参数:
filters:3*(5+len(classes))
classes: len(classes) = 1,这里以只有一个tank标签为例
random:原来是1,显存小改为0
然后修改model_data下coco,voc这两个文件,放入你的类别,这里存入tank。
5.修改训练代码train.py,开始训练:
keras-yolo3自带的train.py会加载预先对coco数据集已经训练完成的yolo3权重文件,并冻结了开始到最后倒数第N层,以及在训练中只会保存最后一次训练完毕的数据,没办法在规定次数中保存训练数据,这里对代码进行了修改,更正了上述问题:
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/222/'
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)
tensorboard = TensorBoard(log_dir=log_dir)
checkpoint = ModelCheckpoint(log_dir + "self_trained.h5",
monitor='val_loss', save_weights_only=True, save_best_only=True,
period=1)
callbacks_list = [tensorboard,checkpoint]
batch_size = 10 #you can fix it
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,
callbacks = callbacks_list,
verbose=2)
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)-3
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()
注意路径,文件保存在log_dir,也可以自己修改,保存次数是period参数设置,period = 1代表每训练一次就会保存一次训练数据。大约训到losses值小于15即可,这里是训练好的数据(h5文件):
6.数据测试:
源代码是将测试集代码随机抽取一张的,这里再改下detect_img函数使其能够测试指定的图片:
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()
r_image.save('E:/keras-yolo3/keras-yolo3/picback/' + img)
yolo.close_session()
然后执行,测试过程和前面所讲一样,因为我就训练了不到200次(这根本不是我的重点),就不贴出很挫的测试效果图了。不过很多大神跑了很久,还是测试成功的,主要注意标签标记时准一些就好了。
代码已上传至GitHub及Gitee,欢迎star,欢迎讨论:
GitHub:https://github.com/wangwei39120157028/Machine_Learning_research_on_simple_target_recognition_and_intention_analysis
Gitee:https://gitee.com/wwy2018/Machine_Learning_research_on_simple_target_recognition_and_intention_analysis/settings