Code Monkey home page Code Monkey logo

yolov4-pytorch's Introduction

YOLOV4:You Only Look Once目标检测模型在pytorch当中的实现


目录

  1. 仓库更新 Top News
  2. 相关仓库 Related code
  3. 性能情况 Performance
  4. 实现的内容 Achievement
  5. 所需环境 Environment
  6. 文件下载 Download
  7. 训练步骤 How2train
  8. 预测步骤 How2predict
  9. 评估步骤 How2eval
  10. 参考资料 Reference

Top News

2023-07:新增Seed设定,用于保证每次训练结果一致。

2022-04:支持多GPU训练,新增各个种类目标数量计算,新增heatmap。

2022-03:进行了大幅度的更新,修改了loss组成,使得分类、目标、回归loss的比例合适、支持step、cos学习率下降法、支持adam、sgd优化器选择、支持学习率根据batch_size自适应调整、新增图片裁剪。
BiliBili视频中的原仓库地址为:https://github.com/bubbliiiing/yolov4-pytorch/tree/bilibili

2021-10:进行了大幅度的更新,增加了大量注释、增加了大量可调整参数、对代码的组成模块进行修改、增加fps、视频预测、批量预测等功能。

相关仓库

模型 路径
YoloV3 https://github.com/bubbliiiing/yolo3-pytorch
Efficientnet-Yolo3 https://github.com/bubbliiiing/efficientnet-yolo3-pytorch
YoloV4 https://github.com/bubbliiiing/yolov4-pytorch
YoloV4-tiny https://github.com/bubbliiiing/yolov4-tiny-pytorch
Mobilenet-Yolov4 https://github.com/bubbliiiing/mobilenet-yolov4-pytorch
YoloV5-V5.0 https://github.com/bubbliiiing/yolov5-pytorch
YoloV5-V6.1 https://github.com/bubbliiiing/yolov5-v6.1-pytorch
YoloX https://github.com/bubbliiiing/yolox-pytorch
YoloV7 https://github.com/bubbliiiing/yolov7-pytorch
YoloV7-tiny https://github.com/bubbliiiing/yolov7-tiny-pytorch

性能情况

训练数据集 权值文件名称 测试数据集 输入图片大小 mAP 0.5:0.95 mAP 0.5
VOC07+12+COCO yolo4_voc_weights.pth VOC-Test07 416x416 - 89.0
COCO-Train2017 yolo4_weights.pth COCO-Val2017 416x416 46.1 70.2

实现的内容

  • 主干特征提取网络:DarkNet53 => CSPDarkNet53
  • 特征金字塔:SPP,PAN
  • 训练用到的小技巧:Mosaic数据增强、Label Smoothing平滑、CIOU、学习率余弦退火衰减
  • 激活函数:使用Mish激活函数
  • ……balabla

所需环境

torch==1.2.0

文件下载

训练所需的yolo4_weights.pth可在百度网盘中下载。
链接: https://pan.baidu.com/s/1oXz13QwLx1lnXct538qL2Q
提取码: 16qc
yolo4_weights.pth是coco数据集的权重。
yolo4_voc_weights.pth是voc数据集的权重。

VOC数据集下载地址如下,里面已经包括了训练集、测试集、验证集(与测试集一样),无需再次划分:
链接: https://pan.baidu.com/s/19Mw2u_df_nBzsC2lg20fQA
提取码: j5ge

训练步骤

a、训练VOC07+12数据集

  1. 数据集的准备
    本文使用VOC格式进行训练,训练前需要下载好VOC07+12的数据集,解压后放在根目录

  2. 数据集的处理
    修改voc_annotation.py里面的annotation_mode=2,运行voc_annotation.py生成根目录下的2007_train.txt和2007_val.txt。

  3. 开始网络训练
    train.py的默认参数用于训练VOC数据集,直接运行train.py即可开始训练。

  4. 训练结果预测
    训练结果预测需要用到两个文件,分别是yolo.py和predict.py。我们首先需要去yolo.py里面修改model_path以及classes_path,这两个参数必须要修改。
    model_path指向训练好的权值文件,在logs文件夹里。
    classes_path指向检测类别所对应的txt。

    完成修改后就可以运行predict.py进行检测了。运行后输入图片路径即可检测。

