一、工具介绍
visdom是Facebook专门为PyTorch开发的一款可视化工具,可以直接对Tensor进行操作,胜任大部分的数据可视化任务。我们先来看两个动图小案例感受一下。
Sumhub小芝士
- 一种灵活的工具,用于创建、组织和共享实时丰富数据的可视化。支持 Torch 和 Numpy
二、工具使用
2.1 开启visdom服务
首先通过以下命令安装visdom
服务。
pip install visdom
安装完成后,就让我们打开它的服务看一下吧
python3 -m visdom.server
Sumhub小芝士
- 第一次启动的时候会下载一些js文件,请别惊慌
2.2 创建visdom环境
vis = visdom.Visdom(env='model_1')
运行上述代码就可以创建一个Visdom
环境,在浏览器中输入http://localhost:8097
就可以在Environment
中看到我们的环境。
2.3 可视化应用
文字输出
vis.text('Hello World', win='text1')
如果我们需要在该窗口的文本后进行追加,那么同样适用上面的代码,改变一下参数即可。
vis.text('Hi', win='text1', append=True)
二维图像
通常在模型训练时,我们会记录输出的loss数值,用来观察训练情况,那么此时用visdom来进行实时观测且可视化就非常方便了,visdom可以直接对Tensor进行操作。
for i in range(10):
vis.line(X=torch.FloatTensor([i]), Y=torch.FloatTensor([i**2]), win='loss', update='append' if i> 0 else None)
远程监督训练
很多时候,我们都会将程序丢到服务器上进行训练,那么每次要进行观察的时候往往不方便,此时便可以使用visdom
模块通过浏览器访问远程服务器的8097端口来远程观察模型的训练情况。
vis.matplotlib
用Visdom
模块显示matplotlib
图像。
viz = Visdom()
assert viz.check_connection()
try:
import matplotlib.pyplot as plt
plt.plot([1, 23, 2, 4])
plt.ylabel('some numbers')
viz.matplot(plt)
except BaseException as err:
print('Skipped matplotlib example')
print('Error message: ', err)
vis.video
通过Visdom
模块显示视频。
try:
# video demo: download video from http://media.w3.org/2010/05/sintel/trailer.ogv
video_url = 'http://media.w3.org/2010/05/sintel/trailer.ogv'
# linux
if _platform == "linux" or _platform == "linux2":
videofile = '/home/%s/trailer.ogv' % getpass.getuser()
# MAC OS X
elif _platform == "darwin":
videofile = '/Users/%s/trailer.ogv' % getpass.getuser()
# download video
urllib.request.urlretrieve(video_url, videofile)
if os.path.isfile(videofile):
viz.video(videofile=videofile)
except ImportError:
print('Skipped video example')
vis.image(图片单张/多张)
# single
viz.image(
np.random.rand(3, 512, 256),
opts=dict(title='Random!', caption='How random.'),
)
# multi
viz.images(
np.random.randn(20, 3, 64, 64),
opts=dict(title='Random images', caption='How random.')
)
vis.scatter(散点图2D/3D)
# draw random scatter
import time
Y = np.random.rand(100)
old_scatter = viz.scatter(
X=np.random.rand(100, 2),
Y=(Y[Y > 0] + 1.5).astype(int),
opts=dict(
legend=['Didnt', 'Update'],
xtickmin=-50,
xtickmax=50,
xtickstep=0.5,
ytickmin=-50,
ytickmax=50,
ytickstep=0.5,
markersymbol='cross-thin-open',
),
)
time.sleep(5)
# update window, including market、coordinate、style and so on
viz.update_window_opts(
win=old_scatter,
opts=dict(
legend=['Apples', 'Pears'],
xtickmin=0,
xtickmax=1,
xtickstep=0.5,
ytickmin=0,
ytickmax=1,
ytickstep=0.5,
markersymbol='cross-thin-open',
),
)
# add actter by update='new'
import time
win = viz.scatter(
X=np.random.rand(255, 2),
opts=dict(
markersize=10,
markercolor=np.random.randint(0, 255, (255, 3,)),
),
)
# if windows exists
assert viz.win_exists(win), 'Created window marked as not existing'
time.sleep(2)
# add new describaption to scatter
viz.scatter(
X=np.random.rand(255),
Y=np.random.rand(255),
win=win,
name='new_trace',
update='new'
)
# 2D散点图,分配不同颜色
viz.scatter(
X=np.random.rand(255, 2),
# random set 1 or 2
Y=(np.random.rand(255) + 1.5).astype(int),
opts=dict(
markersize=10,
# 分配两种颜色
markercolor=np.random.randint(0, 255, (2, 3,)),
),
)
# 3D
viz.scatter(
X=np.random.rand(100, 3),
Y=(Y + 1.5).astype(int),
opts=dict(
legend=['Men', 'Women'],
markersize=5,
)
)
vis.line(曲线图)
viz.line(Y=np.random.rand(10), opts=dict(showlegend=True))
Y = np.linspace(-5, 5, 100)
viz.line(
Y=np.column_stack((Y * Y, np.sqrt(Y + 5))),
X=np.column_stack((Y, Y)),
opts=dict(markers=False),
)
vis.bar(柱方图)
viz.bar(X=np.random.rand(20))
viz.bar(
X=np.abs(np.random.rand(5, 3)),
opts=dict(
stacked=True,
legend=['Facebook', 'Google', 'Twitter'],
rownames=['2012', '2013', '2014', '2015', '2016']
)
)
viz.bar(
X=np.random.rand(20, 3),
opts=dict(
stacked=False,
legend=['The Netherlands', 'France', 'United States']
)
)
vis.heat/contour/surface(热成图、地理图、表面图)
viz.heatmap(
X=np.outer(np.arange(1, 6), np.arange(1, 11)),
opts=dict(
columnnames=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
rownames=['y1', 'y2', 'y3', 'y4', 'y5'],
colormap='Electric',
)
)
# contour
x = np.tile(np.arange(1, 101), (100, 1))
y = x.transpose()
X = np.exp((((x - 50) ** 2) + ((y - 50) ** 2)) / -(20.0 ** 2))
viz.contour(X=X, opts=dict(colormap='Viridis'))
# surface
viz.surf(X=X, opts=dict(colormap='Hot'))
vis.boxplot/stem/quiver(箱型图、茎干图、箭状图)
# boxplot
X = np.random.rand(100, 2)
X[:, 1] += 2
viz.boxplot(
X=X,
opts=dict(legend=['Men', 'Women'])
)
# stemplot
Y = np.linspace(0, 2 * math.pi, 70)
X = np.column_stack((np.sin(Y), np.cos(Y)))
viz.stem(
X=X,
Y=Y,
opts=dict(legend=['Sine', 'Cosine'])
)
# quiver plot
X = np.arange(0, 2.1, .2)
Y = np.arange(0, 2.1, .2)
X = np.broadcast_to(np.expand_dims(X, axis=1), (len(X), len(X)))
Y = np.broadcast_to(np.expand_dims(Y, axis=0), (len(Y), len(Y)))
U = np.multiply(np.cos(X), Y)
V = np.multiply(np.sin(X), Y)
viz.quiver(
X=U,
Y=V,
opts=dict(normalize=0.9),
)
vis.text/pie/mesh(文字、饼图、网格图)
# text window with Callbacks
txt = 'This is a write demo notepad. Type below. Delete clears text:<br>'
callback_text_window = viz.text(txt)
# pie chart
X = np.asarray([19, 26, 55])
viz.pie(
X=X,
opts=dict(legend=['Residential', 'Non-Residential', 'Utility'])
)
# mesh plot
x = [0, 0, 1, 1, 0, 0, 1, 1]
y = [0, 1, 1, 0, 0, 1, 1, 0]
z = [0, 0, 0, 0, 1, 1, 1, 1]
X = np.c_[x, y, z]
i = [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2]
j = [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3]
k = [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6]
Y = np.c_[i, j, k]
viz.mesh(X=X, Y=Y, opts=dict(opacity=0.5))