- 前言:调研_20190521。
-
1 Requirements
- torch>=0.4
无论是在服务器上面还是在我们自己的电脑上面,当我们成功安装了Ubuntu系统之后,系统一般情况下会自带Python2.x或Python3.x环境。
Ubuntu系统还会自动帮我们安装Python2.x环境下的pip安装工具,但是没有Python3.x环境下的pip3安装工具,所以我们需要手动安装pip3。
如果没有,那么可以首先安装 pip:sudo apt install -y python-pip
然后安装 pip3:sudo apt install -y python3-pip
更新 pip 版本:sudo pip install --upgrade pip
更新 pip3 版本:sudo pip3 install --upgrade pip
查看已安装的 python 包:pip freeze
使用pip更新pytorch和torchvision
pip list --outdated -format=legacy # 列举pip当前可以更新的所有安装包
pip install --upgrade pytorch torchvision # 更新pytorch和torchvision安装
使用pip安装指定版本
pip install pytorch==0.1.10
如何查看当前pytorch版本 有时候我们想要知道当前的pytorch版本,我们可以使用如下代码打印出当前的版本:
import torch print(torch.version)
卸载pytorch重新安装
pip uninstall torch
- numpy
NumPy(Numeric Python)是用Python进行科学计算的基本软件包。 NumPy是Python编程语言的扩展,增加了对大型多维数组和矩阵的支持,以及一个大型的高级数学函数库来操作这些数组。NumPy提供了许多高级的数值编程工具,如:矩阵数据类型、矢量处理,以及精密的运算库。专为进行严格的数字处理而产生。
pip:
pip install numpy
- torchvision
torchvision是独立于pytorch的关于图像操作的一些方便工具库。 torchvision的详细介绍在:https://pypi.org/project/torchvision/
torchvision主要包括一下几个包:
vision.datasets : 几个常用视觉数据集,可以下载和加载,这里主要的高级用法就 是可以看源码如何自己写自己的Dataset的子类
vision.models : 流行的模型,例如 AlexNet, VGG, ResNet 和 Densenet 以及 与训 练好的参数。
vision.transforms : 常用的图像操作,例如:随机切割,旋转,数据类型转换,图 像到tensor ,numpy 数组到tensor , tensor 到 图像等。
vision.utils : 用于把形似 (3 x H x W) 的张量保存到硬盘中,给一个mini-batch的图 像可以产生一个图像格网。
pip:
pip install torchvision
- pillow
PIL(Python Imaging Library)是Python常用的图像处理库,而Pillow是PIL的一个友好Fork,提供了广泛的文件格式支持,强大的图像处理能力,主要包括图像储存、图像显示、格式转换以及基本的图像处理操作等。
Pillow的文档:http://pillow.readthedocs.io/en/latest/
Pillow的github:https://github.com/python-pillow/Pillow
pip:
pip install Pillow
- matplotlib
matplotlib是Python编程语言及其NumPy数值数学扩展的绘图库。 它提供了一个面向对象的API,用于将绘图嵌入到使用通用GUI工具包(如wxPython,Qt或GTK +)的应用程序中。 还有一个基于状态机(如OpenGL)的程序“pylab”接口,其设计与MATLAB非常相似。
pip:
sudo pip install matplotlib
如果matplotlib 装不上需要先安装其依赖的包libpng和freetype
安装libpng:
sudo apt-get install libpng-dev
安装freetype:
wget http://download.savannah.gnu.org/releases/freetype/freetype-2.4.10.tar.gz
tar zxvf freetype-2.4.10.tar.gz cd freetype-2.4.10/
./congfigure
make sudo make install
然后再通过pip来安装matplotlib
pip install matplotlib
- torchsummary
torchsummary 库实现类似于 Keras 的model.summary()的功能,以便于打印 PyTorch 模型信息。
pip:
pip install torchsummary
git clone https://github.com/sksq96/pytorch-summary
使用方法:
from torchsummary import summary summary(pytorch_model, input_size=(channels, H, W))
其中, input_size 是必须设定的,以对网络进行一次 forward.
- tqdm
tqdm官网地址:https://pypi.org/project/tqdm/
Github地址:https://github.com/tqdm/tqdm
Tqdm 是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 tqdm(iterator)。
pip:
pip install tqdm
示例一 简单的demo:
# !/user/bin/env python
# -*- coding:utf-8 -*-
import time
from tqdm import tqdm
from tqdm._tqdm import trange
for i in tqdm(range(100)):
time.sleep(0.01)
2 Prepare the data
- path to data
如果我们的工程目录是/PyTorch-YOLOv3/…我们可以像这样将自己的数据信息输入到训练网络:
/PyTorch-YOLOv3/data/custom/images/…
like this: …
/PyTorch-YOLOv3/data/custom/labels/…
like this:
/PyTorch-YOLOv3/data/custom/train.txt
like this: …
/PyTorch-YOLOv3/data/custom/valid.txt
/PyTorch-YOLOv3/data/custom/test.txt
/PyTorch-YOLOv3/data/custom/custom.names
like this:…
在/PyTorch-YOLOv3/config下新建custom.data文件并录入如下:
classes = 20 #以voc数据为例,训练样本有20个种类
train = /data/custom/train.txt
valid = /data/custom/valid.txt
test = /data/custom/test.txt
names = /data/custom/custom.names
- xml_2_txt
按照voc数据集的结构放置图像文件:
Annotation中主要存放xml文件,每一个xml对应一张图像,并且每个xml中存放的是标记的各个目标的位置和类别信息,命名通常与对应的原始图像一样;
ImageSets我们只需要用到Main文件夹,这里面存放的是一些文本文件,通常为train.txt、test.txt等,该文本文件里面的内容是需要用来训练或测试的图像的名字;
根据自己情况修改/PyTorch-YOLOv3/voc2label.py脚本并运行,将xml文件转换成yolo格式的txt文件,放在生成的同级labels文件夹内。
- compute anchor box
yolov3.cfg的默认 anchor box 尺寸是基于 ImageNet训练集,使用 k-means 聚类算法获得的。在实际应用中,我们可能会检测一些形状特殊的物体,比如长尺,这时候,通用的anchor box尺寸会对最终训练模型的准确度产生影响,这时我们需要根据自己的样本生成对应的 anchor box 尺寸,替代默认值。
通过kmeans.py获得自己样本的 anchor box 尺寸
根据需要修改label_path以及n_anchors label_path 存储的是训练样本所有标注文本txt的地址
like this:
yolov3中n_anchors为9,tiny-yolov3中n_anchors为6
运行脚本后,在终端显示9个anchor box的值,用来替代yolov3.cfg文件中的anchor box尺寸
3 Know about .cfg file
[net]
# Testing 测试模式
# batch=1
# subdivisions=1
# Training 训练模式
batch=16 # 一批训练样本的样本数量,每batch个样本更新一次参数
subdivisions=1 # batch/subdivisions作为一次性送入训练器的样本数量,如果内存不够大,将batch分割为subdivisions个子batch
# 上面这两个参数如果电脑内存小,则把batch改小一点,batch越大,训练效果越好,subdivisions越大,可以减轻显卡压力
width=416 # input图像的宽
height=416 # input图像的高
channels=3 # input图像的通道数
# 以上三个参数为输入图像的参数信息 width和height影响网络对输入图像的分辨率,从而影响precision,只可以设置成32的倍数
momentum=0.9 # DeepLearning1中最优化方法中的动量参数,这个值影响着梯度下降到最优值得速度
decay=0.0005 # 权重衰减正则项,防止过拟合.每一次学习的过程中,将学习后的参数按照固定比例进行降低,为了防止过拟合,decay参数越大对过拟合的抑制能力越强。
angle=0 # 通过旋转角度来生成更多训练样本
saturation = 1.5 # 通过调整饱和度来生成更多训练样本
exposure = 1.5 # 通过调整曝光量来生成更多训练样本
hue=.1 # 通过调整色调来生成更多训练样本
learning_rate=0.001 # 学习率决定着权值更新的速度,设置得太大会使结果超过最优值,太小会使下降速度过慢。 如果仅靠人为干预调整参数,需要不断修改学习率。刚开始训练时可以将学习率设置的高一点,而一定轮数之后,将其减小,在训练过程中,一般根据训练轮数设置动态变化的学习率。刚开始训练时:学习率以 0.01 ~ 0.001 为宜。一定轮数过后:逐渐减缓。 接近训练结束:学习速率的衰减应该100倍以上。学习率的调整参考https://blog.csdn.net/qq_33485434/article/details/80452941
burn_in=1000 # 在迭代次数小于burn_in时,其学习率的更新有一种方式,大于burn_in时,才采用policy的更新方式
max_batches = 500200 # 训练达到max_batches后停止学习
policy=steps # 这个是学习率调整的策略,有policy:constant, steps, exp, poly, step, sig, RANDOM,constant等方式
steps=400000,450000 # 下面这两个参数steps和scale是设置学习率的变化,比如迭代到400000次时,学习率衰减十倍。
scales=.1,.1 # 450000次迭代时,学习率又会在前一个学习率的基础上衰减十倍
[convolutional]
batch_normalize=1 # 是否做BN
filters=32 # 输出特征图的数量
size=3 # 卷积核的尺寸
stride=1 # 做卷积运算的步长
pad=1 # 如果pad为0,padding由 padding参数指定;如果pad为1,padding大小为size/2,padding应该是对输入图像左边缘拓展的像素数量
activation=leaky # 激活函数的类型
# Downsample
......
# Downsam ple
######################
[convolutional]
size=1
stride=1
pad=1
filters=255 # 每一个[region/yolo]层前的最后一个卷积层中的 filters=(classes+1+coords)*anchors_num
activation=linear
[yolo] # 在yoloV2中yolo层叫region层
mask = 6,7,8 # 这一层预测第6、7、8个 anchor boxes ,每个yolo层实际上只预测3个由mask定义的anchors
anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326
# coco2014,anchors是可以事先计算出来
classes=80 # 网络需要识别的物体种类数
num=9 # 每个grid cell预测几个box,和anchors的数量一致。当想要使用更多anchors时需要调大num,且如果调大num后训练时Obj趋近0的话可以尝试调大object_scale
jitter=.3 # 利用数据抖动产生更多数据,YOLOv2中使用的是crop,filp,以及net层的angle,flip是随机的, jitter就是crop的参数,tiny-yolo-voc.cfg中jitter=.3,就是在0~0.3中进行crop
ignore_thresh = .5 # 决定是否需要计算IOU误差的参数,大于thresh,IOU误差不会夹在cost function中
truth_thresh = 1
random=1 # 如果为1,每次迭代图片大小随机从320到608,步长为32,如果为0,每次训练大小与输入大小一致
...
4 Modify the parameters
- train
parser = argparse.ArgumentParser()
parser.add_argument("--epochs", type=int, default=200, help="number of epochs")
parser.add_argument('-batch_size', type=int, default=32, help='size of each image batch')
parser.add_argument('-model_config_path', type=str, default='config/yolov3.cfg', help='path to model config file')
parser.add_argument('-data_config_path', type=str, default='config/costum.data', help='path to data config file')
parser.add_argument('-pretarained_path', type=str, default='weights/darknet53.conv.74', help='path to weights file')
parser.add_argument('-class_path', type=str, default='data/custom/custom.names', help='path to class label file')
parser.add_argument('-iou_thres', type=float, default=0.5, help='iou threshold required to qualify as detected')
parser.add_argument('-conf_thres', type=float, default=0.5, help='object confidence threshold')
parser.add_argument('-nms_thres', type=float, default=0.45, help='iou threshold for non-maximum suppression')
parser.add_argument('-n_cpu', type=int, default=0, help='number of cpu threads to use during batch generation')
parser.add_argument('-img_size', type=int, default=416, help='size of each image dimension')
opt = parser.parse_args()
parser.add_argument("--tiny_version", type=bool, default=False, help="whether is the yolov3-tiny version")
...
print(opt)
parameter means:
epochs: 设置循环的参数
batch_size: 每个batch大小
model_config_path: 网络配置文件
data_config_path: custom.data文件,存储相关信息
pretarained_path: 权重文件路径
class_path: 类别文件,注意类别的顺序,coco.names
iou_thres: iou阈值
conf_thres: 目标执行度阈值
nms_thres: 非极大抑制阈值
n_cpu: 实用多少个线程来创建batch
img_size: 设置初始图片大小
- image_detect
parser = argparse.ArgumentParser()
parser.add_argument('--image_folder', type=str, default='/samples', help='path to dataset')
parser.add_argument('--weights_path', type=str, default='checkpoints/epoch_***.weights', help='path to weights file')
...
image_detect.py line43
os.makedirs('output', exist_ok=True) # detect结果保存路径
image_folder # 用于detect的数据保存路径
weights_path # detect的权重文件路径
5 Reference
[1] PyTorch version of Yolo3/TinyYolo3, which is developed by Chen Yong
[2] https://github.com/eriklindernoren/PyTorch-YOLOv3
[3] https://blog.csdn.net/miao0967020148/article/details/80400357
[4] https://www.jianshu.com/p/4c12ee91a6d7
[5] https://blog.csdn.net/fengzhen8023/article/details/82927776
[6] https://www.cnblogs.com/yjphhw/p/9773333.html
[7] http://www.cnblogs.com/pcat/p/6790058.html
[8] https://blog.csdn.net/Mr_Cat123/article/details/78563998
[9] https://blog.csdn.net/yato0514/article/details/78754551
[10] https://www.aiuai.cn/aifarm458.html
[11] https://blog.csdn.net/qq_33472765/article/details/82940843
[12] https://blog.csdn.net/weixin_42880443/article/details/81953158
[13] https://blog.csdn.net/WK785456510/article/details/81565637
[14] https://blog.csdn.net/weixin_42731241/article/details/81474920
[15] http://www.cnblogs.com/pprp/p/10152698.html