基於SwinTransformer的目標檢測訓練模型學習總結
一、簡要介紹
Swin Transformer是2021年提出的,是一種基於Transformer的一種深度學習網絡結構,在目標檢測、實例分割等計算機視覺任務上均取得了SOTA的性能。同時這篇論文也獲得了ICCV2021年的Best Paper。
1.1 Transformer的關鍵里程碑
- Tranformer: 在2017年6月,僅基於注意力機制的Transformer首次由谷歌提出,應用於NLP自然語言處理的任務上表現出了良好的性能。
- BERT: 在2018年10月,預訓練Transformer模型開始在NLP領域中占主導地位。
- GPT-3: 在2020年5月,提出一個帶有170億參數的大型Transformer,向通用NLP模型邁出了一大步。
- DETR: 在2020年5月,提出一個簡單而有效的高層視覺框架,將目標檢測視為一個直接集預測問題。
- iGPT: 在2020年7月,針對NLP的模型也可以用於圖像預訓練。
- VIT: 在2020年10月,純Transformer架構適用於可視化識別
- IPT: 在2020年12月,第一個結合多任務的低層視覺變換Transformer模型
- VIT Variants: 在2021年,提出基於VIT模型的幾種變體,例如DeiT、PVT、TNT、Swin。
Swin Transformer是由微軟亞洲研究院提出的一種Transformer結構模型,它取得了多個計算機視覺任務和數據集上的SOTA性能,這些任務包括目標檢測、實例分割和語義分割,圖像分類。它可以用作計算機視覺的通用backbone。在NLP和CV兩個領域之間的差異,例如視覺實體尺度的巨大差異以及與文字中的單詞相比,圖像中像素的高分辨率,帶來了使Transformer從語言適應視覺方面的挑戰。
1.2 Transformer的網絡結構
和大多數seq2seq模型一樣,transformer的結構也是由encoder和decoder組成。
實際上,Transformer是基於Encoder和Decoder的網絡架構。最初是被用來解決NLP自然語言處理來提出的,主要是用來的處理seq2seq的任務,例如語言的翻譯。它的主要特點是采用了Multi-Head Attention的注意力機制以及Encoder和Decoder之間的Cross相互的注意力機制。
1.3 Swin Transformer的網絡架構
Swin Transformer的優勢在於在ViT的基礎上將hierarchy(層次性)、locality(局部性)、translation invariance(平移不變性)等先驗引入Transformer網絡結構設計從而能在視覺任務中取得更好的性能。
下面分別從幾個特性來介紹:
-
層次性:從上圖可以看到,Image經過Patch Partition傳入,經過多個stage,其中每個stage中分別對其進行Patch Mergeing和Swin Transformer Block的處理,在此過程中Size的大小不斷減少,同時通道數不斷地增加,這就是該結構體現的層次性。
-
局部性:神經網絡的前面幾層應該只探索輸入圖像中的局部區域,而不過度在意圖像中相隔較遠區域的關系,這就是“局部性”原則。最終,可以聚合這些局部特征,以在整個圖像級別進行預測。
-
平移不變性:不管檢測對象出現在圖像中的哪個位置,神經網絡的前面幾層應該對相同的圖像區域具有相似的反應,即為“平移不變性”。卷積神經網絡具有平移不變性,而圖網絡不具有該性質,因此不能直接做卷積操作。平移不變性是一個很有用的性質,尤其是當我們關心某個特征是否出現而不關心它出現的具體位置時。簡單地說,卷積+最大池化約等於平移不變性。
1.4 核心創新點
每個Swin Transformer模塊都由兩個Block組成。
(1)自注意力的計算在局部的非重疊窗口內進行。
(2)在前后兩層的Transformer模塊中,非重疊窗口的配置相比前一層做了半個窗口的移位,使得上一層中不同窗戶的信息進行了交換。
二、目標檢測相關基礎
2.1 目標檢測任務理解與總結
2.2 目標檢測之常用數據集
2.3 目標檢測之性能指標
三、Transformer的介紹及在CV領域內的應用
解碼器與編碼器
Positional Encoding
Decoder
DETR
End to End Object Detection with Transformers
四、Swin Transformer的原理
論文
Ze Liu Yutong Lin Yue Cao Han Hu Yixuan Wei Zheng Zhang Stephen Lin Baining Guo
Swin Transformer : Hierarchical Vision Transformer using Shifted Windows. ICCV 2021
https://arxiv.org/abs/2103.14030
SOTA
Problems of ViT
. Does not consider the difference between textual and visual signals
. Mainly for image classification
Key tech innovation : locality by Shifted windows
• Non-overlapped windows (faster real speed than sliding windows)
• Windows are shifted in the next layer
Hierarchical feature maps
• Windows Multi-Head Self-Attention (W-MSA)
• Shifted Windows Multi-Head Self-Attention (SW-MSA)
1)自注意的計算在局部的非重疊窗口內進行。不同query會共享同樣的key集合,從而對硬件友好
2)在前后兩層的Transformer模塊中,非重疊窗口的配置相比前一層做了半個窗口的移位,使得上一層中不
同窗口的信息進行了交換。
Self-attention in non-overlapped windows
For efficient modeling, we propose to compute self attention within local windows.
The windows are arranged to evenly partition the image in a non-overlapping manner.
Supposing each window contains M × M patches, the computational complexity of a global
MSA module and a window based one on an image of h × w patches are :
The architecture of a Swin Transformer (Swin-T)
Patch Merging
經過Patch Merging后,feature map的高和寬會減半,深度會加倍
Swin Transformer block
Swin Transformer is built by replacing the standard multi-head
self attention (MSA) module in a Transformer block by a module
based on shifted windows, with other layers kept the same.
A Swin Transformer block consists of a shifted window based MSA
module, followed by a 2-layer MLP with GELU nonlinearity in
between.
A LayerNorm (LN) layer is applied before each MSA module and
each MLP, and a residual connection is applied after each module.
Shifted window partitioning in successive blocks
Swin T(Tiny),S(Small),B(Base),L(Large)
• win. sz. 7x7表示使用的窗口(Windows)的大小
• dim表示feature map的channel深度)
• head表示多頭注意力模塊中head的個數
Architecture Variants
where C is the channel number of the hidden layers in the first stage.
Architecture Variants
The window size is set to M = 7 by default. The query dimension of each
head is d = 32, and the expansion layer of each MLP is α = 4.
Illustration of an efficient batch computation approach for self-attention in shifted window partitioning
Experimental Designs
3 datasets to cover various recognition tasks of different granularities
• lmage-level lmageNet-1K classification (1.28M images; 1000 classes).
• Region-level coco object detection (115K images; 80 classes).
• Pixel-level ADE20K semantic segmentation (20K images; 150 classes)
Results on COCO object detection and instance segmentation
Results of semantic segmentation on the ADE20K val and test set
五、Swin Transformer的環境部署和訓練相關
5.1 軟件安裝
1) 安裝Anaconda
Anaconda 是一個用於科學計算的 Python 發行版,支持 Linux, Mac, Windows, 包含了眾多流行的科學
計算、數據分析的 Python 包。
-
先去官方地址下載好對應的安裝包
下載地址:https://www.anaconda.com/download/#linux -
然后安裝anaconda
bash ~/Downloads/Anaconda3-2021.05-Linux-x86_64.sh
anaconda會自動將環境變量添加到PATH里面,如果后面你發現輸入conda提示沒有該命令,那么
你需要執行命令 source ~/.bashrc 更新環境變量,就可以正常使用了。
如果發現這樣還是沒用,那么需要添加環境變量。
編輯~/.bashrc 文件,在最后面加上
export PATH=/home/bai/anaconda3/bin:$PATH
注意:路徑應改為自己機器上的路徑
保存退出后執行: source ~/.bashrc
再次輸入 conda list 測試看看,應該沒有問題。
添加Aanaconda國內鏡像配置
清華TUNA提供了 Anaconda 倉庫的鏡像,運行以下三個命令:
conda config --add channels
https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels
https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --set show_channel_urls yes
2) 安裝pytorch
首先創建一個anaconda虛擬環境,環境名字可自己確定,這里本人使用mypytorch作為環境名:
conda create -n mypytorch python=3.8
安裝成功后激活mypytorch環境:
conda activate mypytorch
注意:10.2處應為cuda的安裝版本號
編輯~/.bashrc 文件,設置使用mypytorch環境下的python3.8
alias python='/home/linxu/anaconda3/envs/mypytorch/bin/python3.8'
注意:python路徑應改為自己機器上的路徑
保存退出后執行: source ~/.bashrc
該命令將自動回到base環境,再執行 conda activate mypytorch 到pytorch環境。
5.2 Swin Transformer項目安裝
1) 安裝mmcv
克隆mmcv項目到本地
git clone -b v1.3.1 https://github.com/open-mmlab/mmcv.git
cd mmcv
MMCV_WITH_OPS=1 pip install -e .
檢查
pip list
2) 安裝mmdetection
參考:https://mmdetection.readthedocs.io/zh_CN/v2.19.1/get_started.html
git clone -b v2.11.0 https://github.com/open-mmlab/mmdetection.git
cd mmdetection
pip install -r requirements/build.txt
pip install -v -e . # or "python setup.py
- 安裝apex
git clone https://github.com/NVIDIA/apex
cd apex
python setup.py install
注意:cuda的版本應和cudatoolkit一致
4)安裝Swin-Transformer-Object-Detection
git clone https://github.com/SwinTransformer/Swin-Transformer-ObjectDetection.git
執行
cd Swin-Transformer-Object-Detection
python setup.py develop
下載預訓練權重文件
下載mask_rcnn_swin_tiny_patch4_window7_1x.pth權重文件,並放置在Swin-Transformer-ObjectDetection文件夾下
百度網盤下載鏈接:
鏈接:https://pan.baidu.com/s/1cO3ln3fokP3cazveC-bjuw
提取碼:uzzk
測試命令:
python demo/image_demo.py demo/demo.jpg
configs/swin/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-800_adamw_1x_coco.py
mask_rcnn_swin_tiny_patch4_window7_1x.pth
5.3.標注自己的數據集
- 安裝圖像標注工具labelImg
克隆labelImg
git clone https://github.com/tzutalin/labelImg.git
使用Anaconda安裝
到labelImg路徑下執行命令
conda install pyqt=5
pip install lxml
pyrcc5 -o libs/resources.py resources.qrc
python labelImg.py
- 添加自定義類別
修改文件labelImg/data/predefined_classes.txt
ball
messi
trophy
3)使用labelImg進行圖像標注
用labelImg標注生成PASCAL VOC格式的xml標記文件。例如:
width =1000
height = 654
PASCAL VOC標記文件如下:
5.4 准備自己的數據集
- 下載項目文件
從百度網盤下載
VOCdevkit_bm.zip (下載到並解壓)
prepare_mydata.py
pascal_voc.py
testfiles.zip (下載到Swin-Transformer-Object-Detection目錄下並解壓)
鏈接:https://pan.baidu.com/s/1cO3ln3fokP3cazveC-bjuw
提取碼:uzzk
2)解壓建立或自行建立數據集
使用PASCAL VOC數據集的目錄結構:
建立文件夾層次為 VOCdevkit / VOC2007
VOC2007下面建立三個文件夾:Annotations,JPEGImages和ImageSets/Main
JPEGImages放所有的數據集圖片;Annotations放所有的xml標記文件;ImageSets/Main下存放訓練
集、驗證集、測試集划分文件(目前為空)
執行python腳本:
python prepare_mydata.py
注意根據自己的數據集修改其中的classes=["ball","messi"]
ImageSets/Main目錄下可以看到生成四個文件
- train.txt給出了訓練集圖片文件的列表(不含文件名后綴)
- val.txt給出了驗證集圖片文件的列表
- test.txt給出了測試集圖片文件的列表
- trainval.txt給出了訓練集和驗證集圖片文件的列表
4)PASCAL VOC數據格式轉換成COCO數據格式
執行python腳本
python pascal_voc.py VOCdevkit --out-dir mycoco --out-format coco
注意根據自己的數據集修改其中的voc_classes = ["ball", "messi"]
然后,把轉成的COCO數據格式的數據的目錄結構准備成COCO目錄結構格式。
在Swin-Transformer-Object-Detection根目錄下面,創建目錄結構如下:
└── data
├── coco
├── annotations
├── instances_train2017.json
└── instances_val2017.json
├── train2017
└── val2017
其中:
train2017放置voc-images/train2017中的圖片
val2017放置voc-images/val2017中的圖片
voc07_train.json改名為instances_train2017.json
voc07_val.json改名為instances_val2017.json
5.5 修改配置文件
5.5.1 step1
1) 修改changemaskrcnn.py中num_class並執行該腳本, 產生新的權重文件
python changemaskrcnn.py
5.5.2 step2
2)修改 configs/_base_/models/mask_rcnn_swin_fpn.py
中num_classes, 共兩處
5.5.3 step3
3)修改 configs/_base_/default_runtime.py
中interval, load_from
5.5.4 step4
4)修改 configs/swin/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-800_adamw_1x_coco.py
中的 _base_
,max_epochs
, lr
5.5.5 step5
5) 修改 configs/_base_/datasets/coco_detection.py
中的
samples_per_gpu=2,
workers_per_gpu=2,
5.5.6 step6
6)修改mmdet\datasets\coco.py中的CLASSES
另外,如果在訓練時出現錯誤:IndexError: list index out of range
注釋掉coco.py中_segm2json(self, results)函數中的以下語句 (268~271行)
#if isinstance(segms[i]['counts'], bytes):
# segms[i]['counts'] = segms[i]['counts'].decode()
# data['segmentation'] = segms[i]
# segm_json_results.append(data)
5.5.7 step7
為了保持類別和類名一致,需要修改./mmdet/core/evaluation/class_names.py中的內容
同時還需要修改.\mmdet\datasets\coco.py中的內容
最后為了避免第三方庫受之前環境配置的影響,重新編譯一遍源碼。
python setup.py install
5.6 訓練自己的數據集
- 訓練命令
在Swin-Transformer-Object-Detection路徑下執行:
python tools/train.py configs/swin/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-800_adamw_1x_coco.py
- 訓練結果的查看
查看Swin-Transformer-Object-Detection/work_dirs目錄下的文件
5.7 測試訓練出的網絡模型
- 測試圖片
python demo/image_demo.py testfiles/img1.jpg
configs/swin/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-800_adamw_1x_coco.py
work_dirs/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-
800_adamw_1x_coco/latest.pth --score-thr 0.5
2)測試視頻
python demo/video_demo.py testfiles/messi.mp4 configs/swin/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-800_adamw_1x_coco.py
work_dirs/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-
800_adamw_1x_coco/latest.pth --score-thr 0.5 --show
3)性能統計
python tools/test.py configs/swin/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-
800_adamw_1x_coco.py work_dirs/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-
800_adamw_1x_coco/latest.pth --eval bbox
4)日志分析
python tools/analysis_tools/analyze_logs.py plot_curve
work_dirs/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-
800_adamw_1x_coco/20211225_030436.log.json