影像辨識
Python影像辨識筆記(九之四):可視化YOLOv3訓練過程中的loss、IOU、avg Recall等的曲線圖
以下程式需要用到matplotlib和pandas兩個套件 ,使用TX2的話,請先參考以下文章進行套件的安裝
NVIDIA Jetson TX2學習筆記(五): 安裝matplotlib和pandas
1.訓練YOLOv3模型時,使用下列指令,將訓練過程保存到trainRecord.log中
./darknet detector train cfg/voc.data cfg/yolov3.cfg darknet53.conv.74 -gpus 0 |tee -a trainRecord.txt
2.建立三個.py檔案(extract_log.py、train_iou_visualization.py、train_loss_visualization.py)
extract_log.py:將trainRecord.log的文字內容進行轉換處理,並分別存成:train_log_loss.txt和train_log_iou.txt
#!/usr/bin/python
#coding=utf-8
#该文件用于提取训练log,去除不可解析的log后使log文件格式化,生成新的log文件供可视化工具绘图
import inspect
import os
import random
import sys
def extract_log(log_file, new_log_file, key_word):
with open(log_file, 'r') as f:
with open(new_log_file, 'w') as train_log:
for line in f:
#去除多GPU的同步log;去除除零错误的log
if ('Syncing' in line) or ('nan' in line):
continue
if key_word in line:
train_log.write(line)
f.close()
train_log.close()
extract_log('trainRecord.log', 'train_log_loss.txt', 'images')
extract_log('trainRecord.log', 'train_log_iou.txt', 'IOU')
train_loss_visualization.py:視覺化loss
#!/usr/bin/python
#coding=utf-8
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#根据自己的log_loss.txt中的行数修改lines, 修改训练时的迭代起始次数(start_ite)和结束次数(end_ite)。
lines = 5374
start_ite = 1 #log_loss.txt里面的最小迭代次数
end_ite = 5000 #log_loss.txt里面的最大迭代次数
step = 10 #跳行数,决定画图的稠密程度
igore = 0 #当开始的loss较大时,你需要忽略前igore次迭代,注意这里是迭代次数
#y_ticks = [0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4]#纵坐标的值,可以自己设置。
data_path = 'train_log_loss.txt' #log_loss的路径。
####-----------------只需要改上面的,下面的可以不改动
names = ['loss', 'avg', 'rate', 'seconds', 'images']
result = pd.read_csv(data_path, skiprows=[x for x in range(lines) if (x<lines*1.0/((end_ite - start_ite)*1.0)*igore or x%step!=9)], error_bad_lines=\
False, names=names)
result.head()
for name in names:
result[name] = result[name].str.split(' ').str.get(1)
result.head()
result.tail()
for name in names:
result[name] = pd.to_numeric(result[name])
result.dtypes
print(result['avg'].values)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
###-----------设置横坐标的值。
x_num = len(result['avg'].values)
tmp = (end_ite-start_ite - igore)/(x_num*1.0)
x = []
for i in range(x_num):
x.append(i*tmp + start_ite + igore)
#print(x)
print('total = %d\n' %x_num)
print('start = %d, end = %d\n' %(x[0], x[-1]))
###----------
ax.plot(x, result['avg'].values, label='avg_loss')
#ax.plot(result['loss'].values, label='loss')
#plt.yticks(y_ticks)#如果不想自己设置纵坐标,可以注释掉。
plt.grid()
ax.legend(loc = 'best')
ax.set_title('The loss curves')
ax.set_xlabel('batches')
fig.savefig('loss')
train_iou_visualization.py:視覺化iou
#!/usr/bin/python
#coding=utf-8
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#根据log_iou修改行数
lines = 5374
step = 5000
start_ite = 100
end_ite = 10000
igore = 100
data_path = 'train_log_iou.txt' #log_loss的路径。
names = ['Region Avg IOU', 'Class', 'Obj', 'No Obj', '.5_Recall', '.7_Recall', 'count']
#result = pd.read_csv('log_iou.txt', skiprows=[x for x in range(lines) if (x%10==0 or x%10==9)]\
result = pd.read_csv(data_path, skiprows=[x for x in range(lines) if (x<lines*1.0/((end_ite - start_ite)*1.0)*igore or x%step!=0)]\
, error_bad_lines=False, names=names)
result.head()
for name in names:
result[name] = result[name].str.split(': ').str.get(1)
result.head()
result.tail()
for name in names:
result[name] = pd.to_numeric(result[name])
result.dtypes
####--------------
x_num = len(result['Region Avg IOU'].values)
tmp = (end_ite-start_ite - igore)/(x_num*1.0)
x = []
for i in range(x_num):
x.append(i*tmp + start_ite + igore)
#print(x)
print('total = %d\n' %x_num)
print('start = %d, end = %d\n' %(x[0], x[-1]))
####-------------
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x, result['Region Avg IOU'].values, label='Region Avg IOU')
#ax.plot(result['Avg Recall'].values, label='Avg Recall')
plt.grid()
ax.legend(loc='best')
ax.set_title('The Region Avg IOU curves')
ax.set_xlabel('batches')
fig.savefig('iou')
3.成果
loss曲線

