深度学习(tensorboard使用)

在做深度学习的时候,尤其是在没有界面的服务器上训练时,可以利用tensorboard工具输出各种曲线或中间图像。

下面代码将曲线和图像输出到run目录下临时文件中。

from tensorboardX import SummaryWriter
from PIL import Image
import numpy as np
import torchvision
import torch
from torchvision import transforms,datasets

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

writer = SummaryWriter(log_dir='./runs/')

for i in range(100):
    writer.add_scalar("task1", 0, i)
    writer.add_scalar("task2", i, i)
    writer.add_scalar("task3", np.sin(i/50.0*np.pi), i)

img = Image.open("1.jpg")
img_np = np.array(img)
writer.add_image('img', img_np,0,dataformats='HWC')

img = Image.open("2.jpg")
img_tensor = torchvision.transforms.ToTensor()(img)
writer.add_image('img', img_tensor,1,dataformats='CHW')

for idx, data in enumerate(train_loader):
    grid = torchvision.utils.make_grid(data[0]) 
    writer.add_image('mnist', grid, idx) 

    if idx>10:
        break

writer.close()

最后执行:tensorboard --logdir=./runs --port=6123,在浏览器ip:6123就可以查看结果了。

posted @ 2024-11-02 15:30  Dsp Tian  阅读(6)  评论(0编辑  收藏  举报