如何使用python的plot繪制loss、acc曲線(xiàn)并存儲(chǔ)成圖片
前言
使用 python的plot 繪制網(wǎng)絡(luò)訓(xùn)練過(guò)程中的的 loss 曲線(xiàn)以及準(zhǔn)確率變化曲線(xiàn),這里的主要思想就時(shí)先把想要的損失值以及準(zhǔn)確率值保存下來(lái),保存到 .txt 文件中,待網(wǎng)絡(luò)訓(xùn)練結(jié)束,我們?cè)倌眠@存儲(chǔ)的數(shù)據(jù)繪制各種曲線(xiàn)。
其大致步驟為:數(shù)據(jù)讀取與存儲(chǔ) - > loss曲線(xiàn)繪制 - > 準(zhǔn)確率曲線(xià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)確率值。
這里的損失值是怎么保存到文件中的呢?首先,找到網(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)確率樣例
...
###
從這一行開(kāi)始就是訓(xùn)練部分了,往下會(huì)找到類(lèi)似的這兩句代碼,就是損失值和準(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 曲線(xiàn)
主要需要 numpy 庫(kù)和 matplotlib 庫(kù)。
pip install numpy malplotlib
首先,將 .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 曲線(xiàn)部分:
if __name__ == "__main__":
train_loss_path = r"/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),曲線(xiàn)寬度為1,實(shí)線(xiàn),增加標(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")
這樣就算把損失圖像畫(huà)出來(lái)了!如下:

三、繪制準(zhǔn)確率曲線(xiàn)
有了上面的基礎(chǔ),這就簡(jiǎn)單很多了。
只是有一點(diǎn)要記住,上面的x軸是迭代次數(shù),這里的是訓(xùn)練輪次 epoch。
if __name__ == "__main__":
train_acc_path = r"/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),曲線(xiàn)寬度為1,實(shí)線(xiàn),增加標(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)確率變化曲線(xiàn)畫(huà)出來(lái)了!如下:

以下是完整代碼,以繪制準(zhǔn)確率曲線(xiàn)為例,并且將x軸換成了iters,和損失曲線(xiàn)保持一致,供參考:
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"/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曲線(xiàn)并存儲(chǔ)成圖片的文章就介紹到這了,更多相關(guān)python plot繪制loss、acc曲線(xiàn)存儲(chǔ)成圖片內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
人工智能最火編程語(yǔ)言 Python大戰(zhàn)Java!
開(kāi)發(fā)者到底應(yīng)該學(xué)習(xí)哪種編程語(yǔ)言才能獲得機(jī)器學(xué)習(xí)或數(shù)據(jù)科學(xué)這類(lèi)工作呢?這是一個(gè)非常重要的問(wèn)題。本文為大家提供作者的答案并解釋原因2017-11-11
自定義Django_rest_framework_jwt登陸錯(cuò)誤返回的解決
這篇文章主要介紹了自定義Django_rest_framework_jwt登陸錯(cuò)誤返回的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
Python實(shí)現(xiàn)將MySQL數(shù)據(jù)庫(kù)表中的數(shù)據(jù)導(dǎo)出生成csv格式文件的方法
這篇文章主要介紹了Python實(shí)現(xiàn)將MySQL數(shù)據(jù)庫(kù)表中的數(shù)據(jù)導(dǎo)出生成csv格式文件的方法,涉及Python針對(duì)mysql數(shù)據(jù)庫(kù)的連接、查詢(xún)、csv格式數(shù)據(jù)文件的生成等相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
pandas改變df列的順序的方法實(shí)現(xiàn)
本文主要介紹了pandas改變df列的順序的方法實(shí)現(xiàn),主要使用 Pandas 中的 reindex() 方法,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-03-03
pytorch MSELoss計(jì)算平均的實(shí)現(xiàn)方法
這篇文章主要介紹了pytorch MSELoss計(jì)算平均的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-05-05
python的ArgumentParser使用及說(shuō)明
這篇文章主要介紹了python的ArgumentParser使用及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08