IOU曲線

參考資料
Python影像辨識筆記(九之三):YOLOv3結合深度學習的Object Detector
原文Training YOLOv3 : Deep Learning based Custom Object Detector
Github程式碼Repo:https://github.com/spmallick/learnopencv/tree/master/YOLOv3-Training-Snowman-Detector
YOLOv3的訓練流程
取得資料
要分類的照片
python3 getDataFromOpenImages_snowman.py
已經標記的Class名稱.csv
(wget
https://storage.googleapis.com/openimages/2018_04/class-descriptions-boxable.csv)
需要被標記的檔案.csv
(wget
https://storage.googleapis.com/openimages/2018_04/train/train-annotations-bbox.csv)
切成訓練集和測試集
訓練集70%~90%
測試集10~30%
python3 splitTrainAndTest.py /full/path/to/snowman/JPEGImages/
Darknet
下載與編譯Darknet
cd ~
git clone https://github.com/pjreddie/darknet
cd darknet
make
修改examples/detector.c的內容
把
if(i%10000==0 || (i < 1000 && i%100 == 0)){
改成:
if(i%1000==0 || (i < 2000 && i%200 == 0)){
#每200次迭代存檔一次,2000次後,每1000次迭代存檔一次
資料標記
Labels資料夾中的檔案有:
<object-class-id> <center-x> <center-y> <width> <height>
object-class-id是物件的class屬性(只辨識1種就寫0就好)
center-x和center-y代表著標記框框的中心X座標和中心Y座標(px為單位)
width和height代表標記框框的寬度和高度(px為單位)

下載預先訓練的模型
運用遷移學習的方式,可以產生不錯的訓練效果
cd ~/darknet
wget https://pjreddie.com/media/files/darknet53.conv.74 -O ~/darknet/darknet53.conv.74
資料檔案
針對darknet.data,提供連結到相關檔案的路徑
#只訓練一種標籤的話,classes必須=1
#路徑必須為絕對路徑
#classes.names檔案包含有classes的名稱
#backup資料夾用來保存訓練的weights存放路徑
classes = 1
train = /path/to/snowman/snowman_train.txt
valid = /path/to/snowman/snowman_test.txt
names = /path/to/snowman/classes.names
backup = /path/to/snowman/weights/
YOLOv3的參數設定
[net]
# Testing
# batch=1
# subdivisions=1
# Training
batch=64
subdivisions=16
#batch=64代表在一次迭代中,有64張圖片被拿來訓練,以更新神經網路的參數
#subdivisions是拿來處理GPU記憶體不足的問題,可以使用1,2,4,8,16來測測看
#subdivisions=16代表GPU每次處理(batch/subdivisions)=64/16=4張圖片
#在測試過程中batch和subdivisions都會被設定成1
width=416 #代表圖片寬度將被修改尺寸成416
height=416 #代表圖片高度將被修改尺寸成416
channels=3 #代表使用RGB,共3個頻道來處理圖片
momentum=0.9 #拿來懲罰權重變動太過劇烈(防止Over-fitting)
decay=0.0005 #預設值即可,同樣拿來處理Over-fitting
learning_rate=0.001
policy=steps
steps=3800
scales=.1
burn_in=400
# learning_rate控制學習的幅度(通常在0.01~0.0001),剛開始訓練時,因為對資料不了解,學習率高一點(大膽的學習),隨著對資料的熟悉,必須下降學習率(謹慎的學習)
#在上面的案例中,學習率會在達到第3800次迭代時,乘上scales(此例為.1),來獲取新的學習率。我們也可以指定多個steps和scales。
#burn_in peroid參數又被稱作為warm-up period
Data augmentation(資料增強)
#同樣的雪人圖片,使用不同的角度、飽和度、曝光、色調,依舊還是雪人的圖片
angle=0 #角度
saturation = 1.5 #飽和度
exposure = 1.5 #曝光
hue=.1 #色調
#使用預設值做訓練
Number of iterations迭代的次數
max_batches=5200
#1個class標籤有5200次迭代已經很充足了
#對一個擁有n個標籤的物件偵測器,至少需要訓練2000*n個batches
訓練YOLOv3
cd ~/darknet
./darknet detector train /path/to/snowman/darknet.data /path/to/snowman/darknet-yolov3.cfg ./darknet53.conv.74 > /path/to/snowman/train.log
#確保給予正確的路徑,避免出現錯誤
#訓練記錄保存在train.log中
#即時監控訓練losss
grep “avg” /path/to/snowman/train.log
#顯示目前batch中的batch number、loss、截至目前為止的平均batch、目前的學習率、此次batch所花費的時間、截至目前為止已經使用的圖片數量
(batch number, loss in the current batch,
average loss till the current batch, current learning rate, time taken for the
batch and images used till current batch.)
何時停止訓練?
#繪製avg loss
python3 plotTrainLoss.py /full/path/to/train.log
測試訓練出來的Model
用嶄新的資料來測試我們訓練出來的模型
提供object_detection_yolo.py中,modelConfiguration和modelWeights的正確路徑
#測試model
python3 object_detection_yolo.py –image=snowmanImage.jpg
Python影像辨識筆記(九之二):關於YOLOv3的一些心得
1.使用純CPU訓練時,defaults.py中的batch、epoch、learning rate(lr)都不可以調太高。(會因為記憶體不足而造成當機問題產生)
batch=1、epoch=1、learning rate=1e-4,電腦不會當機(CPU為i5-2400)
2.要使用GPU訓練時,最好用性能較高的顯示卡,網路上看到大多使用GTX1080 Ti在跑訓練(以我自己的電腦為例,GTX 750 Ti,都會出現GPU記憶體不足的錯誤情形)
3.圖片的標記需要使用labelimg來進行標記,會產出xml檔案(VOC格式,需要將VOC格式的xml文件轉換成YOLO格式的txt文件),或txt檔案(YOLO格式)
4.YOLO中的cfg設定要注意

5.一定要安裝Visual C++ 2015 build tools ,不然會有很多錯誤問題產生
6.路徑最好使用「絕對路徑」比較不會有錯誤產生
7.cfg參數調整:如果顯示卡記憶體太小,將random調整成0、subdivision調大
8.在上次的記憶點重新訓練(加上 -1 )python flow --model cfg/yolo3.cfg --load-1--train --annotation train/annotations --dataset train/images
9.訓練好的Model怎麼進行預測
方法1 在darkflow資料夾中有一個ckpt資料夾,裡面有checkpoint和.meta和.profile檔。先產生.pb檔,再進行預測python ./flow --model cfg/yolov2-tiny-test.cfg --load bin/yolov2-tiny.weights--savepbpython ./flow--pbLoadbuilt_graph/yolov2-tiny-test.pb --metaLoad built_graph/yolov2-tiny-test.meta --imgdir sample_img/
方法2
直接用.cfg和.weights檔進行預測
python ./flow --model cfg/yolov2-tiny-test.cfg --load bin/yolov2-tiny.weights --imgdir sample_img/
10.更多結果參考Python影像辨識筆記(九):分別在Windows和Ubuntu 18.04上安裝並執行YOLOv3(使用GPU)持續更新,本文也會同步更新。
