import torchvision
from torch import nn
from torch.utils.data import DataLoader
import torch
data_set = torchvision.datasets.CIFAR10(train=False,
root='./dataset/',
download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
]))
data_loader = DataLoader(dataset=data_set, batch_size=128)
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.sequential = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=32,
kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(in_channels=32, out_channels=32,
kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(in_channels=32, out_channels=64,
kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
nn.Flatten(),
nn.Linear(in_features=1024, out_features=64),
nn.Linear(in_features=64, out_features=10)
)
def forward(self, input):
output = self.sequential(input)
return output
model = Model()
loss = nn.CrossEntropyLoss()
optim = torch.optim.SGD(params=model.parameters(), lr=0.01)
for epoch in range(20):
epoch_loss = 0.0
for data in data_loader:
imgs, targets = data
output = model(imgs)
res_loss = loss(output, targets)
optim.zero_grad()
res_loss.backward()
optim.step()
epoch_loss += res_loss
print(epoch_loss)
|