| import torch
|
| import torch.optim as optim
|
| import torch.nn as nn
|
| from torchvision import datasets, transforms
|
| from torch.utils.data import DataLoader
|
|
|
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
| transform = transforms.ToTensor()
|
|
|
| train_set = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
|
| test_set = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
|
|
|
| train_loader = DataLoader(train_set , batch_size=64 , shuffle=True)
|
| test_loader = DataLoader(test_set , batch_size=64 , shuffle=False)
|
|
|
| class CIFARNet(nn.Module):
|
| def __init__(self):
|
| super(CIFARNet, self).__init__()
|
| self.conv1 = nn.Conv2d(3, 16, 3)
|
| self.relu1 = nn.ReLU()
|
| self.pool = nn.MaxPool2d(2, 2)
|
|
|
| self.conv2 = nn.Conv2d(16, 32, 3)
|
|
|
| self.flatten = nn.Flatten()
|
| self.fc1 = nn.Linear(32 * 6 * 6, 128)
|
| self.relu2 = nn.ReLU()
|
| self.fc2 = nn.Linear(128, 10)
|
|
|
| def forward(self, x):
|
| x = self.conv1(x)
|
| x = self.relu1(x)
|
| x = self.pool(x)
|
| x = self.conv2(x)
|
| x = self.pool(x)
|
| x = self.flatten(x)
|
| x = self.fc1(x)
|
| x = self.relu2(x)
|
| x = self.fc2(x)
|
| return x
|
|
|
| model = CIFARNet().to(device)
|
| criterion = nn.CrossEntropyLoss()
|
| optimizer = optim.Adam(model.parameters(), lr=0.001)
|
|
|
| def train():
|
| model.train()
|
| for images , labels in train_loader:
|
| images = images.to(device)
|
| labels = labels.to(device)
|
|
|
| outputs = model(images)
|
| loss = criterion(outputs, labels)
|
|
|
| optimizer.zero_grad()
|
| loss.backward()
|
| optimizer.step()
|
|
|
| def test():
|
| model.eval()
|
| total = 0
|
| correct = 0
|
| with torch.no_grad():
|
| for images, labels in test_loader:
|
| images = images.to(device)
|
| labels = labels.to(device)
|
|
|
| outputs = model(images)
|
| pred = outputs.argmax(1)
|
|
|
| correct += (pred == labels).sum().item()
|
| total += labels.size(0)
|
|
|
| acc = correct / total
|
| print(f"test acc: {acc:.4f}")
|
|
|
| for epoch in range(5):
|
| train()
|
| print(f"epoch: {epoch+1} finished")
|
| test() |