b、训练自己的数据集

  1. 数据集的准备
    本文使用VOC格式进行训练,训练前需要自己制作好数据集,
    训练前将标签文件放在VOCdevkit文件夹下的VOC2007文件夹下的Annotation中。
    训练前将图片文件放在VOCdevkit文件夹下的VOC2007文件夹下的JPEGImages中。

  2. 数据集的处理
    在完成数据集的摆放之后,我们需要利用voc_annotation.py获得训练用的2007_train.txt和2007_val.txt。
    修改voc_annotation.py里面的参数。第一次训练可以仅修改classes_path,classes_path用于指向检测类别所对应的txt。
    训练自己的数据集时,可以自己建立一个cls_classes.txt,里面写自己所需要区分的类别。
    model_data/cls_classes.txt文件内容为:

cat
dog
...

修改voc_annotation.py中的classes_path,使其对应cls_classes.txt,并运行voc_annotation.py。

  1. 开始网络训练
    训练的参数较多,均在train.py中,大家可以在下载库后仔细看注释,其中最重要的部分依然是train.py里的classes_path。
    classes_path用于指向检测类别所对应的txt,这个txt和voc_annotation.py里面的txt一样!训练自己的数据集必须要修改!
    修改完classes_path后就可以运行train.py开始训练了,在训练多个epoch后,权值会生成在logs文件夹中。

  2. 训练结果预测
    训练结果预测需要用到两个文件,分别是yolo.py和predict.py。在yolo.py里面修改model_path以及classes_path。
    model_path指向训练好的权值文件,在logs文件夹里。
    classes_path指向检测类别所对应的txt。

    完成修改后就可以运行predict.py进行检测了。运行后输入图片路径即可检测。

预测步骤

a、使用预训练权重

  1. 下载完库后解压,在百度网盘下载yolo_weights.pth,放入model_data,运行predict.py,输入
img/street.jpg
  1. 在predict.py里面进行设置可以进行fps测试和video视频检测。

b、使用自己训练的权重

  1. 按照训练步骤训练。
  2. 在yolo.py文件里面,在如下部分修改model_path和classes_path使其对应训练好的文件;model_path对应logs文件夹下面的权值文件,classes_path是model_path对应分的类
_defaults = {
    #--------------------------------------------------------------------------#
    #   使用自己训练好的模型进行预测一定要修改model_path和classes_path!
    #   model_path指向logs文件夹下的权值文件,classes_path指向model_data下的txt
    #   如果出现shape不匹配,同时要注意训练时的model_path和classes_path参数的修改
    #--------------------------------------------------------------------------#
    "model_path"        : 'model_data/yolo_weights.pth',
    "classes_path"      : 'model_data/coco_classes.txt',
    #---------------------------------------------------------------------#
    #   anchors_path代表先验框对应的txt文件,一般不修改。
    #   anchors_mask用于帮助代码找到对应的先验框,一般不修改。
    #---------------------------------------------------------------------#
    "anchors_path"      : 'model_data/yolo_anchors.txt',
    "anchors_mask"      : [[6, 7, 8], [3, 4, 5], [0, 1, 2]],
    #---------------------------------------------------------------------#
    #   输入图片的大小,必须为32的倍数。
    #---------------------------------------------------------------------#
    "input_shape"       : [416, 416],
    #---------------------------------------------------------------------#
    #   只有得分大于置信度的预测框会被保留下来
    #---------------------------------------------------------------------#
    "confidence"        : 0.5,
    #---------------------------------------------------------------------#
    #   非极大抑制所用到的nms_iou大小
    #---------------------------------------------------------------------#
    "nms_iou"           : 0.3,
    #---------------------------------------------------------------------#
    #   该变量用于控制是否使用letterbox_image对输入图像进行不失真的resize,
    #   在多次测试后,发现关闭letterbox_image直接resize的效果更好
    #---------------------------------------------------------------------#
    "letterbox_image"   : False,
    #-------------------------------#
    #   是否使用Cuda
    #   没有GPU可以设置成False
    #-------------------------------#
    "cuda"              : True,
}
  1. 运行predict.py,输入
img/street.jpg
  1. 在predict.py里面进行设置可以进行fps测试和video视频检测。

评估步骤

a、评估VOC07+12的测试集

  1. 本文使用VOC格式进行评估。VOC07+12已经划分好了测试集,无需利用voc_annotation.py生成ImageSets文件夹下的txt。
  2. 在yolo.py里面修改model_path以及classes_path。model_path指向训练好的权值文件,在logs文件夹里。classes_path指向检测类别所对应的txt。
  3. 运行get_map.py即可获得评估结果,评估结果会保存在map_out文件夹中。

