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

[plain] view plain copy
 
  1. pip install cython  
  2. pip install easydict  
  3. apt-get install python-opencv  

(2)下载py-faster-rcnn

  1. # Make sure to clone with --recursive  
  2. 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文件后,执行:

  1. 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" #按训练集类别改,该值为类别数+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  
    }  
  }  
}  

  

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修改

(1)
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  

  

这里assert (boxes[:, 2] >= boxes[:, 0]).all()可能出现AssertionError,具体解决办法参考:

 

 

!!!为防止与之前的模型搞混,训练前把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中修改:

 
  1. 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,主要修改:

[plain] view plain copy
 
  1. CLASSES = ('__background__',  
  2.            '你的标签1', '你的标签2', '你的标签3', '你的标签4')  

改成你的数据集标签;

 

 

[plain] view plain copy
 
  1. NETS = {'vgg16': ('VGG16',  
  2.                   'VGG16_faster_rcnn_final.caffemodel'),  
  3.         'zf': ('ZF',  
  4.                   'ZF_faster_rcnn_final.caffemodel')}  

上面ZF的caffemodel改成你的caffemodel。

 

[plain] view plain copy
 
  1. im_names = ['1559.jpg','1564.jpg']  


改成你的测试图片。(测试图片放在py-faster-rcnn\data\demo中)

10.结果

在py-faster-rcnn下,

执行: 

  1. ./tools/demo.py --net zf  

或者将默认的模型改为zf: 

  1. parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16]',  
  2.                         choices=NETS.keys(), default='vgg16')  

修改: 

  1. default='zf'  

执行:

  1. ./tools/demo.py 

 

Faster RCNN 训练中的一些问题及解决办法

今天使用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],一路跑下来到最后的时候会有另一个错。

    File "/home/dl-box/wei/py-faster-rcnn/tools/../lib/datasets/voc_eval.py", line 149, in voc_eval
        BB = BB[sorted_ind, :]
    IndexError: too many indices for array
    这个错是说没有学习到东西,我用了[4000,2000,4000,2000]试了一下也不行。不过能看到这个错误,如果你的数据集做的没有问题的话,用[80000,40000,80000,40000](亲测大概16小时,1341张图)运行你自己的数据集就没问题了。为了省时间我用的是[40000,20000,40000,2000](大概8小时,50张图)。这个时间好像与图片大小和图片数量关系不大。感觉只与迭代次数有关。
 这个时候是sorted_ind为空导致的,可以添加判断:修改如下,让代码继续运行:

  if len(sorted_ind) != 0:
    BB = BB[sorted_ind, :]
    image_ids = [image_ids[x] for x in sorted_ind]

 

更新后的代码详见GitHub:

posted on 2017-10-24 17:45  Sanny.Liu-CV&&ML  阅读(6630)  评论(0编辑  收藏  举报

导航