import torchvision from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader #1.torchvision中数据集的使用......................................................... dataset_transform = torchvision.transforms.Compose([ torchvision.transforms.ToTensor() ]) #下载数据集CIFAR10 通过datasets train_set = torchvision.datasets.CIFAR10(root="./dataset", train=True, transform=dataset_transform, download=True) test_set = torchvision.datasets.CIFAR10(root="./dataset", train=False, transform=dataset_transform, download=True) ''' ''' 数据集的基本观察 print(test_set[0]) print(test_set.classes) img, target = test_set[0] print(img) print(target) print(test_set.classes[target]) img.show() #打印出猫的图片 ''' #print(train_set[0]) '''用SummaryWriter读取数据集中的图片 writer = SummaryWriter("p10") #在终端用tensorboard --logdir='p10'打开 for i in range(10): img, target = test_set[i] writer.add_image("test_set", img, i) writer.close() ''' #2.DataLoader中数据集的使用............................................................. test_data = torchvision.datasets.CIFAR10("./dataset", train=False, transform=torchvision.transforms.ToTensor()) test_loader = DataLoader(dataset=test_data, batch_size=64, shuffle=True, num_workers=0, drop_last=True) # 测试数据集中第一张图片及target img, target = test_data[0] print(img.shape) print(target) writer = SummaryWriter("dataloader") #tensorboard --logdir='dataloader' --port=6008 名称要一致否则无图片 for epoch in range(2): step = 0 for data in test_loader: imgs, targets = data # print(imgs.shape) # print(targets) writer.add_images("Epoch: {}".format(epoch), imgs, step) #将epoch填入{}中 step = step + 1 writer.close()
import torch from torch import nn import torch.nn.functional as F ''' #3.nn.Module的基本使用.................................................................. class Tudui(nn.Module): 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) ''' #4.卷积的基本操作....................................................................... input = torch.tensor([[1, 2, 0, 3, 1], #输入图像 [0, 1, 2, 3, 1], [1, 2, 1, 0, 0], [5, 2, 3, 1, 1], [2, 1, 0, 1, 1]]) kernel = torch.tensor([[1, 2, 1], #卷积核 [0, 1, 0], [2, 1, 0]]) input = torch.reshape(input, (1, 1, 5, 5)) kernel = torch.reshape(kernel, (1, 1, 3, 3)) print(input.shape) print(kernel.shape) output = F.conv2d(input, kernel, stride=1) print(output) output2 = F.conv2d(input, kernel, stride=2) print(output2) output3 = F.conv2d(input, kernel, stride=1, padding=1) #stride->步长为1,padding->进行0填充 print(output3)