1. Tensorboard的使用
# 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
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的用法
from torchvision import transforms
tensor_trans = transforms.ToTensor() #从transform中选择一个class进行创建
tensor_img = tensor_trans(img)
print(tensor_img)
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()