b、评估自己的数据集

  1. 本文使用VOC格式进行评估。
  2. 如果在训练前已经运行过voc_annotation.py文件,代码会自动将数据集划分成训练集、验证集和测试集。如果想要修改测试集的比例,可以修改voc_annotation.py文件下的trainval_percent。trainval_percent用于指定(训练集+验证集)与测试集的比例,默认情况下 (训练集+验证集):测试集 = 9:1。train_percent用于指定(训练集+验证集)中训练集与验证集的比例,默认情况下 训练集:验证集 = 9:1。
  3. 利用voc_annotation.py划分测试集后,前往get_map.py文件修改classes_path,classes_path用于指向检测类别所对应的txt,这个txt和训练时的txt一样。评估自己的数据集必须要修改。
  4. 在yolo.py里面修改model_path以及classes_path。model_path指向训练好的权值文件,在logs文件夹里。classes_path指向检测类别所对应的txt。
  5. 运行get_map.py即可获得评估结果,评估结果会保存在map_out文件夹中。

Reference

https://github.com/qqwweee/keras-yolo3/
https://github.com/Cartucho/mAP
https://github.com/Ma-Dan/keras-yolo4

yolov4-pytorch's People

Contributors

bubbliiiing avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yolov4-pytorch's Issues

cuda问题请教

请问大佬,您使用的GPU驱动是什么版本,我的是NVIDIA 10.1,在使用您的代码时报错,驱动太老,请问这个问题怎么解决,必须要升级驱动吗

如何得到mAP

不好意思打扰了,如果想得到mAP,该怎么加一些代码呢?

请问yolov4原论文提到的方法都在这里实现了吗?

下面是yolov4原论文中给出的方法,请问您的代码全部实现了这些功能吗?如果没有的话具体哪些还没有实现呢?谢谢!

YOLO v4 uses:
• Bag of Freebies (BoF) for backbone: CutMix and Mosaic data augmentation, DropBlock regularization,Class label smoothing
• Bag of Specials (BoS) for backbone: Mish activation, Cross-stage partial connections (CSP), Multi input weighted residual
connections (MiWRC)
• Bag of Freebies (BoF) for detector: CIoU-loss,CmBN, DropBlock regularization, Mosaic data augmentation, Self-Adversarial
Training, Eliminate grid sensitivity, Using multiple anchors for a single ground truth, Cosine annealing scheduler [52], Optimal
hyperparameters, Random training shapes
• Bag of Specials (BoS) for detector: Mish activation,SPP-block, SAM-block, PAN path-aggregation block,DIoU-NMS

偶尔会出现一些莫名其妙的大框

大佬,我用你的代码训练,效果确实不错,但是偶尔会在没有目标的帧中出现一些大框,我觉得原因就是昨天我说的没有加入不包括目标的训练样本导致的。我现在想加入不包括目标的训练样本,但是需要参考我之前的yolov3来魔改,我python能力不够,大佬,你能改改吗?

anno的格式问题

yolov4-pytorch/train.py

Lines 73 to 76 in 8a0fd2f

targets_val = [Variable(torch.from_numpy(ann).type(torch.FloatTensor)) for ann in targets_val]
else:
images_val = Variable(torch.from_numpy(images_val).type(torch.FloatTensor))
targets_val = [Variable(torch.from_numpy(ann).type(torch.FloatTensor)) for ann in targets_val]

运行代码时,有时候会报错说输入应该是numpy格式而不是list格式。
建议将torch.from_numpy(ann)改为torch.from_numpy(np.array(ann))

训练报错

你好博主,非常感谢分享。
我在按照提示的步骤进行训练时出现了如下的错误:
1 . Traceback (most recent call last):
File "yolov4-pytorch-master\nets\yolo4.py", line 129, in forward
P4 = torch.cat([P4,P5_upsample],axis=1)
TypeError: cat() got an unexpected keyword argument 'axis' (已将axis改成dim,请问这个是版本原因还是?)

2. Traceback (most recent call last):
File "yolov4-pytorch-master\nets\yolo_training.py", line 167, in forward
ciou = (1 - box_ciou( pred_boxes_for_ciou[mask.bool()], t_box[mask.bool()]))* box_loss_scale[mask.bool()]
AttributeError: 'Tensor' object has no attribute 'bool'(请问这个问题怎么进行修改呢?)

