Python使用matplotlib.pyplot畫熱圖和損失圖的代碼詳解
更新時(shí)間:2023年09月19日 10:53:23 作者:童話ing
眾所周知,在完成論文相關(guān)工作時(shí)畫圖必不可少,如損失函數(shù)圖、熱力圖等是非常常見的圖,在本文中,總結(jié)了這兩個(gè)圖的畫法,下面給出了完整的代碼,開箱即用,感興趣的同學(xué)可以自己動(dòng)手嘗試一下
一、損失函數(shù)圖
import matplotlib.pyplot as plt
file = open('E:\\5120154230PythonCode\\PBAN-PyTorch-master\\state_dict\\loss\\PBAN_New_restaurant15_0.001_80_0.2_16.csv') # 打開文檔
data = file.readlines() # 讀取文檔數(shù)據(jù)
para_1 = [] # 新建列表,用于保存第一列數(shù)據(jù)
para_2 = [] # 新建列表,用于保存第二列數(shù)據(jù)
cnt = 0
for num in data:
try:
temp = num.split(",")
cnt += 1
if cnt==700:
break
except:
continue
para_1.append(float(num.split(',')[0]))
para_2.append(float(num.split(',')[1]))
plt.figure()
# plt.title('loss')
plt.xlabel("iterations")
plt.ylabel("loss")
#color in cnblogs.com/qccc/p/12795541.html
#orange、teal、red、chocolate
plt.plot(para_1, para_2)
plt.show()CSV數(shù)據(jù)格式:第一列為Epoch或者迭代次數(shù)等,第二列為損失值。

效果圖:

二、熱圖
import matplotlib.pyplot as plt import pandas as pd import matplotlib.ticker as ticker d = [ [0.43757705, 0.30564879, 0.08757705, 0.013755781, 0.13755781, 0.04080211, 0.03615228], [0.31525328, 0.42328909, 0.04004493, 0.01735733, 0.01755249, 0.02630009, 0.09020273], [0.01546572, 0.09022246, 0.4166335, 0.09773314, 0.10259592, 0.0447391, 0.03261019], [0.01536734, 0.010553601, 0.045800883, 0.39755909, 0.1465714, 0.0408309, 0.03612638], [0.11513351, 0.01193435, 0.051866556, 0.046714543, 0.42510962, 0.03154159, 0.4848393], [0.11544053, 0.0941444, 0.050161916, 0.09768857, 0.11385846, 0.43073818, 0.13351071], [0.01529034, 0.07752335, 0.04121181, 0.01742287, 0.35099512, 0.03777161, 0.38087882] ] variables = ['Great', 'food', 'but', 'the', 'service', 'was', 'dreadful'] labels = ['Great', 'food', 'but', 'the', 'service', 'was', 'dreadful'] df = pd.DataFrame(d, columns=variables, index=labels) fig = plt.figure(figsize=(7, 6)) #寬、高 ax = fig.add_subplot(1, 1, 1) #畫布設(shè)置為1行1列顯示在第一塊中 # cmap參考:https://matplotlib.org/2.0.2/users/colormaps.html # hot_r、afmhot_r、plasma_r、ocean_r # interpolation:nearest,None、none cax = ax.matshow(df, interpolation='nearest', cmap='hot_r') fig.colorbar(cax) tick_spacing = 1 ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing)) ax.yaxis.set_major_locator(ticker.MultipleLocator(tick_spacing)) ax.set_xticklabels([''] + list(df.columns)) ax.set_yticklabels([''] + list(df.index)) plt.show()
效果:

另一份代碼:
import matplotlib.pylab as plt
import numpy as np
def samplemat(dims):
aa = np.zeros(dims)
for i in range(dims[1]):
aa[0,i] = i
return aa
dimlist = [(1, 12)]
for d in dimlist:
arr = samplemat(d)
plt.matshow(arr)
plt.show()
以上就是Python使用matplotlib.pyplot畫熱圖和損失圖的代碼詳解的詳細(xì)內(nèi)容,更多關(guān)于Python matplotlib.pyplot畫圖的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python使用qrcode二維碼庫(kù)生成二維碼方法詳解
這篇文章主要介紹了Python使用qrcode二維碼庫(kù)生成二維碼方法詳解,需要的朋友可以參考下2020-02-02
Python腳本實(shí)現(xiàn)自動(dòng)替換文件指定內(nèi)容
這篇文章主要為大家詳細(xì)介紹了如何編寫一個(gè)py腳本,可以實(shí)現(xiàn)自定義替換py文件里面指定內(nèi)容,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-03-03

