Pytorch学习笔记(二):Tensorboard的使用

1. Tensorboard的使用

  • add.scalar用法:添加标量数据到summary当中
    • 需要添加图表的标题(tag), 数值y(scalar_value), 训练步数x(global_step) 
# pip install tensorboard # 安装tensorboard
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter("logs")
# y = x
for i in range(100):
    writer.add_scalar("y = x", i , i)
  • 如何打开文件:在终端输入以下代码

tensorboard --logdir logs --port 6007

  • add.image用法
    • img_tensor 需要我们的图片数据类型为tensor或者numpy,我们可以利用opencv读取数据
    • from PIL import Image 读取的数据类型是PIL.JpegImage类型,可以利用Numpy进行数据转换

# add_image
import numpy as np
from PIL import Image
writer = SummaryWriter("logs")
image_path = "train/bees_image/198508668_97d818b6c4.jpg"
img_PIL = Image.open(image_path)
img_array = np.array(img_PIL)
# 我们需要对numpy型的高度 宽度 通道顺序进行调整,dataformats
writer.add_image("test",img_array,2, dataformats = 'HWC')

2. Transforms的用法

  • 类似于一个工具箱
    • Compose:进行中心裁剪
    • ToTensor:将PIL、numpy类型的图片转化成tensor文件......
    • 从工具箱中选择工具创建具体的工具,再使用这个工具
from torchvision import transforms
tensor_trans = transforms.ToTensor() #从transform中选择一个class进行创建
tensor_img = tensor_trans(img) 
print(tensor_img)
  • Tensor数据类型
    • Tensor数据包装了神经网络理论基础的参数
  • 常见的Transforms:关注输入、输出、作用
    • __call__的作用:内置函数,直接加入参数调用函数
    • Normalize:归一化tensor数据类型
    • Resize:等比裁剪
    • Compose : 参数需要一个列表,在compose中,数据需要是transform类型。
    • RandomCrop : 随机裁剪
trans_norm = transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
img_norm = trans_norm(img_tensor)
# Resize
print(img.size)
trans_resize = transforms.Resize((512,512))
# img_PIL -> resize -> img_resize PIL
img_resize = trans_resize(img)
# img_resize PIL -> totensor -> img_resize tensor
img_resize = trans_totensor(img_resize)
print(img_resize)
# Compose - resize - 2
trans_resize_2 = transforms.Resize(512)
trans_compose = transforms.Compose([trans_resize_2,trans_totensor])
img_resize_2 = trans_compose(img)

# RandomCrop
trans_random = transforms.RandomCrop(256)
trans_compose_2 = transforms.Compose([trans_random,trans_totensor])
for i in range (10):
    img_crop = trans_compose_2(img)
    write.add_image("Randomcrop", img_crop ,i)
writer.close()

3.Torchvision中的数据集使用:导入数据

#dataset transform
import torchvision
from torchvision import transforms
dataset_transform = transforms.Compose([transforms.ToTensor()])
train_set = torchvision.datasets.CIFAR10("./dataset",train = True, transform = dataset_transform,download = True)
test_set = torchvision.datasets.CIFAR10("./dataset",train = False, transform = dataset_transform,download = True)
print(test_set[0])
print(test_set.classes)
img,target = test_set[0]
writer = SummaryWriter("p10")
for i in range(10):
    img,target = test_set[i]
    writer.add_image("test_set",img,i)
writer.close()

你可能感兴趣的:(pytorch,深度学习,神经网络)