TypeError: cat() got an unexpected keyword argument 'axis'

遇到的一个bug
完整错误提示
Traceback (most recent call last):
File "C:/Users/zhq/Desktop/maskdect/yolov4-pytorch-master/train.py", line 178, in
fit_ont_epoch(net,yolo_losses,epoch,epoch_size,epoch_size_val,gen,gen_val,Freeze_Epoch,Cuda)
File "C:/Users/zhq/Desktop/maskdect/yolov4-pytorch-master/train.py", line 49, in fit_ont_epoch
outputs = net(images)
File "D:\Program_Files\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 493, in call
result = self.forward(*input, **kwargs)
File "D:\Program_Files\Anaconda3\lib\site-packages\torch\nn\parallel\data_parallel.py", line 150, in forward
return self.module(*inputs[0], **kwargs[0])
File "D:\Program_Files\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 493, in call
result = self.forward(*input, **kwargs)
File "C:\Users\zhq\Desktop\maskdect\yolov4-pytorch-master\nets\yolo4.py", line 129, in forward
P4 = torch.cat([P4,P5_upsample],axis=1)
TypeError: cat() got an unexpected keyword argument 'axis'

我查了一下,发现相关给出的建议都是针对tf的,还没有好的解决办法

数据集的处理能不能使用k折交叉验证的方法

楼主,我看你数据集按9:1分为训练集和验证集来训练,但是每个epoch都是一样的。能不能在每个epoch里把数据按9:1分为训练集和验证集来训练,这就是说每个epoch的训练集和验证集在变化。也就是说数据集的处理能不能使用k折交叉验证的方法。

test.py

请问会更新test.py 吗 然后生成计算map所需的txt

关于train.py冻结与解冻的问题

你好,我想请问如果在训练的过程中,首先进行冻结一定部分训练,也就是你咋注释中所说防止权值破坏;然后训练到一定的epoch后再进行解冻训练,但是这时候出现预测的准确率大幅下降,是什么原因呢?
那么请问可能是在冻结训练的时候出现已经过拟合现象,然后在基于已经过拟合的模型进行解冻后训练导致的?

Have you ever been in this situation?

Hello, big guy, may I ask, I use your training garbage classification, the label also changed to garbage, why the end of the training tag inside suddenly more people, cars, bicycles, etc., and the identification is quite accurate, but my training set does not have these pictures, what is this??

关于训练的疑问

您好,首先感谢您的分享。 我有几个疑问之处:

  1. 为什么先冻结25个epoch 的训练再解冻 再训练?
  2. 为什么我训练前 25个epoch时, 大概 显存 9个g左右, 第26个epoch就直接显存炸了? 我改小了 batchsize 也是不行。

请问mask的loss影响模型的识别结果吗?

你好,我看训练过程的loss中有mask的参与,那么在最后进行目标识别时,会对结果造成影响吗?因为我理解的最后只进行识别,应该不会有mask的遮罩处理?

小改进,cpu与gpu加载模型

train.py与yolo.py中有使用torch.load()方法的建议加上map_location=xxx,防止gpu训练cpu预测或其它混用情况下报错。
比如可以改成这样:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
pretrained_dict = torch.load(model_path, map_location=device)

数据集方面的问题

通过打印框的位置感觉有问题,请问大佬是不是验证过图像增强的过程?
image
image

将train.py训练得到的权重带入到yolo.py中,出现如下的问题,存在权重与架构不匹配的问题,您能帮忙看看怎么解决吗?谢谢!

RuntimeError: Error(s) in loading state_dict for YoloBody:
size mismatch for yolo_head3.1.weight: copying a param with shape torch.Size([18, 256, 1, 1]) from checkpoint, the shape in current model is torch.Size([255, 256, 1, 1]).
size mismatch for yolo_head3.1.bias: copying a param with shape torch.Size([18]) from checkpoint, the shape in current model is torch.Size([255]).
size mismatch for yolo_head2.1.weight: copying a param with shape torch.Size([18, 512, 1, 1]) from checkpoint, the shape in current model is torch.Size([255, 512, 1, 1]).
size mismatch for yolo_head2.1.bias: copying a param with shape torch.Size([18]) from checkpoint, the shape in current model is torch.Size([255]).
size mismatch for yolo_head1.1.weight: copying a param with shape torch.Size([18, 1024, 1, 1]) from checkpoint, the shape in current model is torch.Size([255, 1024, 1, 1]).
size mismatch for yolo_head1.1.bias: copying a param with shape torch.Size([18]) from checkpoint, the shape in current model is torch.Size([255]).

