學(xué)習(xí)數(shù)據(jù)分析與科學(xué)計(jì)算的小伙伴們對(duì)數(shù)據(jù)可視化的需求是比較重視的。所以python的第三方庫(kù)種有很多python可視化工具,今天小編要介紹的python可視化工具是visdom,在小編往期的文章中已經(jīng)有簡(jiǎn)單的visdom的使用介紹了,今天小編就系統(tǒng)化地整理一下常用的一些visdom的使用方法吧。
概述
Visdom:一個(gè)靈活的可視化工具,可用來(lái)對(duì)于 實(shí)時(shí),富數(shù)據(jù)的 創(chuàng)建,組織和共享。支持Torch和Numpy還有pytorch。
visdom
可以實(shí)現(xiàn)遠(yuǎn)程數(shù)據(jù)的可視化,對(duì)科學(xué)實(shí)驗(yàn)有很大幫助。我們可以遠(yuǎn)程的發(fā)送圖片和數(shù)據(jù),并進(jìn)行在ui界面顯示出來(lái),檢查實(shí)驗(yàn)結(jié)果,或者debug.
要用這個(gè)先要安裝,對(duì)于python模塊而言,安裝都是蠻簡(jiǎn)單的:
pip install visdom
安裝完每次要用直接輸入代碼打開(kāi):
python -m visdom.server
然后根據(jù)提示在瀏覽器中輸入相應(yīng)地址即可,默認(rèn)地址為:http://localhost:8097/
使用示例
1. vis.text(), vis.image()
import visdom # 添加visdom庫(kù)
import numpy as np # 添加numpy庫(kù)
vis = visdom.Visdom(env='test') # 設(shè)置環(huán)境窗口的名稱(chēng),如果不設(shè)置名稱(chēng)就默認(rèn)為main
vis.text('test', win='main') # 使用文本輸出
vis.image(np.ones((3, 100, 100))) # 繪制一幅尺寸為3 * 100 * 100的圖片,圖片的像素值全部為1
其中:
visdom.Visdom(env=‘命名新環(huán)境')
vis.text(‘文本', win=‘環(huán)境名')
vis.image(‘圖片',win=‘環(huán)境名')
2. 畫(huà)直線(xiàn) .line() 一條
import visdom
import numpy as np
vis = visdom.Visdom(env='my_windows') # 設(shè)置環(huán)境窗口的名稱(chēng),如果不設(shè)置名稱(chēng)就默認(rèn)為main
x = list(range(10))
y = list(range(10))
# 使用line函數(shù)繪制直線(xiàn) 并選擇顯示坐標(biāo)軸
vis.line(X=np.array(x), Y=np.array(y), opts=dict(showlegend=True))
vis.line([x], [y], opts=dict(showlegend=True)[展示說(shuō)明])
兩條
import visdom
import numpy as np
vis = visdom.Visdom(env='my_windows')
x = list(range(10))
y = list(range(10))
z = list(range(1,11))
vis.line(X=np.array(x), Y=np.column_stack((np.array(y), np.array(z))), opts=dict(showlegend=True))
vis.line([x], [y=np.column_stack((np.array(y),np.array(z),np.array(還可以增加)))])
np.column_stack(a,b), 表示兩個(gè)矩陣按列合并
sin(x)曲線(xiàn)
import visdom
import torch
vis = visdom.Visdom(env='sin')
x = torch.arange(0, 100, 0.1)
y = torch.sin(x)
vis.line(X=x,Y=y,win='sin(x)',opts=dict(showlegend=True))
持續(xù)更新圖表
import visdom
import numpy as np
vis = visdom.Visdom(env='my_windows')
# 利用update更新圖像
x = 0
y = 0
my_win = vis.line(X=np.array([x]), Y=np.array([y]), opts=dict(title='Update'))
for i in range(10):
x += 1
y += i
vis.line(X=np.array([x]), Y=np.array([y]), win=my_win, update='append')
使用“append”追加數(shù)據(jù),“replace”使用新數(shù)據(jù),“remove”用于刪除“name”中指定的跟蹤。
vis.images()
import visdom
import torch
# 新建一個(gè)連接客戶(hù)端
# 指定env = 'test1',默認(rèn)是'main',注意在瀏覽器界面做環(huán)境的切換
vis = visdom.Visdom(env='test1')
# 繪制正弦函數(shù)
x = torch.arange(1, 100, 0.01)
y = torch.sin(x)
vis.line(X=x,Y=y, win='sinx',opts={'title':'y=sin(x)'})
# 繪制36張圖片隨機(jī)的彩色圖片
vis.images(torch.randn(36,3,64,64).numpy(),nrow=6, win='imgs',opts={'title':'imgs'})
繪制loss函數(shù)的變化趨勢(shì)
#繪制loss變化趨勢(shì),參數(shù)一為Y軸的值,參數(shù)二為X軸的值,參數(shù)三為窗體名稱(chēng),參數(shù)四為表格名稱(chēng),參數(shù)五為更新選項(xiàng),從第二個(gè)點(diǎn)開(kāi)始可以更新
vis.line(Y=np.array([totalloss.item()]), X=np.array([traintime]),
win=('train_loss'),
opts=dict(title='train_loss'),
update=None if traintime == 0 else 'append'
)
實(shí)際代碼
此代碼出自CycleGAN的 utils.py 里一個(gè)實(shí)現(xiàn)
# 記錄訓(xùn)練日志,顯示生成圖,畫(huà)loss曲線(xiàn) 的類(lèi)
class Logger():
def __init__(self, n_epochs, batches_epoch):
'''
:param n_epochs: 跑多少個(gè)epochs
:param batches_epoch: 一個(gè)epoch有幾個(gè)batches
'''
self.viz = Visdom() # 默認(rèn)env是main函數(shù)
self.n_epochs = n_epochs
self.batches_epoch = batches_epoch
self.epoch = 1 # 當(dāng)前epoch數(shù)
self.batch = 1 # 當(dāng)前batch數(shù)
self.prev_time = time.time()
self.mean_period = 0
self.losses = {}
self.loss_windows = {} # 保存loss圖的字典集合
self.image_windows = {} # 保存生成圖的字典集合
def log(self, losses=None, images=None):
self.mean_period += (time.time() - self.prev_time)
self.prev_time = time.time()
sys.stdout.write('
Epoch %03d/%03d [%04d/%04d] -- ' % (self.epoch, self.n_epochs, self.batch, self.batches_epoch))
for i, loss_name in enumerate(losses.keys()):
if loss_name not in self.losses:
self.losses[loss_name] = losses[loss_name].data.item() #這里losses[loss_name].data是個(gè)tensor(包在值外面的數(shù)據(jù)結(jié)構(gòu)),要用item方法取值
else:
self.losses[loss_name] = losses[loss_name].data.item()
if (i + 1) == len(losses.keys()):
sys.stdout.write('%s: %.4f -- ' % (loss_name, self.losses[loss_name]/self.batch))
else:
sys.stdout.write('%s: %.4f | ' % (loss_name, self.losses[loss_name]/self.batch))
batches_done = self.batches_epoch * (self.epoch - 1) + self.batch
batches_left = self.batches_epoch * (self.n_epochs - self.epoch) + self.batches_epoch - self.batch
sys.stdout.write('ETA: %s' % (datetime.timedelta(seconds=batches_left*self.mean_period/batches_done)))
# 顯示生成圖
for image_name, tensor in images.items(): # 字典.items()是以list形式返回鍵值對(duì)
if image_name not in self.image_windows:
self.image_windows[image_name] = self.viz.image(tensor2image(tensor.data), opts={'title':image_name})
else:
self.viz.image(tensor2image(tensor.data), win=self.image_windows[image_name], opts={'title':image_name})
# End of each epoch
if (self.batch % self.batches_epoch) == 0: # 一個(gè)epoch結(jié)束時(shí)
# 繪制loss曲線(xiàn)圖
for loss_name, loss in self.losses.items():
if loss_name not in self.loss_windows:
self.loss_windows[loss_name] = self.viz.line(X=np.array([self.epoch]), Y=np.array([loss/self.batch]),
opts={'xlabel':'epochs', 'ylabel':loss_name, 'title':loss_name})
else:
self.viz.line(X=np.array([self.epoch]), Y=np.array([loss/self.batch]), win=self.loss_windows[loss_name], update='append') #update='append'可以使loss圖不斷更新
# 每個(gè)epoch重置一次loss
self.losses[loss_name] = 0.0
# 跑完一個(gè)epoch,更新一下下面參數(shù)
self.epoch += 1
self.batch = 1
sys.stdout.write('
')
else:
self.batch += 1
train.py中調(diào)用代碼是
# 繪畫(huà)Loss圖
logger = Logger(opt.n_epochs, len(dataloader))
for epoch in range(opt.epoch, opt.n_epochs):
for i, batch in enumerate(dataloader):
......
# 記錄訓(xùn)練日志
# Progress report (http://localhost:8097) 顯示visdom畫(huà)圖的網(wǎng)址
logger.log({'loss_G': loss_G, 'loss_G_identity': (loss_identity_A + loss_identity_B),
'loss_G_GAN': (loss_GAN_A2B + loss_GAN_B2A),
'loss_G_cycle': (loss_cycle_ABA + loss_cycle_BAB), 'loss_D': (loss_D_A + loss_D_B)},
images={'real_A': real_A, 'real_B': real_B, 'fake_A': fake_A, 'fake_B': fake_B})
到此這篇常見(jiàn)的visdom使用方法的介紹就介紹到這了,更多python 可視化工具的了解和數(shù)據(jù)分析學(xué)習(xí)內(nèi)容可以搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章。