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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms
if torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu")
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv = nn.Sequential( nn.Conv2d(1, 96, 11, 4), nn.ReLU(), nn.MaxPool2d(3, 2), nn.Conv2d(96, 256, 5, 1, 2), nn.ReLU(), nn.MaxPool2d(3, 2), nn.Conv2d(256, 384, 3, 1, 1), nn.ReLU(), nn.Conv2d(384, 384, 3, 1, 1), nn.ReLU(), nn.Conv2d(384, 256, 3, 1, 1), nn.ReLU(), nn.MaxPool2d(3, 2) ) self.fc = nn.Sequential( nn.Flatten(), nn.Linear(256*6*6, 4096), nn.Dropout(0.5), nn.Linear(4096, 4096), nn.Dropout(0.5), nn.Linear(4096, 10), )
def forward(self, img): feature = self.conv(img) output = self.fc(feature) return output
training_data = datasets.FashionMNIST( root="data", train=True, download=True, transform=transforms.ToTensor(), )
test_data = datasets.FashionMNIST( root="data", train=False, download=True, transform=transforms.ToTensor(), )
batch_size = 64
train_dataloader = torch.utils.data.DataLoader(training_data, batch_size=batch_size) test_dataloader = torch.utils.data.DataLoader(test_data, batch_size=batch_size)
net = Net().to(device)
criterion = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
for epoch in range(20): index=0 for inputs, labels in train_dataloader: inputs, labels = inputs.to(device), labels.to(device) optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() index+=1 print(f'Epoch [{epoch}], Setp [{index}/{len(train_dataloader)}],Loss: {loss.item():.4f}')
net.eval() correct = 0 total = 0 with torch.no_grad(): for inputs, labels in test_dataloader: inputs, labels = inputs.to(device), labels.to(device) outputs = net(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy: %d %%' % (100 * correct / total))
|