案例带你学Pytorch(4)——TensorboardX详解(2)

    xiaoxiao2021-04-15  273

    对tensorboardX_demo的试运行及注解

    demo参见:https://github.com/lanpa/tensorboardX

    这个demo把tensorboard中各个可以利用的模块(标量、图像、文字、图、音频、精度曲线)都使用了,可以作为一个不错的示范案例。

    import torch import torchvision.utils as vutils import numpy as np import torchvision.models as models from torchvision import datasets from tensorboardX import SummaryWriter resnet18 = models.resnet18(False) writer = SummaryWriter() sample_rate = 44100 freqs = [262, 294, 330, 349, 392, 440, 440, 440, 440, 440, 440] *for* n_iter in range(100): ​ dummy_s1 = torch.rand(1) *#dummy虚拟的, torch.rand()随机数按正态分布进行 ​ dummy_s2 = torch.rand(1) ​ *# data grouping by `slash` #slash斜线* ​ *#添加标量,最终曲线为显示100个随机数* ​ writer.add_scalar('data/scalar1', dummy_s1[0], n_iter) ​ writer.add_scalar('data/scalar2', dummy_s2[0], n_iter) *#添加标量组,最终曲线包括了3个函数,xsinx,xcosx,arctanx,* writer.add_scalars('data/scalar_group', {'xsinx': n_iter * np.sin(n_iter), 'xcosx': n_iter * np.cos(n_iter), 'arctanx': np.arctan(n_iter)}, n_iter)

    dummy_img = torch.rand(32, 3, 64, 64) *# output from network 假图像* *#每十次循环进行一次* if n_iter % 10 == 0: x = vutils.make_grid(dummy_img, *normalize*=True, *scale_each*=True) writer.add_image('Image', x, n_iter) *#添加图像* dummy_audio = torch.zeros(sample_rate * 2)

    从step 0到step 90,共添加了10组图像,每一组(batch包含32个图像,图像尺寸为3×64×64,随机生成):

    for i in range(x.size(0)): # amplitude of sound should in [-1, 1] dummy_audio[i] = np.cos(freqs[n_iter // 10] * np.pi * float(i) / float(sample_rate)) writer.add_audio('myAudio', dummy_audio, n_iter, *sample_rate*=sample_rate)

    writer.add_text('Text', 'text logged at step:' + str(n_iter), n_iter)

    for name, param in resnet18.named_parameters(): writer.add_histogram(name, param.clone().cpu().data.numpy(), n_iter)

    writer.add_pr_curve('xoxo', np.random.randint(2, *size*=100), np.random.rand(100), n_iter) dataset = datasets.MNIST('mnist', *train*=False, *download*=False) images = dataset.test_data[:100].float() label = dataset.test_labels[:100] features = images.view(100, 784) writer.add_embedding(features, *metadata*=label, *label_img*=images.unsqueeze(1)) writer.close()

    运行命令:

    tensorboard --logdir=runs --host localhost

    open TensorBoard 1.13.1 at http://localhost:6006

    仍会持续完善更新,敬请关注!

    建议阅读:https://tensorboard-pytorch.readthedocs.io/en/latest/tutorial.html


    最新回复(0)