Python繪制loss曲線和準(zhǔn)確率曲線實(shí)例代碼
引言
使用 python 繪制網(wǎng)絡(luò)訓(xùn)練過(guò)程中的的 loss 曲線以及準(zhǔn)確率變化曲線,這里的主要思想就時(shí)先把想要的損失值以及準(zhǔn)確率值保存下來(lái),保存到 .txt 文件中,待網(wǎng)絡(luò)訓(xùn)練結(jié)束,我們?cè)倌眠@存儲(chǔ)的數(shù)據(jù)繪制各種曲線。
其大致步驟為:數(shù)據(jù)讀取與存儲(chǔ) - > loss曲線繪制 - > 準(zhǔn)確率曲線繪制
一、數(shù)據(jù)讀取與存儲(chǔ)部分
我們首先要得到訓(xùn)練時(shí)的數(shù)據(jù),以損失值為例,網(wǎng)絡(luò)每迭代一次都會(huì)產(chǎn)生相應(yīng)的 loss,那么我們就把每一次的損失值都存儲(chǔ)下來(lái),存儲(chǔ)到列表,保存到 .txt 文件中。保存的文件如下圖所示:
[1.3817585706710815, 1.8422836065292358, 1.1619832515716553, 0.5217241644859314, 0.5221078991889954, 1.3544578552246094, 1.3334463834762573, 1.3866571187973022, 0.7603049278259277]
上圖為部分損失值,根據(jù)迭代次數(shù)而異,要是迭代了1萬(wàn)次,這里就會(huì)有1萬(wàn)個(gè)損失值。
而準(zhǔn)確率值是每一個(gè) epoch 產(chǎn)生一個(gè)值,要是訓(xùn)練100個(gè)epoch,就有100個(gè)準(zhǔn)確率值。
(那么問題來(lái)了,這里的損失值是怎么保存到文件中的呢? 很少有人講這個(gè),也有一些小伙伴們來(lái)咨詢,這里就統(tǒng)一記錄一下,包括損失值和準(zhǔn)確率值。)
首先,找到網(wǎng)絡(luò)訓(xùn)練代碼,就是項(xiàng)目中的 main.py,或者 train.py ,在文件里先找到訓(xùn)練部分,里面經(jīng)常會(huì)有這樣一行代碼:
for epoch in range(resume_epoch, num_epochs): # 就是這一行 #### ... loss = criterion(outputs, labels.long()) # 損失樣例 ... epoch_acc = running_corrects.double() / trainval_sizes[phase] # 準(zhǔn)確率樣例 ... ###
從這一行開始就是訓(xùn)練部分了,往下會(huì)找到類似的這兩句代碼,就是損失值和準(zhǔn)確率值了。
這時(shí)候?qū)⒁韵麓a加入源代碼就可以了:
train_loss = [] train_acc = [] for epoch in range(resume_epoch, num_epochs): # 就是這一行 ### ... loss = criterion(outputs, labels.long()) # 損失樣例 train_loss.append(loss.item()) # 損失加入到列表中 ... epoch_acc = running_corrects.double() / trainval_sizes[phase] # 準(zhǔn)確率樣例 train_acc.append(epoch_acc.item()) # 準(zhǔn)確率加入到列表中 ... with open("./train_loss.txt", 'w') as train_los: train_los.write(str(train_loss)) with open("./train_acc.txt", 'w') as train_ac: train_ac.write(str(train_acc))
這樣就算完成了損失值和準(zhǔn)確率值的數(shù)據(jù)存儲(chǔ)了!
二、繪制 loss 曲線
主要需要 numpy 庫(kù)和 matplotlib 庫(kù),如果不會(huì)安裝可以自行百度,很簡(jiǎn)單。
首先,將 .txt 文件中的存儲(chǔ)的數(shù)據(jù)讀取進(jìn)來(lái),以下是讀取函數(shù):
import numpy as np # 讀取存儲(chǔ)為txt文件的數(shù)據(jù) def data_read(dir_path): with open(dir_path, "r") as f: raw_data = f.read() data = raw_data[1:-1].split(", ") # [-1:1]是為了去除文件中的前后中括號(hào)"[]" return np.asfarray(data, float)
然后,就是繪制 loss 曲線部分:
if __name__ == "__main__": train_loss_path = r"E:\relate_code\Gaitpart-master\train_loss.txt" # 存儲(chǔ)文件路徑 y_train_loss = data_read(train_loss_path) # loss值,即y軸 x_train_loss = range(len(y_train_loss)) # loss的數(shù)量,即x軸 plt.figure() # 去除頂部和右邊框框 ax = plt.axes() ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) plt.xlabel('iters') # x軸標(biāo)簽 plt.ylabel('loss') # y軸標(biāo)簽 # 以x_train_loss為橫坐標(biāo),y_train_loss為縱坐標(biāo),曲線寬度為1,實(shí)線,增加標(biāo)簽,訓(xùn)練損失, # 默認(rèn)顏色,如果想更改顏色,可以增加參數(shù)color='red',這是紅色。 plt.plot(x_train_loss, y_train_loss, linewidth=1, linestyle="solid", label="train loss") plt.legend() plt.title('Loss curve') plt.show()
這樣就算把損失圖像畫出來(lái)了!如下:
三、繪制準(zhǔn)確率曲線
有了上面的基礎(chǔ),這就簡(jiǎn)單很多了。
只是有一點(diǎn)要記住,上面的x軸是迭代次數(shù),這里的是訓(xùn)練輪次 epoch。
if __name__ == "__main__": train_acc_path = r"E:\relate_code\Gaitpart-master\train_acc.txt" # 存儲(chǔ)文件路徑 y_train_acc = data_read(train_acc_path) # 訓(xùn)練準(zhǔn)確率值,即y軸 x_train_acc = range(len(y_train_acc)) # 訓(xùn)練階段準(zhǔn)確率的數(shù)量,即x軸 plt.figure() # 去除頂部和右邊框框 ax = plt.axes() ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) plt.xlabel('epochs') # x軸標(biāo)簽 plt.ylabel('accuracy') # y軸標(biāo)簽 # 以x_train_acc為橫坐標(biāo),y_train_acc為縱坐標(biāo),曲線寬度為1,實(shí)線,增加標(biāo)簽,訓(xùn)練損失, # 增加參數(shù)color='red',這是紅色。 plt.plot(x_train_acc, y_train_acc, color='red',linewidth=1, linestyle="solid", label="train acc") plt.legend() plt.title('Accuracy curve') plt.show()
這樣就把準(zhǔn)確率變化曲線畫出來(lái)了!如下:
以下是完整代碼,以繪制準(zhǔn)確率曲線為例,并且將x軸換成了iters,和損失曲線保持一致,供參考:
import numpy as np import matplotlib.pyplot as plt # 讀取存儲(chǔ)為txt文件的數(shù)據(jù) def data_read(dir_path): with open(dir_path, "r") as f: raw_data = f.read() data = raw_data[1:-1].split(", ") return np.asfarray(data, float) # 不同長(zhǎng)度數(shù)據(jù),統(tǒng)一為一個(gè)標(biāo)準(zhǔn),倍乘x軸 def multiple_equal(x, y): x_len = len(x) y_len = len(y) times = x_len/y_len y_times = [i * times for i in y] return y_times if __name__ == "__main__": train_loss_path = r"E:\relate_code\Gaitpart-master\file_txt\train_loss.txt" train_acc_path = r"E:\relate_code\Gaitpart-master\train_acc.txt" y_train_loss = data_read(train_loss_path) y_train_acc = data_read(train_acc_path) x_train_loss = range(len(y_train_loss)) x_train_acc = multiple_equal(x_train_loss, range(len(y_train_acc))) plt.figure() # 去除頂部和右邊框框 ax = plt.axes() ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) plt.xlabel('iters') plt.ylabel('accuracy') # plt.plot(x_train_loss, y_train_loss, linewidth=1, linestyle="solid", label="train loss") plt.plot(x_train_acc, y_train_acc, color='red', linestyle="solid", label="train accuracy") plt.legend() plt.title('Accuracy curve') plt.show()
總結(jié)
到此這篇關(guān)于Python繪制loss曲線和準(zhǔn)確率曲線的文章就介紹到這了,更多相關(guān)Python繪制loss曲線 準(zhǔn)確率曲線內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python從Excel讀取數(shù)據(jù)并使用Matplotlib繪制成二維圖像
本課程實(shí)現(xiàn)使用 Python 從 Excel 讀取數(shù)據(jù),并使用 Matplotlib 繪制成二維圖像。這一過(guò)程中,將通過(guò)一系列操作來(lái)美化圖像,最終得到一個(gè)可以出版級(jí)別的圖像。本課程對(duì)于需要書寫實(shí)驗(yàn)報(bào)告,學(xué)位論文,發(fā)表文章,做報(bào)告的學(xué)員具有較大價(jià)值2023-02-02pytorch交叉熵?fù)p失函數(shù)的weight參數(shù)的使用
這篇文章主要介紹了pytorch交叉熵?fù)p失函數(shù)的weight參數(shù)的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05python 基于pygame實(shí)現(xiàn)俄羅斯方塊
這篇文章主要介紹了python 基于pygame實(shí)現(xiàn)俄羅斯方塊的方法,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-03-03詳解Python 使用 selenium 進(jìn)行自動(dòng)化測(cè)試或者協(xié)助日常工作
這篇文章主要介紹了Python 使用 selenium 進(jìn)行自動(dòng)化測(cè)試 或者協(xié)助日常工作,我們可以使用 selenium 來(lái)幫助我們進(jìn)行自動(dòng)化的 Web 測(cè)試,也可以通過(guò) selenium 操作瀏覽器做一些重復(fù)的,簡(jiǎn)單的事情,來(lái)減輕我們的工作2021-09-09tensorflow1.0學(xué)習(xí)之模型的保存與恢復(fù)(Saver)
這篇文章主要介紹了tensorflow1.0學(xué)習(xí)之模型的保存與恢復(fù)(Saver) ,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04分析用Python腳本關(guān)閉文件操作的機(jī)制
這篇文章主要介紹了分析用Python腳本關(guān)閉文件操作的機(jī)制,作者分Python2.x版本和3.x版本兩種情況進(jìn)行了闡述,需要的朋友可以參考下2015-06-06