c++环境下编译模型

你好,我想问下用该项目训练好的模型能用于C++环境下进行编译、预测吗?例如darknet编译

训练问题请教

您好,使用您的代码,全部默认的参数配置,在VOC2007数据集上,训练到40+轮后,训练集的损失从20-30降至3附近,但是验证集的损失几乎没有变化,一直在8、9、10左右震荡,这似乎是过拟合的迹象,不知道大佬怎么看 ?
另外,您下图的仓库,到底实现的yolov4还是v3 ?
image

检测速度问题

您好,我把yolov4-tiny的特征融合FPN网络改成了yolov4的PANet网络,检测精度有提高,但是速度降低了很多,FPS只有8~10,和yolov4差不多了,yolov4是8左右,明明我的模型都比yolov4少了一大半,请问下这是怎么回事啊?

一些疑问

感谢大佬的代码!
在自己改造数据集加载为pytorch的Dataset类时,用plt显示__getitem__()方法获取的图片时,发现mosaic为true获取的图片显示为黑色,经过调试发现:
get_random_data()方法的图片会经过>>除255再乘255
get_random_data_with_Mosaic()方法会经过>>除255再乘255又除255
最终mosaic显示为黑色,只要去掉mosaic方法内的最后一个除255就可以了。
请问这个是预期的嘛?

预测类别错误

楼主好,我用这个模型正常训练完,收敛到20左右,进行预测时发现类别不对,而且最后显示的置信度值很低,0.03左右,但是框出来的确实是缺陷,估计是啥原因?

所需环境配置?

所需环境
tensorflow-gpu==1.13.1
keras==2.1.5?
这是一个pytorch的版本吗 :)

train时,遇到invalid load key, '\x00',怎么解决?谢谢大佬们

Loading weights into state dict...
Traceback (most recent call last):
File "train.py", line 141, in
pretrained_dict = torch.load(model_path, map_location=device)
File "/home/liupenglei/anaconda3/envs/pythorch/lib/python3.6/site-packages/torch/serialization.py", line 387, in load
return _load(f, map_location, pickle_module, **pickle_load_args)
File "/home/liupenglei/anaconda3/envs/pythorch/lib/python3.6/site-packages/torch/serialization.py", line 564, in _load
magic_number = pickle_module.load(f, **pickle_load_args)
_pickle.UnpicklingError: invalid load key, '\x00'.

utils/utils.py中的yolo_correct_boxes函数的疑问

大佬代码非常优雅,值得我深入学习
在拜读您代码的时候,关于utils.py中的yolo_correct_boxes函数,感觉您实现的好像有问题吧?
scale是一个二元tuple,其中一个是1,另一个大于1,之前图片输入网络的时候,是将图片缩放到恰好可以粘贴到416*416的灰色背景上,而原图片的高宽比没有变化啊,为什么这里要对y,x坐标进行不同scale的放缩呢??

是我理解错了吗? 可以劳烦您检查一下吗,如果确认无误,我再慢慢琢磨,谢谢

训练问题

我用yolov4训练猫狗的模型时,效果非常好。但是我用yolov4训练人猫狗的模型时,训练了一个星期了,在验证集和训练集上的loss一直保持在一个较高的值,降不下去了。拿训练好的模型去做测试,效果很差,应该是还没训练好,但是loss一直降不下去了,不知道楼主与没遇见过这个情况。

注:猫狗的数据集有4万张,人猫狗的数据集有12万张。

VOC数据集,从零开始训练

没试过加载预训练权重,BD网盘太慢不想下。
VOC数据集,从零开始训练没有效果。
Cosine_lr = False
mosaic = False
尺寸为608x608
其它都是默认参数,训练20epoch后loss大约在25左右,然后手动测试图片发现没有框。请问从零开始训练参数大概如何调整呢?

在docker下报了一个错 求帮助

root@42f6601705a0:/workspace/yolov4-pytorch-master# python3 train.py
Loading weights into state dict...
Finished!
/workspace/yolov4-pytorch-master/utils/dataloader.py:251: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
bboxes = np.array(bboxes)

数据集中为啥没负样本

voc_annotation.py这个脚本把没有目标的负样本全部过滤掉了。请问你这个训练代码能不能加负样本进行训练

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.