Caffe---Pycaffe 繪制loss和accuracy曲線
《Caffe自帶工具包---繪制loss和accuracy曲線》:可以看出使用caffe自帶的工具包繪制loss曲線和accuracy曲線十分的方便簡單,而這種方法看起來貌似只能分開繪制曲線,無法將兩種曲線繪制在一張圖上。但,我們有時為了更加直觀的觀察訓練loss和測試loss,往往需要將這兩種曲線繪制在一張圖上。那如何解決呢?python接口,Pycaffe可以實現將這兩種曲線繪制在一張圖上。
目前,我知道的知識面中,Pycaffe有兩種方式可以畫出loss和accuracy曲線:一種是,根據之前博文里保存的訓練日志.log文件,Pycaffe進行繪制;另一種是,Pycaffe自己進行訓練,訓練完后自動出圖。
目錄
1,Pycaffe---只繪圖(前提已有訓練的.log文件)
2,Pycaffe---訓練+繪圖
正文
1,Pycaffe---只繪圖
這種方式屬於繪制訓練后的loss和accuracy曲線,繪圖所需的信息,利用python從log日志里面獲取。一般步驟:train_xxx_log.sh文件訓練,然后保存xxx.log文件,手動將xxx.log文件名改成xxx.txt,然后用Pycaffe繪圖。
(1)示例,寫一個FromLogTxt_draw_LossAccuracy.py文件(參考:https://blog.csdn.net/u014593748/article/details/76152622):
------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import sys
import re
import matplotlib.pyplot as plt
import numpy as np
in_log_path='/home/wp/caffe/myself/road/Log/record_train_road_log.txt' #輸入日志文件的位置
out_fig_path='/home/wp/caffe/myself/road/Log/record_train_road_log.jpg' #輸出圖片的位置
f=open(in_log_path,'r')
accuracy=[]
train_loss=[]
test_loss=[]
max_iter=0
test_iter=0
test_interval=0
display=0
target_str=['accuracy = ','Test net output #1: loss = ','Train net output #0: loss = ',
'max_iter: ','test_iter: ','test_interval: ','display: ']
while True:
line=f.readline()
# print len(line),line
if len(line)<1:
break
for i in range(len(target_str)):
str=target_str[i]
idx = line.find(str)
if idx != -1:
num=float(line[idx + len(str):idx + len(str) + 5])
if(i==0):
accuracy.append(num)
elif(i==1):
test_loss.append(num)
elif(i==2):
train_loss.append(num)
elif(i==3):
max_iter=float(line[idx + len(str):])
elif(i==4):
test_iter=float(line[idx + len(str):])
elif(i==5):
test_interval=float(line[idx + len(str):])
elif(i==6):
display=float(line[idx + len(str):])
else:
pass
f.close()
# print test_iter
# print max_iter
# print test_interval
# print len(accuracy),len(test_loss),len(train_loss)
_,ax1=plt.subplots()
ax2=ax1.twinx()
#繪制train_loss曲線圖像,顏色為綠色'g'
ax1.plot(display*np.arange(len(train_loss)),train_loss,color='g',label='train loss',linestyle='-')
#繪制test_loss曲線圖像,顏色為黃色'y'
ax1.plot(test_interval*np.arange(len(test_loss)),test_loss,color='y',label='test loss',linestyle='-')
#繪制accuracy曲線圖像,顏色為紅色'r'
ax2.plot(test_interval*np.arange(len(accuracy)),accuracy,color='r',label='accuracy',linestyle='-')
ax1.legend(loc=(0.7,0.8)) #使用二元組(0.7,0.8)定義標簽位置
ax2.legend(loc=(0.7,0.72))
ax1.set_xlabel('iteration')#設置X軸標簽
ax1.set_ylabel('loss') #設置Y1軸標簽
ax2.set_ylabel('accuracy') #設置Y2軸標簽
plt.savefig(out_fig_path,dpi=100) #將圖像保存到out_fig_path路徑中,分辨率為100
plt.show() #顯示圖片
------------------------------------------------------------------------------------
# python FromLogTxt_draw_LossAccuracy.py
(2)或者,在shell下根據XXX.log文件,提取loss值以及accuracy值,保存到test_loss.txt,train_loss.txt,test_acc.txt。參考https://blog.csdn.net/m0_37477175/article/details/78431717。
終端下,進入相應的目錄下:cat train_road_20180525.log | grep "Train net output" | awk '{print $11}',如下:
python+pandas來間接繪圖!首先我們查看一下網絡訓練參數:
#訓練每迭代500次,進行一次預測 test_interval: 500 #每經過100次迭代,在屏幕打印一次運行log display: 100 #最大迭代次數 max_iter: 10000
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Created on Tue Oct 17 2017 @author: jack wang This program for visualize the loss and accuracy """ import pandas as pd import numpy as np import matplotlib.pyplot as plt train_interval = 100 #display = 100 test_interval = 500 max_iter = 10000 def loadData(file): dataMat = [] fr = open(file) for line in fr.readlines(): lineA = line.strip().split() dataMat.append(float(lineA[0])) return dataMat trainloss = loadData('trainloss.txt') testloss = loadData('testloss.txt') trainLoss = pd.Series(trainloss, index = range(0,max_iter,100)) testLoss = pd.Series(testloss, index = range(0,max_iter+500,500)) fig = plt.figure() plt.plot(trainLoss) plt.plot(testLoss) plt.xlabel(u"iter") plt.ylabel(u"loss") plt.title(u"trainloss vs testloss") plt.legend((u'trainloss', u'testloss'),loc='best') plt.show() testacc = loadData('testacc.txt') testAcc = pd.Series(testacc, index = range(0,max_iter+500,500)) plt.plot(testAcc) plt.show()
注明:這種方法,個人沒有順利的做下來,留作下次繼續研究。
2,Pycaffe---訓練+繪圖
這種方式屬於繪制訓練過程的loss和accuracy曲線。一般步驟:Pycaffe自己寫一個文件,里面既能訓練網絡,又能保存信息,然后繪制圖。示例,寫一個Pycaffe_TrainTest_then_loss_accuracy.py(參考https://www.cnblogs.com/denny402/p/5686067.html):
------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
#!/usr/bin/env python
from pylab import *
import matplotlib.pyplot as plt
import caffe
solver = caffe.SGDSolver('/home/wp/caffe/myself/road/prototxt_files/solver.prototxt')
niter = 200
display= 10
test_iter = 200
test_interval =100
train_loss = zeros(ceil(niter * 1.0 / display))
test_loss = zeros(ceil(niter * 1.0 / test_interval))
test_acc = zeros(ceil(niter * 1.0 / test_interval))
solver.step(1)
_train_loss = 0; _test_loss = 0; _accuracy = 0
for it in range(niter):
solver.step(1)
_train_loss += solver.net.blobs['loss'].data
if it % display == 0:
train_loss[it // display] = _train_loss / display
_train_loss = 0
if it % test_interval == 0:
for test_it in range(test_iter):
solver.test_nets[0].forward()
_test_loss += solver.test_nets[0].blobs['loss'].data
_accuracy += solver.test_nets[0].blobs['accuracy'].data
test_loss[it / test_interval] = _test_loss / test_iter
test_acc[it / test_interval] = _accuracy / test_iter
_test_loss = 0
_accuracy = 0
print '\nplot the train loss and test accuracy\n'
_, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(display * arange(len(train_loss)), train_loss, 'g')
ax1.plot(test_interval * arange(len(test_loss)), test_loss, 'y')
ax2.plot(test_interval * arange(len(test_acc)), test_acc, 'r')
ax1.set_xlabel('iteration')
ax1.set_ylabel('loss')
ax2.set_ylabel('accuracy')
plt.show()
plt.pause(0.000001)
------------------------------------------------------------------------------------
# cd caffe
#python Pycaffe_TrainTest_then_loss_accuracy.py
# .py這里放在caffe目錄下,不在caffe目錄下修改相應的路徑即可。
# 代碼含義,根據參考文章理解,.py文件中少出現漢字注釋,否則會出現[ python: can't open file 'Pycaffe_TrainTest_then_loss_accuracy.py002.py': [Errno 2] No such file or directory ]這樣的提示。
最后,訓練完后,就會出現loss和accuracy曲線圖了。設置niter = 200,快速迭代出圖。
附,相關代碼說明:
------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
#加載必要的庫
import matplotlib.pyplot as plt import caffe caffe.set_device(0) caffe.set_mode_gpu() # 使用SGDSolver,即隨機梯度下降算法 solver = caffe.SGDSolver('/home/xxx/mnist/solver.prototxt') # 等價於solver文件中的max_iter,即最大解算次數 niter = 9380 # 每隔100次收集一次數據 display= 100 # 每次測試進行100次解算,10000/100 test_iter = 100 # 每500次訓練進行一次測試(100次解算),60000/64 test_interval =938 #初始化 train_loss = zeros(ceil(niter * 1.0 / display)) test_loss = zeros(ceil(niter * 1.0 / test_interval)) test_acc = zeros(ceil(niter * 1.0 / test_interval)) # iteration 0,不計入 solver.step(1) # 輔助變量 _train_loss = 0; _test_loss = 0; _accuracy = 0 # 進行解算 for it in range(niter): # 進行一次解算 solver.step(1) # 每迭代一次,訓練batch_size張圖片 _train_loss += solver.net.blobs['SoftmaxWithLoss1'].data if it % display == 0: # 計算平均train loss train_loss[it // display] = _train_loss / display _train_loss = 0 if it % test_interval == 0: for test_it in range(test_iter): # 進行一次測試 solver.test_nets[0].forward() # 計算test loss _test_loss += solver.test_nets[0].blobs['SoftmaxWithLoss1'].data # 計算test accuracy _accuracy += solver.test_nets[0].blobs['Accuracy1'].data # 計算平均test loss test_loss[it / test_interval] = _test_loss / test_iter # 計算平均test accuracy test_acc[it / test_interval] = _accuracy / test_iter _test_loss = 0 _accuracy = 0 # 繪制train loss、test loss和accuracy曲線 print '\nplot the train loss and test accuracy\n' _, ax1 = plt.subplots() ax2 = ax1.twinx() # train loss -> 綠色 ax1.plot(display * arange(len(train_loss)), train_loss, 'g') # test loss -> 黃色 ax1.plot(test_interval * arange(len(test_loss)), test_loss, 'y') # test accuracy -> 紅色 ax2.plot(test_interval * arange(len(test_acc)), test_acc, 'r') ax1.set_xlabel('iteration') ax1.set_ylabel('loss') ax2.set_ylabel('accuracy') plt.show()
------------------------------------------------------------------------------------