轉載: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" #按訓練集類別改,該值為類別數+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修改
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: