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曲線

參考資料

YOLO-V3可視化訓練過程中的參數,繪製loss、IOU、avg Recall等的曲線圖

Python文字轉語音(Text TO Speech)

text_file_to_speech.py

安裝

pip install gtts

文字檔案轉語音

# Import the Gtts module for text  
# to speech conversion 
from gtts import gTTS 
  
# import Os module to start the audio file
import os 

fh = open("test.txt", "r")
myText = fh.read().replace("\n", " ")

# Language we want to use 
language = 'en'

output = gTTS(text=myText, lang=language, slow=False)

output.save("output.mp3")
fh.close()

# Play the converted file 
os.system("start output.mp3")

文字轉語音

# Import the Gtts module for text  
# to speech conversion 
from gtts import gTTS 
  
# import Os module to start the audio file
import os 
  
mytext = 'Convert this Text to Speech in Python'
  
# Language we want to use 
language = 'en'
myobj = gTTS(text=mytext, lang=language, slow=False) 
myobj.save("output.mp3") 
  
# Play the converted file 
os.system("start output.mp3") 

如何使用Python讀寫SPSS的檔案

使用Pandas

import pandas as pd

df =pd.read_spss('fileName.sav')
df.tail()
cols = ['ID', 'Day', 'Age', 'Response', 'Gender']
df = pd.read_spss('fileName.sav', usecols=cols)
df.head()

使用Pyreadstat

#讀取
import pyreadstat

df, meta = pyreadstat.read_sav('fileName.sav')

type(df)
df.head()#寫入
pyreadstat.write_sav(df, 'fileName.sav')