1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| import torchvision.datasets from torch import nn from torch.nn import Sequential,Conv2d,MaxPool2d,Flatten,Linear from torch.utils.data import DataLoader import torch
dataset=torchvision.datasets.CIFAR10("./dataset2",train=False,transform=torchvision.transforms.ToTensor(), download=True)
dataloader=DataLoader(dataset,batch_size=1)
class NetWork(nn.Module): def __init__(self): super(NetWork, self).__init__() self.conv1=Conv2d(3,32,5,padding=2) self.maxpool1=MaxPool2d(2) self.conv2=Conv2d(32,32,5,padding=2) self.maxpool2=MaxPool2d(2) self.conv3=Conv2d(32,64,5,padding=2) self.maxpool3=MaxPool2d(2) self.flatten=Flatten() self.linear1=Linear(1024,64) self.linear2=Linear(64,10)
self.model1=Sequential( Conv2d(3,32,5,padding=2), MaxPool2d(2), Conv2d(32,32,5,padding=2), MaxPool2d(2), Conv2d(32, 64, 5, padding=2), MaxPool2d(2), Flatten(), Linear(1024, 64), Linear(64, 10) )
def forward(self,x): x=self.model1(x) return x
loss=nn.CrossEntropyLoss() network=NetWork() optim=torch.optim.SGD(network.parameters(),lr=0.01) for epoch in range(20): running_loss=0.0 for data in dataloader: imgs, targets=data outputs=network(imgs) result_loss=loss(outputs, targets) optim.zero_grad() result_loss.backward() optim.step() running_loss=running_loss+result_loss print(running_loss)
|