py-faster-rcnn 训练自己的数据
转载:http://blog.csdn.net/sinat_30071459/article/details/51332084 Faster-RCNN+ZF用自己的数据集训练模型(Python版本)
说明:本博文假设你已经做好了自己的数据集,该数据集格式和VOC2007相同。
Faster-RCNN源码下载地址:
Matlab版本:https://github.com/ShaoqingRen/faster_rcnn
Python版本:https://github.com/rbgirshick/py-faster-rcnn
本文用到的是Python版本,在Linux下运行。
Matlab版本的训练过程:http://blog.csdn.net/sinat_30071459/article/details/50546891
准备工作:
1.配置caffe
这个不多说,网上教程很多。
2.其他的注意事项
这里说的挺详细了,认真看看吧。地址:https://github.com/rbgirshick/py-faster-rcnn(主要内容如下)
下面大概翻译一下上面网址的内容吧。
(1)安装cython, python-opencv,easydict
- pip install cython
- pip install easydict
- apt-get install python-opencv
(2)下载py-faster-rcnn
- # Make sure to clone with --recursive
- git clone --recursive https://github.com/rbgirshick/py-faster-rcnn.git
如图:
(3)进入py-faster-rcnn/lib
执行make
如图:
(4)进入py-faster-rcnn\caffe-fast-rcnn
执行 cp Makefile.config.example Makefile.config
然后,配置Makefile.config文件,可参考我的配置:Makefile.config文件
注意,这里需要将Makefile.config文件中的 WITH_PYTHON_LAYER=1 打开,否则会报Check failed: registry.count(type) == 1 (0 vs. 1) Unknown layer type: Python错误。
配置好Makefile.config文件后,执行:
- make -j8 && make pycaffe
如图:
(5)下载VOC2007数据集
提供一个百度云地址:http://pan.baidu.com/s/1mhMKKw4
解压,然后,将该数据集放在py-faster-rcnn\data下,用你的数据集替换VOC2007数据集。(替换Annotations,ImageSets和JPEGImages)
(用你的Annotations,ImagesSets和JPEGImages替换py-faster-rcnn\data\VOCdevkit2007\VOC2007中对应文件夹)
(6)下载ImageNet数据集下预训练得到的模型参数(用来初始化)
提供一个百度云地址:http://pan.baidu.com/s/1hsxx8OW
解压,然后将该文件放在py-faster-rcnn\data下
下面是训练前的一些修改。
1.py-faster-rcnn/models/pascal_voc/ZF/faster_rcnn_alt_opt/stage1_fast_rcnn_train.pt修改
layer {
name: 'data'
type: 'Python'
top: 'data'
top: 'rois'
top: 'labels'
top: 'bbox_targets'
top: 'bbox_inside_weights'
top: 'bbox_outside_weights'
python_param {
module: 'roi_data_layer.layer'
layer: 'RoIDataLayer'
param_str: "'num_classes': 16" #按训练集类别改,该值为类别数+
}
}
layer {
name: "cls_score"
type: "InnerProduct"
bottom: "fc7"
top: "cls_score"
param { lr_mult: 1.0 }
param { lr_mult: 2.0 }
inner_product_param {
num_output: 16 #按训练集类别改,该值为类别数+1
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
value: 0
}
}
}
layer {
name: "bbox_pred"
type: "InnerProduct"
bottom: "fc7"
top: "bbox_pred"
param { lr_mult: 1.0 }
param { lr_mult: 2.0 }
inner_product_param {
num_output: 64 #按训练集类别改,该值为(类别数+1)*4
weight_filler {
type: "gaussian"
std: 0.001
}
bias_filler {
type: "constant"
value: 0
}
}
}
2.py-faster-rcnn/models/pascal_voc/ZF/faster_rcnn_alt_opt/stage1_rpn_train.pt修改
layer {
name: 'input-data'
type: 'Python'
top: 'data'
top: 'im_info'
top: 'gt_boxes'
python_param {
module: 'roi_data_layer.layer'
layer: 'RoIDataLayer'
param_str: "'num_classes': 16" #按训练集类别改,该值为类别数+1
}
}
3.py-faster-rcnn/models/pascal_voc/ZF/faster_rcnn_alt_opt/stage2_fast_rcnn_train.pt修改
layer {
name: 'data'
type: 'Python'
top: 'data'
top: 'rois'
top: 'labels'
top: 'bbox_targets'
top: 'bbox_inside_weights'
top: 'bbox_outside_weights'
python_param {
module: 'roi_data_layer.layer'
layer: 'RoIDataLayer'
param_str: "'num_classes': 16" #按训练集类别改,该值为类别数+1
}
}
layer {
name: "cls_score"
type: "InnerProduct"
bottom: "fc7"
top: "cls_score"
param { lr_mult: 1.0 }
param { lr_mult: 2.0 }
inner_product_param {
num_output: 16 #按训练集类别改,该值为类别数+1
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
value: 0
}
}
}
layer {
name: "bbox_pred"
type: "InnerProduct"
bottom: "fc7"
top: "bbox_pred"
param { lr_mult: 1.0 }
param { lr_mult: 2.0 }
inner_product_param {
num_output: 64 #按训练集类别改,该值为(类别数+1)*4
weight_filler {
type: "gaussian"
std: 0.001
}
bias_filler {
type: "constant"
value: 0
}
}
}
4.py-faster-rcnn/models/pascal_voc/ZF/faster_rcnn_alt_opt/stage2_rpn_train.pt修改
layer {
name: 'input-data'
type: 'Python'
top: 'data'
top: 'im_info'
top: 'gt_boxes'
python_param {
module: 'roi_data_layer.layer'
layer: 'RoIDataLayer'
param_str: "'num_classes': 16" #按训练集类别改,该值为类别数+1
}
}
5.py-faster-rcnn/models/pascal_voc/ZF/faster_rcnn_alt_opt/faster_rcnn_test.pt修改
layer {
name: "cls_score"
type: "InnerProduct"
bottom: "fc7"
top: "cls_score"
inner_product_param {
num_output: 16 #按训练集类别改,该值为类别数+1
}
}
layer {
name: "bbox_pred"
type: "InnerProduct"
bottom: "fc7"
top: "bbox_pred"
inner_product_param {
num_output: 64 #按训练集类别改,该值为(类别数+1)*4
}
}
6.py-faster-rcnn/lib/datasets/pascal_voc.py修改
class pascal_voc(imdb):
def __init__(self, image_set, year, devkit_path=None):
imdb.__init__(self, 'voc_' + year + '_' + image_set)
self._year = year
self._image_set = image_set
self._devkit_path = self._get_default_path() if devkit_path is None \
else devkit_path
self._data_path = os.path.join(self._devkit_path, 'VOC' + self._year)
self._classes = ('__background__', # always index 0
'你的标签1','你的标签2',你的标签3','你的标签4'
)
上面要改的地方是
修改训练集文件夹:
self._data_path = os.path.join(self._devkit_path, 'VOC'+self._year)
用你的数据集直接替换原来VOC2007内的Annotations,ImageSets和JPEGImages即可,以免出现各种错误。
修改标签:
self._classes = ('__background__', # always index 0
'你的标签1','你的标签2','你的标签3','你的标签4'
)
修改成你的数据集的标签就行。
(2)
cls = self._class_to_ind[obj.find('name').text.lower().strip()]
这里把标签转成小写,如果你的标签含有大写字母,可能会出现KeyError的错误,所以建议标签用小写字母。
(去掉lower应该也行)
建议训练的标签还是用小写的字母,如果最终需要用大写字母或中文显示标签,可参考:
http://blog.csdn.net/sinat_30071459/article/details/51694037
7.py-faster-rcnn/lib/datasets/imdb.py修改
该文件的append_flipped_images(self)函数修改为:
def append_flipped_images(self):
num_images = self.num_images
widths = [PIL.Image.open(self.image_path_at(i)).size[0]
for i in xrange(num_images)]
for i in xrange(num_images):
boxes = self.roidb[i]['boxes'].copy()
oldx1 = boxes[:, 0].copy()
oldx2 = boxes[:, 2].copy()
boxes[:, 0] = widths[i] - oldx2 - 1
print boxes[:, 0]
boxes[:, 2] = widths[i] - oldx1 - 1
print boxes[:, 0]
assert (boxes[:, 2] >= boxes[:, 0]).all()
entry = {'boxes' : boxes,
'gt_overlaps' : self.roidb[i]['gt_overlaps'],
'gt_classes' : self.roidb[i]['gt_classes'],
'flipped' : True}
self.roidb.append(entry)
self._image_index = self._image_index * 2
!!!为防止与之前的模型搞混,训练前把output文件夹删除(或改个其他名),还要把py-faster-rcnn/data/cache中的文件和
py-faster-rcnn/data/VOCdevkit2007/annotations_cache中的文件删除(如果有的话)。
至于学习率等之类的设置,可在py-faster-rcnn/models/pascal_voc/ZF/faster_rcnn_alt_opt中的solve文件设置,迭代次数可在py-faster-rcnn\tools的train_faster_rcnn_alt_opt.py中修改:
- max_iters = [80000, 40000, 80000, 40000]
分别为4个阶段(rpn第1阶段,fast rcnn第1阶段,rpn第2阶段,fast rcnn第2阶段)的迭代次数。可改成你希望的迭代次数。
如果改了这些数值,最好把py-faster-rcnn/models/pascal_voc/ZF/faster_rcnn_alt_opt里对应的solver文件(有4个)也修改,stepsize小于上面修改的数值。
8.开始训练
进入py-faster-rcnn,执行:
./experiments/scripts/faster_rcnn_alt_opt.sh 0 ZF pascal_voc
这样,就开始训练了。
可能会报 AttributeError: 'module' object has no attribute 'text_format'错误,在文件./lib/fast_rcnn/train.py增加一行import google.protobuf.text_format 即可解决问题
9.测试
将训练得到的py-faster-rcnn\output\faster_rcnn_alt_opt\***_trainval中ZF的caffemodel拷贝至py-faster-rcnn\data\faster_rcnn_models(如果没有这个文件夹,就新建一个),然后,修改:
py-faster-rcnn\tools\demo.py,主要修改:
- CLASSES = ('__background__',
- '你的标签1', '你的标签2', '你的标签3', '你的标签4')
改成你的数据集标签;
- NETS = {'vgg16': ('VGG16',
- 'VGG16_faster_rcnn_final.caffemodel'),
- 'zf': ('ZF',
- 'ZF_faster_rcnn_final.caffemodel')}
上面ZF的caffemodel改成你的caffemodel。
- im_names = ['1559.jpg','1564.jpg']
改成你的测试图片。(测试图片放在py-faster-rcnn\data\demo中)
10.结果
在py-faster-rcnn下,
执行:
- ./tools/demo.py --net zf
或者将默认的模型改为zf:
- parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16]',
- choices=NETS.keys(), default='vgg16')
修改:
- default='zf'
执行:
- ./tools/demo.py
今天使用Faster RCNN训练自己的数据的时候,出现了一些因为boost或者是numpy版本不兼容导致的问题,经过各种查资料和求助大神,总算是顺利把网络跑起来了。下面内容都是今天亲测出现的问题并与其对应的解决方案,和大家一起分享,也便于我以后查看。
训练方法:在配置好Faster RCNN之后,准备好自己的数据,修改网络的配置文件和相应的训练脚本满,使用end to end 的训练方法,在$py-faster-rcnn的根目录下执行:./experiments/scripts/faster_rcnn_end2end.sh 0 VGG16 pascal_voc 。以下都是执行该脚本后出现的问题。
Problem 1
AttributeError: 'module' object has no attribute ‘text_format'
解决方法:在/home/xxx/py-faster-rcnn/lib/fast_rcnn/train.py的头文件导入部分加上 :import google.protobuf.text_format
Problem 2
TypeError: 'numpy.float64' object cannot be interpreted as an index
这里是因为numpy版本不兼容导致的问题,最好的解决办法是卸载你的numpy,安装numpy1.11.0。如果你和笔者一样不是服务器的网管,没有权限的话,就只能自己想办法解决了。
修改如下几个地方的code:
1) /home/xxx/py-faster-rcnn/lib/roi_data_layer/minibatch.py
将第26行:fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)
改为:fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image).astype(np.int)
2) /home/xxx/py-faster-rcnn/lib/datasets/ds_utils.py
将第12行:hashes = np.round(boxes * scale).dot(v)
改为:hashes = np.round(boxes * scale).dot(v).astype(np.int)
3) /home/xxx/py-faster-rcnn/lib/fast_rcnn/test.py
将第129行: hashes = np.round(blobs['rois'] * cfg.DEDUP_BOXES).dot(v)
改为: hashes = np.round(blobs['rois'] * cfg.DEDUP_BOXES).dot(v).astype(np.int)
4) /home/xxx/py-faster-rcnn/lib/rpn/proposal_target_layer.py
将第60行:fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)
改为:fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image).astype(np.int)
Problem3
TypeError: slice indices must be integers or None or have an __index__ method
这里还是因为numpy版本的原因,最好的解决办法还是换numpy版本(见problem2),但同样也有其他的解决办法。
修改 /home/lzx/py-faster-rcnn/lib/rpn/proposal_target_layer.py,转到123行:
for ind in inds:
cls = clss[ind]
start = 4 * cls
end = start + 4
bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
return bbox_targets, bbox_inside_weights
这里的ind,start,end都是 numpy.int 类型,这种类型的数据不能作为索引,所以必须对其进行强制类型转换,转化结果如下:
for ind in inds:
ind = int(ind)
cls = clss[ind]
start = int(4 * cos)
end = int(start + 4)
bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
return bbox_targets, bbox_inside_weights
以上内容是笔者在训练自己的datasets时候出现的一些问题,大部分还是因为Faster RCNN 发布的时候使用的一些库现在都升级了,所以需要对代码中一些细节进行修改!
Problem 4:
AssertionError: Path does not exist: /home/dl-box/wei/py-faster-rcnn/data/VOCdevkit2007/VOC2007/JPEGImages/000001.jpg
找不到这个路径,但是我的文件确实放对了地方,而且当我用cd命令的时候可以进入这个文件夹,打开对应的.jpg文件。
可能有两个原因:
1.没有权限对文件操作
解决:chmod -R 777 /home/dl-box/wei/py-faster-rcnn/data/VOCdevkit2007/VOC2007/JPEGImages/
2.可能是编码问题,要改成utf-8的格式
解决:在这个文件中py-faster-rcnn/lib/datasets/pascal_voc.py的_load_image_set_index下
将 image_index = [x.strip() for x in f.readlines()] 改成 image_index = [x.decode('utf-8-sig').strip() for x in f.readlines()] 就好了。
如果有编码问题的话可能你还要修改另一个地方,要不test的时候会报错。
解决:py-faster-rcnn/lib/datasets/voc_eval.py这个文件
将imagenames = [x.strip() for x in lines]改成imagenames = [x.decode('utf-8-sig').strip() for x in lines]
Problem5:
我改的比较极端[40,20,40,20],一路跑下来到最后的时候会有另一个错。
if len(sorted_ind) != 0:
BB = BB[sorted_ind, :]
image_ids = [image_ids[x] for x in sorted_ind]
更新后的代码详见GitHub:
py-faster-rcnn 训练自己的数据的更多相关文章
- caffe学习三:使用Faster RCNN训练自己的数据
本文假设你已经完成了安装,并可以运行demo.py 不会安装且用PASCAL VOC数据集的请看另来两篇博客. caffe学习一:ubuntu16.04下跑Faster R-CNN demo (基于c ...
- python3 + Tensorflow + Faster R-CNN训练自己的数据
之前实现过faster rcnn, 但是因为各种原因,有需要实现一次,而且发现许多博客都不全面.现在发现了一个比较全面的博客.自己根据这篇博客实现的也比较顺利.在此记录一下(照搬). 原博客:http ...
- caffe 用faster rcnn 训练自己的数据 遇到的问题
1 . 怎么处理那些pyx和.c .h文件 在lib下有一些文件为.pyx文件,遇到不能import可以cython 那个文件,然后把lib文件夹重新make一下. 遇到.c 和 .h一样的操作. 2 ...
- faster rcnn 源码学习-------数据读入及RoIDataLayer相关模块解读
参考博客:::https://www.cnblogs.com/Dzhen/p/6845852.html 非常全面的解读参考:::https://blog.csdn.net/DaVinciL/artic ...
- 如何才能将Faster R-CNN训练起来?
如何才能将Faster R-CNN训练起来? 首先进入 Faster RCNN 的官网啦,即:https://github.com/rbgirshick/py-faster-rcnn#installa ...
- py faster rcnn+ 1080Ti+cudnn5.0
看了py-faster-rcnn上的issue,原来大家都遇到各种问题. 我要好好琢磨一下,看看到底怎么样才能更好地把GPU卡发挥出来.最近真是和GPU卡较上劲了. 上午解决了g++的问题不是. 然后 ...
- faster rcnn训练详解
http://blog.csdn.net/zy1034092330/article/details/62044941 py-faster-rcnn训练自己的数据:流程很详细并附代码 https://h ...
- faster rcnn训练自己的数据集
采用Pascal VOC数据集的组织结构,来构建自己的数据集,这种方法是faster rcnn最便捷的训练方式
- Faster Rcnn训练自己的数据集过程大白话记录
声明:每人都有自己的理解,动手实践才能对细节更加理解! 一.算法理解 此处省略一万字.................. 二.训练及源码理解 首先配置: 在./lib/utils文件下....运行 p ...
- py faster rcnn的lib编译出错问题
真是好事多磨啊,计算机系统依然是14.04,而cuda依然是8.0,唯一不同的是时间不一样,下载的各种库版本有差别,GPU的driver不一样. 但是这样就出问题了,py-faster rcnn的li ...
随机推荐
- 微信小程序自定义分享图片
自定义分享图片 onShareAppMessage: (res) => { if (res.from === 'button') { console.log("来自页面内转发按钮&qu ...
- 理解和使用 Promise.all 和 Promise.race
一.Pomise.all的使用 Promise.all可以将多个Promise实例包装成一个新的Promise实例.同时,成功和失败的返回值是不同的,成功的时候返回的是一个结果数组,而失败的时候则返回 ...
- 07-hibernate进阶
1,hibernate.cfg.xml常用配置 2,session简介 3,transaction简介 4,session详解 5,对象关系映射常用配置 hibernate.cfg.xml常用配置 s ...
- 忽略警告注解@SuppressWarnings详解
简介:java.lang.SuppressWarnings是J2SE 5.0中标准的Annotation之一.可以标注在类.字段.方法.参数.构造方法,以及局部变量上. 作用:告诉编译器忽略指定的警告 ...
- Python-所有特殊方法、魔术方法、钩子
C.__init__(self[, arg1, ...]) 构造器(带一些可选的参数) C.__new__(self[, arg1, ...]) 构造器(带一些可选的参数)通常用在设置不变数据类型的子 ...
- 【web框架】Django
一.什么是web框架? 框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单的说,就是你用别人搭建好的舞台来做表演. 对于所有 ...
- linux c++ 文件获取md5
当前在linux系统下,shell命令可以获取md5值,如下: 如果进行c++编程,在代码里执行shell命令可以获得,但是很不雅观,特别是了解了system或者popen函数的机制之后.现在介绍使用 ...
- SQLServer强制保存
当你把nvarchar(200)改成nvarchar(100)的时候,可能会报错: Saving changes is not permitted. The changes you have made ...
- Mysql删除重复数据保留最小的id
在网上查找删除重复数据保留id最小的数据,方法如下: DELETE FROM people WHERE peopleName IN ( SELECT peopleName FROM people GR ...
- Mac 常用的手势
可以在触屏版-更多手势查看 技巧:前期慢慢滑动练习.一定要慢慢滑动,这样可以清楚的看出有没有产生效果,尤其注意大拇指滑动的感觉. 回到桌面:四指向外 打开Lanuchpad:四指向内 查看所有任务:三 ...