TensorFlow1.8.0+Python3.6+CUDA-9.0+Faster-RCNN訓練自己的數據集! |
文章目錄
前期準備
-
主要參考github代碼 :https://github.com/endernewton/tf-faster-rcnn
-
主要參考CSDN文章1:https://zhuanlan.zhihu.com/p/31426458
-
主要參考簡書中文章2:Tensorflow-Faster-Rcnn解讀
-
程序運行環境包如下:
(tf36) zhangkf@wang-ThinkStation-P520:~/tf/tf-faster-rcnn-master$ conda list
# packages in environment at /home/zhangkf/anaconda3/envs/tf36:
#
# Name Version Build Channel
_libgcc_mutex 0.1 main https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
absl-py 0.8.1 pypi_0 pypi
astor 0.8.0 pypi_0 pypi
bleach 1.5.0 pypi_0 pypi
ca-certificates 2019.8.28 0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
certifi 2019.9.11 py36_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
cycler 0.10.0 pypi_0 pypi
cython 0.29.13 pypi_0 pypi
easydict 1.9 pypi_0 pypi
gast 0.3.2 pypi_0 pypi
grpcio 1.24.1 pypi_0 pypi
html5lib 0.9999999 pypi_0 pypi
kiwisolver 1.1.0 pypi_0 pypi
libedit 3.1.20181209 hc058e9b_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
libffi 3.2.1 hd88cf55_4 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
libgcc-ng 9.1.0 hdf63c60_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
libstdcxx-ng 9.1.0 hdf63c60_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
markdown 3.1.1 pypi_0 pypi
matplotlib 3.1.1 pypi_0 pypi
ncurses 6.1 he6710b0_1 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
numpy 1.17.3 pypi_0 pypi
opencv-python 3.4.0.14 pypi_0 pypi
openssl 1.1.1d h7b6447c_3 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
pillow 6.2.0 pypi_0 pypi
pip 19.2.3 py36_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
protobuf 3.10.0 pypi_0 pypi
pyparsing 2.4.2 pypi_0 pypi
python 3.6.9 h265db76_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
python-dateutil 2.8.0 pypi_0 pypi
pyyaml 5.1.2 pypi_0 pypi
readline 7.0 h7b6447c_5 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
scipy 1.3.1 pypi_0 pypi
setuptools 41.4.0 py36_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
six 1.12.0 pypi_0 pypi
sqlite 3.30.0 h7b6447c_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
tensorboard 1.8.0 pypi_0 pypi
tensorflow-gpu 1.8.0 pypi_0 pypi
termcolor 1.1.0 pypi_0 pypi
tk 8.6.8 hbc83047_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
werkzeug 0.16.0 pypi_0 pypi
wheel 0.33.6 py36_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
xz 5.2.4 h14c3975_4 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
zlib 1.2.11 h7b6447c_3 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
- 其中下載的
github
程序結構爲:
data: #存放demo測試數據、預訓練模型、訓練數據(VOC2007數據格式)
docker: #cuda文件
experiments: #訓練測試sh文件、訓練測試過程日誌文件
lib: #數據讀取、訓練模型等文件
tools: #模型訓練、驗證等python文件
一. Faster-RCNN簡要介紹
1.1. Faster-RCNN網絡結構圖
Faster-RCNN
網絡結構圖參考作者 一文讀懂Faster RCNN!
- 上圖展示了
python
版本中的VGG16
模型中的faster_rcnn_test.pt
的網絡結構,可以清晰的看到該網絡對於一副任意大小PxQ
的圖像,首先縮放至固定大小MxN
,然後將MxN
圖像送入網絡;而Conv layers
中包含了13
個conv
層+13
個relu
層+4
個pooling
層;RPN
網絡首先經過3x3
卷積,再分別生成positive anchors
和對應bounding box regression
偏移量,然後計算出proposals
;而Roi Pooling
層則利用proposals
從feature maps
中提取proposal feature
送入後續全連接和softmax
網絡作classification
(即分類proposal
到底是什麼object
)。
二. Faster-RCNN訓練步驟
2.1. 編譯Cython
- 1. 首先克隆代碼:
git clone https://github.com/endernewton/tf-faster-rcnn
- 2. 根據你的顯卡更改下對應的計算單元。在
/lib/setup.py
的第130
行,TitanX
對應的是sm_52
。在這可以查到每種顯卡對應的計算單元!
- 3. 編譯Cython: 仍然在
lib
路徑下,編譯Cython
模塊
make clean
make
cd ..
- 4. 編譯完成顯示如下:
(tf36) zhangkf@wang-ThinkStation-P520:~/tf/tf-faster-rcnn-master/lib$ make clean
rm -rf */*.pyc
rm -rf */*.so
(tf36) zhangkf@wang-ThinkStation-P520:~/tf/tf-faster-rcnn-master/lib$ make
python setup.py build_ext --inplace
running build_ext
skipping 'utils/bbox.c' Cython extension (up-to-date)
building 'utils.cython_bbox' extension
creating build
creating build/temp.linux-x86_64-3.6
creating build/temp.linux-x86_64-3.6/utils
{'gcc': ['-Wno-cpp', '-Wno-unused-function']}
gcc -pthread -B /home/zhangkf/anaconda3/envs/tf36/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/zhangkf/anaconda3/envs/tf36/lib/python3.6/site-packages/numpy/core/include -I/home/zhangkf/anaconda3/envs/tf36/include/python3.6m -c utils/bbox.c -o build/temp.linux-x86_64-3.6/utils/bbox.o -Wno-cpp -Wno-unused-function
gcc -pthread -shared -B /home/zhangkf/anaconda3/envs/tf36/compiler_compat -L/home/zhangkf/anaconda3/envs/tf36/lib -Wl,-rpath=/home/zhangkf/anaconda3/envs/tf36/lib -Wl,--no-as-needed -Wl,--sysroot=/ build/temp.linux-x86_64-3.6/utils/bbox.o -o /home/zhangkf/tf/tf-faster-rcnn-master/lib/utils/cython_bbox.cpython-36m-x86_64-linux-gnu.so
skipping 'nms/cpu_nms.c' Cython extension (up-to-date)
building 'nms.cpu_nms' extension
creating build/temp.linux-x86_64-3.6/nms
{'gcc': ['-Wno-cpp', '-Wno-unused-function']}
gcc -pthread -B /home/zhangkf/anaconda3/envs/tf36/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/zhangkf/anaconda3/envs/tf36/lib/python3.6/site-packages/numpy/core/include -I/home/zhangkf/anaconda3/envs/tf36/include/python3.6m -c nms/cpu_nms.c -o build/temp.linux-x86_64-3.6/nms/cpu_nms.o -Wno-cpp -Wno-unused-function
gcc -pthread -shared -B /home/zhangkf/anaconda3/envs/tf36/compiler_compat -L/home/zhangkf/anaconda3/envs/tf36/lib -Wl,-rpath=/home/zhangkf/anaconda3/envs/tf36/lib -Wl,--no-as-needed -Wl,--sysroot=/ build/temp.linux-x86_64-3.6/nms/cpu_nms.o -o /home/zhangkf/tf/tf-faster-rcnn-master/lib/nms/cpu_nms.cpython-36m-x86_64-linux-gnu.so
skipping 'nms/gpu_nms.cpp' Cython extension (up-to-date)
building 'nms.gpu_nms' extension
{'gcc': ['-Wno-unused-function'], 'nvcc': ['-arch=sm_52', '--ptxas-options=-v', '-c', '--compiler-options', "'-fPIC'"]}
/usr/local/cuda-9.0/bin/nvcc -I/home/zhangkf/anaconda3/envs/tf36/lib/python3.6/site-packages/numpy/core/include -I/usr/local/cuda-9.0/include -I/home/zhangkf/anaconda3/envs/tf36/include/python3.6m -c nms/nms_kernel.cu -o build/temp.linux-x86_64-3.6/nms/nms_kernel.o -arch=sm_52 --ptxas-options=-v -c --compiler-options '-fPIC'
ptxas info : 0 bytes gmem
ptxas info : Compiling entry function '_Z10nms_kernelifPKfPy' for 'sm_52'
ptxas info : Function properties for _Z10nms_kernelifPKfPy
0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads
ptxas info : Used 23 registers, 1280 bytes smem, 344 bytes cmem[0], 12 bytes cmem[2]
{'gcc': ['-Wno-unused-function'], 'nvcc': ['-arch=sm_52', '--ptxas-options=-v', '-c', '--compiler-options', "'-fPIC'"]}
gcc -pthread -B /home/zhangkf/anaconda3/envs/tf36/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/zhangkf/anaconda3/envs/tf36/lib/python3.6/site-packages/numpy/core/include -I/usr/local/cuda-9.0/include -I/home/zhangkf/anaconda3/envs/tf36/include/python3.6m -c nms/gpu_nms.cpp -o build/temp.linux-x86_64-3.6/nms/gpu_nms.o -Wno-unused-function
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++
In file included from /home/zhangkf/anaconda3/envs/tf36/lib/python3.6/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830:0,
from /home/zhangkf/anaconda3/envs/tf36/lib/python3.6/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,
from /home/zhangkf/anaconda3/envs/tf36/lib/python3.6/site-packages/numpy/core/include/numpy/arrayobject.h:4,
from nms/gpu_nms.cpp:346:
/home/zhangkf/anaconda3/envs/tf36/lib/python3.6/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning "Using deprecated NumPy
g++ -pthread -shared -B /home/zhangkf/anaconda3/envs/tf36/compiler_compat -L/home/zhangkf/anaconda3/envs/tf36/lib -Wl,-rpath=/home/zhangkf/anaconda3/envs/tf36/lib -Wl,--no-as-needed -Wl,--sysroot=/ build/temp.linux-x86_64-3.6/nms/nms_kernel.o build/temp.linux-x86_64-3.6/nms/gpu_nms.o -L/usr/local/cuda-9.0/lib64 -Wl,-R/usr/local/cuda-9.0/lib64 -lcudart -o /home/zhangkf/tf/tf-faster-rcnn-master/lib/nms/gpu_nms.cpython-36m-x86_64-linux-gnu.so
rm -rf build
- 5. 安裝COCO API
cd data
git clone https://github.com/pdollar/coco.git
cd coco/PythonAPI
make
cd ../../..
2.2. 執行demo.py
-
1. 下載預訓練模型:這一步下載需要翻牆往往下載不成功,因此可以在此網盤中下載:百度網盤提取碼:kw53
-
下載後放在data目錄下進行解壓
tar xvf voc_0712_80k-110k.tgz
-
2. 建立預訓練模型的軟連接:這一步的目的是在
tf-faster-rcnn
目錄下建立output
文件夾,並使用軟連接來使用預訓練模型,使用以下代碼這裏按照步驟走就行:
NET=res101
TRAIN_IMDB=voc_2007_trainval+voc_2012_trainval
mkdir -p output/${NET}/${TRAIN_IMDB}
cd output/${NET}/${TRAIN_IMDB}
ln -s ../../../data/voc_2007_trainval+voc_2012_trainval ./default
cd ../../..
- 3. demo測試:
GPU_ID=0 # GPU_ID爲顯卡列表;可以爲01...
CUDA_VISIBLE_DEVICES=${GPU_ID} ./tools/demo.py
- 4. 最終執行結果如下:
2019-10-21 09:45:11.064981: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1356] Found device 0 with properties:
name: TITAN Xp major: 6 minor: 1 memoryClockRate(GHz): 1.582
pciBusID: 0000:65:00.0
totalMemory: 11.91GiB freeMemory: 10.26GiB
2019-10-21 09:45:11.065014: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0
2019-10-21 09:45:11.349740: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-10-21 09:45:11.349778: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0
2019-10-21 09:45:11.349787: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N
2019-10-21 09:45:11.349962: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 9928 MB memory) -> physical GPU (device: 0, name: TITAN Xp, pci bus id: 0000:65:00.0, compute capability: 6.1)
Loaded network output/res101/voc_2007_trainval+voc_2012_trainval/default/res101_faster_rcnn_iter_110000.ckpt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo for data/demo/000456.jpg
Detection took 2.120s for 300 object proposals
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo for data/demo/000542.jpg
Detection took 0.084s for 300 object proposals
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo for data/demo/001150.jpg
Detection took 0.120s for 300 object proposals
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo for data/demo/001763.jpg
Detection took 0.106s for 300 object proposals
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo for data/demo/004545.jpg
Detection took 0.117s for 300 object proposals
2.3. 使用訓練好的faster模型對數據進行測試
- 這裏有點地方需要改:首先把
tf-faster-rcnn/lib/datasets/voc_eval.py
的第121行的
with open(cachefile,'w') as f
改成:
with open(cachefile,'wb') as f
- 同時還要把第
105
行的
cachefile = os.path.join(cachedir, '%s_annots.pkl' % imagesetfile)
改成:
cachefile = os.path.join(cachedir, '%s_annots.pkl' % imagesetfile.split("/")[-1].split(".")[0])
- 然後再進行測試:
GPU_ID=0
./experiments/scripts/test_faster_rcnn.sh $GPU_ID pascal_voc_0712 res101
- 等待一段時間,最終測試結果如下:
Saving cached annotations to /home/zhangkf/tf/tf-faster-rcnn-master/data/VOCdevkit2007/annotations_cache/test_annots.pkl
AP for aeroplane = 0.8300
AP for bicycle = 0.8684
AP for bird = 0.8136
AP for boat = 0.7407
AP for bottle = 0.6852
AP for bus = 0.8764
AP for car = 0.8804
AP for cat = 0.8830
AP for chair = 0.6245
AP for cow = 0.8679
AP for diningtable = 0.7080
AP for dog = 0.8852
AP for horse = 0.8727
AP for motorbike = 0.8297
AP for person = 0.8273
AP for pottedplant = 0.5327
AP for sheep = 0.8108
AP for sofa = 0.7752
AP for train = 0.8361
AP for tvmonitor = 0.7924
Mean AP = 0.7970
~~~~~~~~
Results:
0.830
0.868
0.814
0.741
0.685
0.876
0.880
0.883
0.624
0.868
0.708
0.885
0.873
0.830
0.827
0.533
0.811
0.775
0.836
0.792
0.797
~~~~~~~~
--------------------------------------------------------------
Results computed with the **unofficial** Python eval code.
Results should be very close to the official MATLAB eval code.
Recompute with `./tools/reval.py --matlab ...` for your paper.
-- Thanks, The Management
--------------------------------------------------------------
579.71user 119.19system 12:20.83elapsed 94%CPU (0avgtext+0avgdata 2226548maxresident)k
0inputs+80728outputs (0major+5967443minor)pagefaults 0swaps
- 到這裏,前面的這些步驟都是在運行源碼,以及利用訓練好的模型進行測試。
2.4. 訓練Pascal VOC數據集
-
首先下載VGG模型:百度網盤提取碼:2e0y ;然後在
data
目錄下創建一個imagenet_weights
文件夾,解壓權重數據並把解壓後的vgg_16.ckpt
重命名爲vgg16.ckpt
,因爲後面在調用權重數據的時候名字需要對應的上。 -
現在就可以進行訓練了,但是爲了節省時間並排除錯誤,我把迭代次數只設置了
500
次,具體操作爲:
# 首先把
./experiments/scripts/train_faster_rcnn.sh #把這個文件裏的第22行把ITERS=70000改成ITERS=500,
# 其次把
./experiments/scripts/test_faster_rcnn.sh #把這個文件裏的的ITERS也改成500。
-
注意:因爲我使用的是
pascal_voc
數據集,所以只需要更改對應數據集的ITERS
的就行了,訓練和測試的都要改,因爲在train_faster_rcnn.sh
的末尾會執行test_faster_rcnn.sh
。 -
開始訓練(這裏最後的
vgg16
就是對應的權重數據,名字要對的上,0
是GPU
的ID
,pascal_voc
是訓練使用的數據集):
./experiments/scripts/train_faster_rcnn.sh 0 pascal_voc vgg16
- 訓練過程的
loss
:
Fix VGG16 layers..
Fixed.
iter: 20 / 500, total loss: 1.995727
>>> rpn_loss_cls: 0.339967
>>> rpn_loss_box: 0.060159
>>> loss_cls: 0.901823
>>> loss_box: 0.561943
>>> lr: 0.001000
speed: 0.608s / iter
iter: 40 / 500, total loss: 1.055077
>>> rpn_loss_cls: 0.703311
>>> rpn_loss_box: 0.217334
>>> loss_cls: 0.002587
>>> loss_box: 0.000000
>>> lr: 0.001000
speed: 0.512s / iter
- 訓練結果:
VOC07 metric? Yes
AP for aeroplane = 0.0498
AP for bicycle = 0.2000
AP for bird = 0.1067
AP for boat = 0.0109
AP for bottle = 0.0003
AP for bus = 0.0795
AP for car = 0.1496
AP for cat = 0.2337
AP for chair = 0.0538
AP for cow = 0.0649
AP for diningtable = 0.0122
AP for dog = 0.2165
AP for horse = 0.2233
AP for motorbike = 0.1858
AP for person = 0.2117
AP for pottedplant = 0.0075
AP for sheep = 0.0453
AP for sofa = 0.1428
AP for train = 0.0957
AP for tvmonitor = 0.0547
Mean AP = 0.1072
~~~~~~~~
Results:
0.050
0.200
0.107
0.011
0.000
0.080
0.150
0.234
0.054
0.065
0.012
0.216
0.223
0.186
0.212
0.007
0.045
0.143
0.096
0.055
0.107
~~~~~~~~
--------------------------------------------------------------
Results computed with the **unofficial** Python eval code.
Results should be very close to the official MATLAB eval code.
Recompute with `./tools/reval.py --matlab ...` for your paper.
-- Thanks, The Management
--------------------------------------------------------------
420.61user 79.41system 9:59.83elapsed 83%CPU (0avgtext+0avgdata 3191188maxresident)k
三. 使用自己的數據集進行訓練+測試
3.1. 數據集製作
- 此部分爲替換自己的
voc
格式的數據集:DL筆記:PascalVOC 數據集介紹+數據集標註工具! - 這裏補充一下:把一個目錄下的文件名字按序號命名:比如我們將圖片的名字修改爲
000001.jpg
這種格式的,統一命名方法,可以參考如下代碼(重要)! - 1. MATLAB代碼實現如下
%%
%圖片保存路徑爲:
%E:\image\car
%E:\image\person
%car和person是保存車和行人的文件夾
%這些文件夾還可以有多個,
%放在image文件夾裏就行
%該代碼的作用是將圖片名字改成000123.jpg這種形式
%%
clc;
clear;
maindir='E:\image\';
name_long=5; %圖片名字的長度,如000123.jpg爲6,最多9位,可修改
num_begin=1; %圖像命名開始的數字如000123.jpg開始的話就是123
subdir = dir(maindir);
n=1;
for i = 1:length(subdir)
if ~strcmp(subdir(i).name ,'.') && ~strcmp(subdir(i).name,'..')
subsubdir = dir(strcat(maindir,subdir(i).name));
for j=1:length(subsubdir)
if ~strcmp(subsubdir(j).name ,'.') && ~strcmp(subsubdir(j).name,'..')
img=imread([maindir,subdir(i).name,'\',subsubdir(j).name]);
imshow(img);
str=num2str(num_begin,'%09d');
newname=strcat(str,'.jpg');
newname=newname(end-(name_long+3):end);
system(['rename ' [maindir,subdir(i).name,'\',subsubdir(j).name] ' ' newname]);
num_begin=num_begin+1;
fprintf('當前處理文件夾%s',subdir(i).name);
fprintf('已經處理%d張圖片\n',n);
n=n+1;
pause(0.1);%可以將暫停去掉
end
end
end
end
- 2. python代碼實現如下
import os
path = "E:\\image"
filelist = os.listdir(path) #該文件夾下所有的文件(包括文件夾)
count=0
for file in filelist:
print(file)
for file in filelist: #遍歷所有文件
Olddir=os.path.join(path,file) #原來的文件路徑
if os.path.isdir(Olddir): #如果是文件夾則跳過
continue
filename=os.path.splitext(file)[0] #文件名
filetype=os.path.splitext(file)[1] #文件擴展名
Newdir=os.path.join(path,str(count).zfill(6)+filetype) #用字符串函數zfill 以0補全所需位數
os.rename(Olddir,Newdir)#重命名
count+=1
- 把一個目錄下的jpg格式的圖片轉換成png格式
import os
import cv2
import sys
import numpy as np
path = './test/'
newpath = './test_jpg_png/'
print(path)
for filename in os.listdir(path):
if os.path.splitext(filename)[1] == '.jpg':
# print(filename)
img = cv2.imread(path + filename)
print(filename.replace(".jpg", ".png"))
newfilename = filename.replace(".jpg", ".png")
# cv2.imshow("Image",img)
# cv2.waitKey(0)
cv2.imwrite(newpath + newfilename, img)
3.2. 開始訓練
- 數據集製作好了之後,就開始替換自己的數據了:首先,在
tf-faster-rcnn/lib/datasets
目錄下的pascal_voc.py
裏第36
行更改自己的類別,’__background__
'切記不可刪掉,把後面的原來的20
個label
換成自己的,不用更改類別數目,也沒有地方可以更改。
-
然後把你的
xml
文件放置在VOCdevkit2007/VOC2007/Annotations
路徑下,記得把原來的刪掉;同時把你的png
文件放在VOCdevkit2007/VOC2007/JPEGImages
路徑下,xml
和png
替換完了,現在該txt
了,把之前matlab
生成是四個txt
文檔放在VOCdevkit2007/VOC2007/ImageSets/Layout
和VOCdevkit2007/VOC2007/ImageSets/Main
。 -
在開始訓練之前,還需要把之前訓練產生的模型以及
cache
刪除掉,分別在tf-faster-rcnn/output/vgg16/voc_2007_trainval/default
路徑下和tf-faster-rcnn/data/cache
路徑下,然後就可以開始訓練了:
./experiments/scripts/train_faster_rcnn.sh 01 pascal_voc vgg16
- 解析
train_faster_rcnn.sh
文件:
#!/bin/bash
set -x # 將後面執行的命令輸出到屏幕
set -e # 如果命令的返回值不是0 則退出shell
export PYTHONUNBUFFERED="True" # 和緩存有關係的一個變量,使得按順序輸出
GPU_ID=$1 # 這一部分是讀取命令信息,包括GPU的編號,網絡類型,以及數據集類型等
DATASET=$2
NET=$3
array=( $@ )
len=${#array[@]}
EXTRA_ARGS=${array[@]:3:$len}
EXTRA_ARGS_SLUG=${EXTRA_ARGS// /_}
case ${DATASET} in # 根據輸入數據類型,進行不同的處理,分爲4種情況pascal_voc; 07+12; coco; 錯誤類型
pascal_voc)
TRAIN_IMDB="voc_2007_trainval" # 定義相應的變量
TEST_IMDB="voc_2007_test"
STEPSIZE="[50000]"
ITERS=100000 # 定義迭代次數
ANCHORS="[8,16,32]"
RATIOS="[0.5,1,2]"
;;
pascal_voc_0712)
TRAIN_IMDB="voc_2007_trainval+voc_2012_trainval"
TEST_IMDB="voc_2007_test"
STEPSIZE="[80000]"
ITERS=110000 # 定義迭代次數
ANCHORS="[8,16,32]"
RATIOS="[0.5,1,2]"
;;
coco)
TRAIN_IMDB="coco_2014_train+coco_2014_valminusminival"
TEST_IMDB="coco_2014_minival"
STEPSIZE="[350000]"
ITERS=490000
ANCHORS="[4,8,16,32]"
RATIOS="[0.5,1,2]"
;;
*)
echo "No dataset given"
exit
;;
esac
# 訓練日誌的存儲路徑
LOG="experiments/logs/${NET}_${TRAIN_IMDB}_${EXTRA_ARGS_SLUG}_${NET}.txt.`date +'%Y-%m-%d_%H-%M-%S'`"
exec &> >(tee -a "$LOG")
echo Logging output to "$LOG"
# 加載網絡訓練的相關參數
set +x
if [[ ! -z ${EXTRA_ARGS_SLUG} ]]; then
NET_FINAL=output/${NET}/${TRAIN_IMDB}/${EXTRA_ARGS_SLUG}/${NET}_faster_rcnn_iter_${ITERS}.ckpt
else
NET_FINAL=output/${NET}/${TRAIN_IMDB}/default/${NET}_faster_rcnn_iter_${ITERS}.ckpt
fi
set -x
# 開始進行訓練
if [ ! -f ${NET_FINAL}.index ]; then
if [[ ! -z ${EXTRA_ARGS_SLUG} ]]; then
CUDA_VISIBLE_DEVICES=${GPU_ID} time python ./tools/trainval_net.py \ # 加載train_net.py進行訓練;
--weight data/imagenet_weights/${NET}.ckpt \ # weight:預訓練模型的參數
--imdb ${TRAIN_IMDB} \ # imdb:訓練的數據集,別名:imdb_name
--imdbval ${TEST_IMDB} \ # imdbval:測試的數據集,別名:imdbval_name
--iters ${ITERS} \ # iters:迭代次數,別名:max_iters
--cfg experiments/cfgs/${NET}.yml \ # cfg:網絡配置文件,別名:cfg_file
--tag ${EXTRA_ARGS_SLUG} \
--net ${NET} \ # net:網絡模型
--set ANCHOR_SCALES ${ANCHORS} ANCHOR_RATIOS ${RATIOS} \ # set:設置配置參數——ANCHOR_SCALES和ANCHO_RATIOS,別名:set_cfgs
TRAIN.STEPSIZE ${STEPSIZE} ${EXTRA_ARGS}
else
CUDA_VISIBLE_DEVICES=${GPU_ID} time python ./tools/trainval_net.py \
--weight data/imagenet_weights/${NET}.ckpt \
--imdb ${TRAIN_IMDB} \
--imdbval ${TEST_IMDB} \
--iters ${ITERS} \
--cfg experiments/cfgs/${NET}.yml \
--net ${NET} \
--set ANCHOR_SCALES ${ANCHORS} ANCHOR_RATIOS ${RATIOS} \
TRAIN.STEPSIZE ${STEPSIZE} ${EXTRA_ARGS}
fi
fi
# 將後面執行的命令輸出到屏幕, 執行測試算法!
./experiments/scripts/test_faster_rcnn.sh $@
四. 知識點補充
補充1:linux創建連接命令ln -s解讀
- ln 的功能是爲某一個文件在另外一個位置建立一個同步的鏈接,這個命令最常用的參數是-s,具體用法是:
ln -s 源文件 目標文件
。 - 當在不同的目錄,用到相同的文件時,可以不需要在每一個需要的目錄下都放一個必須相同的文件,只要在某個固定的目錄,放上該文件,然後在其它的目錄下用ln命令鏈接(link)它就可以,不必重複的佔用磁盤空間。例如:
ln -s /bin/hello.sh /usr/local/bin/hello -s 是代號(symbolic)的意思。
- 這裏有兩點要注意:
- 第一,
ln
命令會保持每一處鏈接文件的同步性,也就是說,不論你改動了哪一處,其它的文件都會發生相同的變化; - 第二,
ln
的鏈接又軟鏈接 和硬鏈接兩種,軟鏈接就是ln -s src dst
,它只會在你選定的位置上生成一個文件的鏡像,不會佔用磁盤空間,硬鏈接ln src dst
,沒有參數-s
, 它會在你選定的位置上生成一個和源文件大小相同的文件,無論是軟鏈接還是硬鏈接,文件都保持同步變化。 - 連接的刪除: 直接
rm dst
,例如:
rm /usr/local/bin/hello
補充2:Nvidia SMI -GPU解讀
- 打開終端輸入:
nvidia-smi
這是靜止狀態,想要一直動態顯示怎麼辦? - 在終端輸入
watch -n 5 nvidia-smi
這樣就是每5秒刷新一次窗口,只要窗口不關閉,它一直運行;
補充3:ubuntu開放指定端口
- 需要在服務器上開啓
web
服務讓別人訪問的時候遇到一些問題,在內網中別人使用ip
加端口訪問的時候一直訪問不到,折騰了半天,發現原來使端口沒開放了解到一般linux
中端口都是默認關閉的,需要開啓的時候需要自己開啓。 - 開放端口,這裏就介紹一下Ubuntu下的方法
- 安裝
iptables
:一般情況下,ubuntu
安裝好的時候,iptables
會被安裝上,如果沒有的話那就安裝上吧
sudo apt-get install iptables
- 添加規則在終端輸入;中間的
80
爲所需要開放的端口;
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
- 保存規則在終端輸入
iptables-save
- 完成上述命令我們就完成了開放指定的端口,但是如果此時服務器重啓,上述規則就沒有了,所以我們需要對規則進行一下持續化操作,這裏我們需要在安裝一下工具來幫我們實現,這裏我們使用
iptables-persistent
- 安裝
iptables-persistent
sudo apt-get install iptables-persistent
- 持久化規則
sudo netfilter-persistent save
sudo netfilter-persistent reload
- 完成上述操作就可以永久打開我們需要的端口了