【Seaborn繪圖】深度強(qiáng)化學(xué)習(xí)實(shí)驗(yàn)中的paper繪圖方法
點(diǎn)擊上方“程序員大白”,選擇“星標(biāo)”公眾號(hào)
重磅干貨,第一時(shí)間送達(dá)
強(qiáng)化學(xué)習(xí)實(shí)驗(yàn)中的繪圖技巧-使用seaborn繪制paper中的圖片,使用seaborn繪制折線圖時(shí)參數(shù)數(shù)據(jù)可以傳遞ndarray或者pandas,不同的源數(shù)據(jù)對(duì)應(yīng)的其他參數(shù)也略有不同.
def getdata():basecond = [[18, 20, 19, 18, 13, 4, 1],[],[]]cond1 = [[18, 19, 18, 19, 20, 15, 14],[],[],[]]cond2 = [[20, 20, 20, 20, 19, 17, 4],[],[]]cond3 = [[20, 20, 20, 20, 19, 17, 12],[],[],[]]return basecond, cond1, cond2, cond3
數(shù)據(jù)維度都為(3,7)或(4, 7)?
第一個(gè)維度表示每個(gè)時(shí)間點(diǎn)采樣不同數(shù)目的數(shù)據(jù)(可認(rèn)為是每個(gè)x對(duì)應(yīng)多個(gè)不同y值) 第二個(gè)維度表示不同的時(shí)間點(diǎn)(可認(rèn)為是x軸對(duì)應(yīng)的x值)
data = getdata()fig = plt.figure()xdata = np.array([0, 1, 2, 3, 4, 5, 6])/5linestyle = ['-', '--', ':', '-.']color = ['r', 'g', 'b', 'k']label = ['algo1', 'algo2', 'algo3', 'algo4']for i in range(4):sns.tsplot(time=xdata, data=data[i], color=color[i], linestyle=linestyle[i], condition=label[i])
sns.tsplot 用來畫時(shí)間序列圖
time參數(shù)表示對(duì)應(yīng)的時(shí)間軸(ndarray),即x軸,data即要求繪制的數(shù)據(jù),上述例子為(3, 7)或(4, 7),color為每條線的顏色,linestyle為每條線的樣式,condition為每條線的標(biāo)記.
plt.ylabel("Success Rate", fontsize=25)plt.xlabel("Iteration Number", fontsize=25)plt.title("Awesome Robot Performance", fontsize=30)plt.show()

1.2 繪圖建議
你的程序代碼需要使用一個(gè)額外的文件記錄結(jié)果,例如csv或pkl文件,而不是直接產(chǎn)生最終的繪圖結(jié)果.這種方式下,你能運(yùn)行程序代碼一次,然后以不同的方式去繪制結(jié)果,記錄超出您認(rèn)為嚴(yán)格必要的內(nèi)容可能是一個(gè)好主意,因?yàn)槟肋h(yuǎn)不知道哪些信息對(duì)于了解發(fā)生的事情最有用.注意文件的大小,但通常最好記錄以下內(nèi)容:每次迭代的平均reward或loss,一些采樣的軌跡,有用的輔助指標(biāo)(如貝爾曼誤差和梯度)
你需要有一個(gè)單獨(dú)的腳本去加載一個(gè)或多個(gè)記錄文件來繪制圖像,如果你使用不同的超參數(shù)或隨機(jī)種子運(yùn)行算法多次,一起加載所有的數(shù)據(jù)(也許來自不同的文件)并畫在一起是個(gè)好主意,使用自動(dòng)生成的圖例和顏色模式使分辨不同的方法變得容易.
深度強(qiáng)化學(xué)習(xí)方法,往往在不同的運(yùn)行中有巨大的變化,因此使用不同的隨機(jī)種子運(yùn)行多次是一個(gè)好主意,在繪制多次運(yùn)行的結(jié)果時(shí),在一張圖上繪制不同運(yùn)行次的結(jié)果,通過使用不同粗細(xì)和顏色的線來分辨.在繪制不同的方法時(shí),你將發(fā)現(xiàn)將他們總結(jié)為均值和方差圖是容易的,然而分布并不總是遵循正態(tài)曲線,所以至少在初始時(shí)有明顯的感覺對(duì)比不同隨機(jī)種子的性能.
1.3 實(shí)驗(yàn)繪圖流程
下面以模仿學(xué)習(xí)的基礎(chǔ)實(shí)驗(yàn)為例
means = []stds = []#使用不同的隨機(jī)種子表示運(yùn)行多次實(shí)驗(yàn)for seed in range(SEED_NUM):tf.set_random_seed(seed*10)np.random.seed(seed*10)mean = []std = []#構(gòu)建神經(jīng)網(wǎng)絡(luò)模型model = tf.keras.Sequential()model.add(layers.Dense(64, activation="relu"))model.add(layers.Dense(64, activation="relu"))model.add(layers.Dense(act_dim, activation="tanh"))model.compile(optimizer=tf.train.AdamOptimizer(0.0001), loss="mse", metrics=['mae'])#迭代次數(shù)for iter in range(ITERATION):print("iter:", iter)#訓(xùn)練模型model.fit(train, label, batch_size=BATCH_SIZE, epochs=EPOCHS)#測(cè)試,通過與環(huán)境交互n次而成,即n趟軌跡roll_reward = []for roll in range(NUM_ROLLOUTS):s = env.reset()done = Falsereward = 0step = 0#以下循環(huán)表示一趟軌跡while not done:a = model.predict(s[np.newaxis, :])s, r, done, _ = env.step(a)reward += rstep += 1if step >= max_steps:break#記錄每一趟的總回報(bào)值roll_reward.append(reward)#n趟回報(bào)的平均值和方差作為這次迭代的結(jié)果記錄mean.append(np.mean(roll_reward))std.append(np.std(roll_reward))#記錄每一次實(shí)驗(yàn),矩陣的一行表示一次實(shí)驗(yàn)每次迭代結(jié)果means.append(mean)stds.append(std)
d = {"mean": means, "std": stds}
with open(os.path.join("test_data", "behavior_cloning_" + ENV_NAME+".pkl"), "wb") as f:
pickle.dump(d, f, pickle.HIGHEST_PROTOCOL)繪圖的程序代碼比較簡單
file = "behavior_cloning_" + ENV_NAME+".pkl"
with open(os.path.join("test_data", file), "rb") as f:
data = pickle.load(f)
x1 = data["mean"]
file = "dagger_" + ENV_NAME+".pkl"
with open(os.path.join("test_data", file), "rb") as f:
data = pickle.load(f)
x2 = data["mean"]
time = range(10)
sns.set(style="darkgrid", font_scale=1.5)
sns.tsplot(time=time, data=x1, color="r", condition="behavior_cloning")
sns.tsplot(time=time, data=x2, color="b", condition="dagger")
plt.ylabel("Reward")
plt.xlabel("Iteration Number")
plt.title("Imitation Learning")
plt.show()

