如何使用python的plot繪制loss、acc曲線并存儲成圖片
前言
使用 python的plot 繪制網(wǎng)絡(luò)訓(xùn)練過程中的的 loss 曲線以及準(zhǔn)確率變化曲線,這里的主要思想就時先把想要的損失值以及準(zhǔn)確率值保存下來,保存到 .txt 文件中,待網(wǎng)絡(luò)訓(xùn)練結(jié)束,我們再拿這存儲的數(shù)據(jù)繪制各種曲線。
其大致步驟為:數(shù)據(jù)讀取與存儲 - > loss曲線繪制 - > 準(zhǔn)確率曲線繪制
一、數(shù)據(jù)讀取與存儲部分
我們首先要得到訓(xùn)練時的數(shù)據(jù),以損失值為例,網(wǎng)絡(luò)每迭代一次都會產(chǎn)生相應(yīng)的 loss,那么我們就把每一次的損失值都存儲下來,存儲到列表,保存到 .txt 文件中。
1.3817585706710815, 1.8422836065292358, 1.1619832515716553, 0.5217241644859314, 0.5221078991889954, 1.3544578552246094, 1.3334463834762573, 1.3866571187973022, 0.7603049278259277
上圖為部分損失值,根據(jù)迭代次數(shù)而異,要是迭代了1萬次,這里就會有1萬個損失值。
而準(zhǔn)確率值是每一個 epoch 產(chǎn)生一個值,要是訓(xùn)練100個epoch,就有100個準(zhǔn)確率值。
這里的損失值是怎么保存到文件中的呢?首先,找到網(wǎng)絡(luò)訓(xùn)練代碼,就是項目中的 main.py,或者 train.py ,在文件里先找到訓(xùn)練部分,里面經(jīng)常會有這樣一行代碼:
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)練部分了,往下會找到類似的這兩句代碼,就是損失值和準(zhǔn)確率值了。
這時候?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ù)存儲了!
二、繪制 loss 曲線
主要需要 numpy 庫和 matplotlib 庫。
pip install numpy malplotlib
首先,將 .txt 文件中的存儲的數(shù)據(jù)讀取進(jìn)來,以下是讀取函數(shù):
import numpy as np # 讀取存儲為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]是為了去除文件中的前后中括號"[]" return np.asfarray(data, float)
然后,就是繪制 loss 曲線部分:
if __name__ == "__main__": train_loss_path = r"/train_loss.txt" # 存儲文件路徑 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,實線,增加標(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() pit.savefig("loss.png")
這樣就算把損失圖像畫出來了!如下:
三、繪制準(zhǔn)確率曲線
有了上面的基礎(chǔ),這就簡單很多了。
只是有一點要記住,上面的x軸是迭代次數(shù),這里的是訓(xùn)練輪次 epoch。
if __name__ == "__main__": train_acc_path = r"/train_acc.txt" # 存儲文件路徑 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,實線,增加標(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() pit.savefig("acc.png")
這樣就把準(zhǔn)確率變化曲線畫出來了!如下:
以下是完整代碼,以繪制準(zhǔn)確率曲線為例,并且將x軸換成了iters,和損失曲線保持一致,供參考:
import numpy as np import matplotlib.pyplot as plt # 讀取存儲為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) # 不同長度數(shù)據(jù),統(tǒng)一為一個標(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"/train_loss.txt" train_acc_path = r"/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() pit.savefig("acc.png")
總結(jié)
到此這篇關(guān)于如何使用python的plot繪制loss、acc曲線并存儲成圖片的文章就介紹到這了,更多相關(guān)python plot繪制loss、acc曲線存儲成圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 非極大值抑制(NMS)的四種實現(xiàn)詳解
本文主要介紹了非極大值抑制(Non-Maximum Suppression,NMS)的四種實現(xiàn)方式,不同方法對NMS速度的影響各不相同,感興趣的小伙伴可以了解一下2021-11-11appium+python自動化配置(adk、jdk、node.js)
這篇文章主要介紹了appium+python自動化配置(adk、jdk、node.js),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11Python實現(xiàn)批量提取Word文檔表格數(shù)據(jù)
在大數(shù)據(jù)處理與信息抽取領(lǐng)域中,Word文檔是各類機構(gòu)和個人普遍采用的一種信息存儲格式,本文將介紹如何使用Python實現(xiàn)對Word文檔中表格的提取,感興趣的可以了解下2024-03-03Python利用psutil庫進(jìn)行監(jiān)控進(jìn)程和資源
psutil是Python系統(tǒng)和進(jìn)程工具庫,它提供了一種跨平臺的方式來獲取系統(tǒng)信息、管理系統(tǒng)進(jìn)程、監(jiān)控系統(tǒng)性能、操作系統(tǒng)資源等,下面就跟隨小編一起來學(xué)習(xí)psutil庫的具體應(yīng)用吧2024-01-01Python中input和raw_input的一點區(qū)別
這篇文章主要介紹了Python中input和raw_input的一點區(qū)別,它們都是用來讀取控制臺輸入的函數(shù),需要的朋友可以參考下2014-10-10