千家信息网

PyTorch中TensorBoard如何使用

发表于:2025-01-31 作者:千家信息网编辑
千家信息网最后更新 2025年01月31日,PyTorch中TensorBoard如何使用,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。步骤设置TensorBoar
千家信息网最后更新 2025年01月31日PyTorch中TensorBoard如何使用

PyTorch中TensorBoard如何使用,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

步骤

  • 设置TensorBoard。

简单说是设置基本tensorboard运行需要的东西,我这代码中的imshow(img)和matplotlib_imshow(img, one_channel=False)都是显示图片的函数,可以统一替换,我自己测试就没改了!

# helper function to show an image# (used in the `plot_classes_preds` function below)def matplotlib_imshow(img, one_channel=False):    if one_channel:        img = img.mean(dim=0)    img = img / 2 + 0.5     # unnormalize    npimg = img.cpu().numpy()    if one_channel:        plt.imshow(npimg, cmap="Greys")    else:        plt.imshow(np.transpose(npimg, (1, 2, 0)))    # 设置tensorBoard# default `log_dir` is "runs" - we'll be more specific herewriter = SummaryWriter('runs/image_classify_tensorboard')# get some random training imagesdataiter = iter(trainloader)images, labels = dataiter.next()# create grid of imagesimg_grid = torchvision.utils.make_grid(images)# show images# matplotlib_imshow(img_grid, one_channel=True)imshow(img_grid)# write to tensorboardwriter.add_image('imag_classify', img_grid)# Tracking model training with TensorBoard# helper functionsdef images_to_probs(net, images):    '''    Generates predictions and corresponding probabilities from a trained    network and a list of images    '''    output = net(images)    # convert output probabilities to predicted class    _, preds_tensor = torch.max(output, 1)    # preds = np.squeeze(preds_tensor.numpy())    preds = np.squeeze(preds_tensor.cpu().numpy())    return preds, [F.softmax(el, dim=0)[i].item() for i, el in zip(preds, output)]def plot_classes_preds(net, images, labels):    '''    Generates matplotlib Figure using a trained network, along with images    and labels from a batch, that shows the network's top prediction along    with its probability, alongside the actual label, coloring this    information based on whether the prediction was correct or not.    Uses the "images_to_probs" function.    '''    preds, probs = images_to_probs(net, images)    # plot the images in the batch, along with predicted and true labels    fig = plt.figure(figsize=(12, 48))    for idx in np.arange(4):        ax = fig.add_subplot(1, 4, idx+1, xticks=[], yticks=[])        matplotlib_imshow(images[idx], one_channel=True)        ax.set_title("{0}, {1:.1f}%\n(label: {2})".format(            classes[preds[idx]],            probs[idx] * 100.0,            classes[labels[idx]]),                    color=("green" if preds[idx]==labels[idx].item() else "red"))    return fig
  • 写入TensorBoard。

这个在训练的每一阶段写入tensorboard

        if i % 2000 == 1999:    # print every 2000 mini-batches            print('[%d, %5d] loss: %.3f' %                  (epoch + 1, i + 1, running_loss / 2000))            # 把数据写入tensorflow            # ...log the running loss            writer.add_scalar('image training loss',                            running_loss / 2000,                            epoch * len(trainloader) + i)            # ...log a Matplotlib Figure showing the model's predictions on a            # random mini-batch            writer.add_figure('predictions vs. actuals',                            plot_classes_preds(net, inputs, labels),                            global_step=epoch * len(trainloader) + i)
  • 运行

tensorboard --logdir=runs

  • 打开http://localhost:6006/ 即可查看

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。

0