有時(shí)我們需要對(duì)曲線進(jìn)行平滑
def smooth(data, sm=1):
if sm > 1:
smooth_data = []
for d in data:
y = np.ones(sm)*1.0/sm
d = np.convolve(y, d, "same")
smooth_data.append(d)
return smooth_datasm表示滑動(dòng)窗口大小,為2*k+1,
smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])

2.pandas
sns.tsplot可以使用pandas源數(shù)據(jù)作為數(shù)據(jù)輸入,當(dāng)使用pandas作為數(shù)據(jù)時(shí),time,value,condition,unit選項(xiàng)將為pandas數(shù)據(jù)的列名.
其中time選項(xiàng)給出使用該列Series作為x軸數(shù)據(jù),value選項(xiàng)表示使用該Series作為y軸數(shù)據(jù),用unit來分辨這些數(shù)據(jù)是哪一次采樣(每個(gè)x對(duì)應(yīng)多個(gè)y),用condition選項(xiàng)表示這些數(shù)據(jù)來自哪一條曲線.
在openai 的spinning up中,將每次迭代的數(shù)據(jù)保存到了txt文件中,類似如下:

可以使用pd.read_table讀取這個(gè)以"\t"分割的文件形成pandas
algo = ["ddpg_" + ENV, "td3_" + ENV, "ppo_" + ENV, "trpo_" + ENV, "vpg_" + ENV, "sac_" + ENV]
data = []
for i in range(len(algo)):
for seed in range(SEED_NUM):
file = os.path.join(os.path.join(algo[i], algo[i] + "_s" + str(seed*10)), "progress.txt")
pd_data = pd.read_table(file)
pd_data.insert(len(pd_data.columns), "Unit", seed)
pd_data.insert(len(pd_data.columns), "Condition", algo[i])
data.append(pd_data)
data = pd.concat(data, ignore_index=True)
sns.set(style="darkgrid", font_scale=1.5)
sns.tsplot(data=data, time="TotalEnvInteracts", value="AverageEpRet", condition="Condition", unit="Unit")
#數(shù)據(jù)大時(shí)使用科學(xué)計(jì)數(shù)法
xscale = np.max(data["TotalEnvInteracts"]) > 5e3
if xscale:
plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
plt.legend(loc='best').set_draggable(True)
plt.tight_layout(pad=0.5)
plt.show()程序參考了spinning up 的代碼邏輯github.com/openai/spinn
繪制效果如下:

完整代碼:https://github.com/feidieufo/homework/tree/master/hw1
推薦閱讀
關(guān)于程序員大白
程序員大白是一群哈工大,東北大學(xué),西湖大學(xué)和上海交通大學(xué)的碩士博士運(yùn)營維護(hù)的號(hào),大家樂于分享高質(zhì)量文章,喜歡總結(jié)知識(shí),歡迎關(guān)注[程序員大白],大家一起學(xué)習(xí)進(jìn)步!

