如何使用python的plot繪制loss、acc曲線并存儲成圖片
前言
使用 python的plot 繪制網(wǎng)絡訓練過程中的的 loss 曲線以及準確率變化曲線,這里的主要思想就時先把想要的損失值以及準確率值保存下來,保存到 .txt 文件中,待網(wǎng)絡訓練結(jié)束,我們再拿這存儲的數(shù)據(jù)繪制各種曲線。
其大致步驟為:數(shù)據(jù)讀取與存儲 - > loss曲線繪制 - > 準確率曲線繪制
一、數(shù)據(jù)讀取與存儲部分
我們首先要得到訓練時的數(shù)據(jù),以損失值為例,網(wǎng)絡每迭代一次都會產(chǎn)生相應的 loss,那么我們就把每一次的損失值都存儲下來,存儲到列表,保存到 .txt 文件中。
1.3817585706710815, 1.8422836065292358, 1.1619832515716553, 0.5217241644859314, 0.5221078991889954, 1.3544578552246094, 1.3334463834762573, 1.3866571187973022, 0.7603049278259277
上圖為部分損失值,根據(jù)迭代次數(shù)而異,要是迭代了1萬次,這里就會有1萬個損失值。
而準確率值是每一個 epoch 產(chǎn)生一個值,要是訓練100個epoch,就有100個準確率值。
這里的損失值是怎么保存到文件中的呢?首先,找到網(wǎng)絡訓練代碼,就是項目中的 main.py,或者 train.py ,在文件里先找到訓練部分,里面經(jīng)常會有這樣一行代碼:
for epoch in range(resume_epoch, num_epochs): # 就是這一行
####
...
loss = criterion(outputs, labels.long()) # 損失樣例
...
epoch_acc = running_corrects.double() / trainval_sizes[phase] # 準確率樣例
...
###
從這一行開始就是訓練部分了,往下會找到類似的這兩句代碼,就是損失值和準確率值了。
這時候?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] # 準確率樣例
train_acc.append(epoch_acc.item()) # 準確率加入到列表中
...
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))
這樣就算完成了損失值和準確率值的數(shù)據(jù)存儲了!
二、繪制 loss 曲線
主要需要 numpy 庫和 matplotlib 庫。
pip install numpy malplotlib
首先,將 .txt 文件中的存儲的數(shù)據(jù)讀取進來,以下是讀取函數(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軸標簽
plt.ylabel('loss') # y軸標簽
# 以x_train_loss為橫坐標,y_train_loss為縱坐標,曲線寬度為1,實線,增加標簽,訓練損失,
# 默認顏色,如果想更改顏色,可以增加參數(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")
這樣就算把損失圖像畫出來了!如下:

三、繪制準確率曲線
有了上面的基礎,這就簡單很多了。
只是有一點要記住,上面的x軸是迭代次數(shù),這里的是訓練輪次 epoch。
if __name__ == "__main__":
train_acc_path = r"/train_acc.txt" # 存儲文件路徑
y_train_acc = data_read(train_acc_path) # 訓練準確率值,即y軸
x_train_acc = range(len(y_train_acc)) # 訓練階段準確率的數(shù)量,即x軸
plt.figure()
# 去除頂部和右邊框框
ax = plt.axes()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.xlabel('epochs') # x軸標簽
plt.ylabel('accuracy') # y軸標簽
# 以x_train_acc為橫坐標,y_train_acc為縱坐標,曲線寬度為1,實線,增加標簽,訓練損失,
# 增加參數(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")
這樣就把準確率變化曲線畫出來了!如下:

以下是完整代碼,以繪制準確率曲線為例,并且將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)一為一個標準,倍乘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é)
到此這篇關于如何使用python的plot繪制loss、acc曲線并存儲成圖片的文章就介紹到這了,更多相關python plot繪制loss、acc曲線存儲成圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
人工智能最火編程語言 Python大戰(zhàn)Java!
開發(fā)者到底應該學習哪種編程語言才能獲得機器學習或數(shù)據(jù)科學這類工作呢?這是一個非常重要的問題。本文為大家提供作者的答案并解釋原因2017-11-11
自定義Django_rest_framework_jwt登陸錯誤返回的解決
這篇文章主要介紹了自定義Django_rest_framework_jwt登陸錯誤返回的解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10
Python實現(xiàn)將MySQL數(shù)據(jù)庫表中的數(shù)據(jù)導出生成csv格式文件的方法
這篇文章主要介紹了Python實現(xiàn)將MySQL數(shù)據(jù)庫表中的數(shù)據(jù)導出生成csv格式文件的方法,涉及Python針對mysql數(shù)據(jù)庫的連接、查詢、csv格式數(shù)據(jù)文件的生成等相關操作技巧,需要的朋友可以參考下2018-01-01
pytorch MSELoss計算平均的實現(xiàn)方法
這篇文章主要介紹了pytorch MSELoss計算平均的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05

