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 112 113 114 115
| from torch.utils.data import Dataset, DataLoader import torchvision.transforms as transforms from torchvision import datasets import torch.nn as nn import torch.nn.functional as F import torch import torch.optim as optim
transform = transforms.Compose([transforms.ToTensor()]) trainset = datasets.FashionMNIST(root='/content', train=True, download=True, transform = transform) testset = datasets.FashionMNIST(root='/content', train=False, download=True, transform = transform)
train_loader = DataLoader(trainset, batch_size=64, shuffle=True, num_workers=2) test_loader = DataLoader(testset, batch_size=64, shuffle=False, num_workers=2)
images, labels = next(iter(train_loader)) images.shape, labels.shape
class FashionCNN(nn.Module): def __init__(self): super(FashionCNN, self).__init__()
self.layer1 = nn.Sequential( nn.Conv2d(1,32,3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2,2) )
self.layer2 = nn.Sequential( nn.Conv2d(32,64,3), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2) ) self.fc1 = nn.Linear(64*6*6, 600) self.drop = nn.Dropout2d(0.25) self.fc2 = nn.Linear(600, 120) self.fc3 = nn.Linear(120, 10) def forward(self, x): out = self.layer1(x) out = self.layer2(out) out = out.view(out.size(0), -1) out = self.fc1(out) out = self.drop(out) out = self.fc2(out) out = self.fc3(out) return out model = FashionCNN()
criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.001,momentum=0.9)
for epoch in range(20): running_loss = 0.0
for i, data in enumerate(train_loader, 0): inputs , labels = data
optimizer.zero_grad()
outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step()
running_loss += loss.item()
if i % 100 == 99: print('Epoch : {}, Iter : {}, Loss : {}'.format(epoch+1,i+1, running_loss/2000)) runngin_loss = 0.0
correct = 0 total = 0 with torch.no_grad(): for data in test_loader: images, labels = data outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()
print(100 * correct / total)
PATH = './fashion_mnist.pth' torch.save(model.state_dict(), PATH)
model = FashionCNN() model.load_state_dict(torch.load(PATH))
|