1. 程式人生 > >python繪製lost(損失)曲線 加 方差範圍

python繪製lost(損失)曲線 加 方差範圍

1. 匯入必要的包

我使用了seaborn,通過sns.set_style可以讓繪製出來的圖更漂亮,而且可以切換不同的型別

import re
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import shutil
import os
sns.set_style('whitegrid')

2. 資料的獲取(可跳過此步)

       我用的資料是通過深度強化得到的回報曲線。資料結構如下所示,我所需要的是從train開始的部分,分別對應總的回報,平均回報和回報的方差。我採用了re.findall的正則表示式去提取我所需要的資料,具體的操作方式可以檢視原始碼。

10-15 22:23:15 DATA/traffic DEBUG     train 0 totalreward : -99477.0 ReturnAvg : -102.55360824742269 ReturnStd : 34.34301970480272
10-15 22:23:29 DATA/traffic DEBUG     train 1 totalreward : -83131.0 ReturnAvg : -85.70206185567011 ReturnStd : 53.442993000985545

file_path = 'log.txt'
content = []
with open(file_path, 'r') as f:
    for line in f.readlines():
        line = line.strip('\n')
        content.append(line)
iter = []
totalreward = []
returnavg = []
returnstd = []
for line in content:
    str1 = re.findall('train.+', line)
    v = [float(x) for x in re.findall('-?\d+.?\d+|\d+', str1[0])]
    iter.append(v[0])
    totalreward.append(v[1])
    returnavg.append(v[2])
    returnstd.append(v[3])

3. 回報繪製

      直接將影象儲存到Plot的資料夾,這裡儲存不了jpg格式,一直儲存,最後將其儲存為png格式成功。設定解析度為1000,其實差不多,只是線更清楚了。

color = cm.viridis(0.5)
f, ax = plt.subplots(1,1)
ax.plot(iter, totalreward, color=color)
ax.legend()
ax.set_xlabel('Iteration')
ax.set_ylabel('Return')
exp_dir = 'Plot/'
if not os.path.exists(exp_dir):
    os.makedirs(exp_dir, exist_ok=True)
else:
    os.makedirs(exp_dir, exist_ok=True)
f.savefig(os.path.join('Plot', 'reward' + '.png'), dpi=1000)

       曲線如下圖,可通過plt.show()顯示出來,或者直接在console輸入f並回車

4.含有方差的平均回報繪製

    在強化學習的論文中,我們經常看到一條收斂線,周圍還有淺淺的範圍線,那些範圍線就是方差。繪製程式碼如下,主要包含了fill_between.

color = cm.viridis(0.7)
f, ax = plt.subplots(1,1)
ax.plot(iter, returnavg, color=color)
r1 = list(map(lambda x: x[0]-x[1], zip(returnavg, returnstd)))
r2 = list(map(lambda x: x[0]+x[1], zip(returnavg, returnstd)))
ax.fill_between(iter, r1, r2, color=color, alpha=0.2)
ax.legend()
ax.set_xlabel('Iteration')
ax.set_ylabel('Return')
exp_dir = 'Plot/'
if not os.path.exists(exp_dir):
    os.makedirs(exp_dir, exist_ok=True)
f.savefig(os.path.join('Plot', 'avgreward' + '.png'), dpi=50)

結果如下

可以看到深綠色上下包裹著淺綠色的線,這就是fill_between的作用,其中可以調節alpha來改變顏色深度。