一、dataset和transform的联用
import torchvision
from torch.utils.tensorboard import SummaryWriter
# import ssl
# root - download为true时,下载的数据集所保存的位置
# transform - takes in an PIL image and returns a transformed version
# train (bool, optional) – If True, 创建训练集,否则为测试集
# download (bool, optional) – If true, 从网上下载数据集
# ssl._create_default_https_context = ssl._create_unverified_context
# 将每一个数据都转为tensor类型
dataset_transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor()
])
train_set = torchvision.datasets.CIFAR10(root="./dataset", transform=dataset_transform, train=True, download= True)
test_set = torchvision.datasets.CIFAR10(root="./dataset", transform=dataset_transform, train=False, download=True)
print(test_set[0])
# (<PIL.Image.Image image mode=RGB size=32x32 at 0x1C6A3520208>, 3) 3表示classes中的属性类别 ,就是label target
# print(test_set.classes)
#
# img, target = test_set[0]
# print(img)
# print(target)
# print(test_set.classes[target])
# img.show()
writer = SummaryWriter("p10")
for i in range(10):
img, target = test_set[i]
writer.add_image("test_set", img, i)
writer.close()
二、dataloader
作用:从dataset中取数据加载到神经网络中
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
# 准备测试数据集
test_set = torchvision.datasets.CIFAR10("./dataset", train=False, transform=torchvision.transforms.ToTensor())
# batch_size是每次训练取几张图片数据 shuffle是训练图片的顺序是否要调整 num_workers是设置多少个进程 drop_last为图片数除以batch_size剩余的指是否要舍去,true为舍去
test_loader = DataLoader(dataset=test_set, batch_size=64, shuffle=True, num_workers=0, drop_last=True)
# 测试数据集中第一张图片及target
img, target = test_set[0]
print(img.shape)
print(target)
writer = SummaryWriter("dataloader")
for epoch in range(2):
step = 0
for data in test_loader:
imgs, targets = data
# print(imgs)
# print(targets)
writer.add_images("Epoch:{}".format(epoch), imgs, step) #注意是images
step = step + 1
writer.close()
三、神经网络的基本骨架-nn.Module的使用
import torch
from torch import nn
# nn.module需要重写两个部分
class Tudui(nn.Module):
# 方法一:直接写
# def __init__(self):
# super(Tudui).__init__(())
# 方法二:Code -> Generate ->override methods
def __init__(self):
super().__init__()
def forward(self, input):
output = input + 1
return output
tudui = Tudui()
x = torch.tensor(1.0)
output = tudui(x)
print(output)