-
Notifications
You must be signed in to change notification settings - Fork 15
/
example6_squeezenet.py
119 lines (96 loc) · 3.67 KB
/
example6_squeezenet.py
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
116
117
118
119
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data
import torchvision.models as models
from torchvision import datasets, transforms
BATCH_SIZE = 32
NUM_WORKERS = 1
LR = 1e-3
data_folder = "cats_and_dogs"
traindir = os.path.join(data_folder, 'train')
testdir = os.path.join(data_folder, 'test')
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
torch.manual_seed(31415926)
if 'cuda' in str(device):
torch.cuda.manual_seed(31415926)
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train_loader = data.DataLoader(
datasets.ImageFolder(traindir,
transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=BATCH_SIZE,
shuffle=True,
num_workers=NUM_WORKERS)
test_loader = data.DataLoader(
datasets.ImageFolder(testdir,
transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=50,
shuffle=True,
num_workers=NUM_WORKERS)
# Definition here: https://github.com/pytorch/vision/blob/master/torchvision/models/squeezenet.py
model = models.squeezenet1_1(pretrained=True)
# Don't train the normal layers
for param in model.parameters():
param.requires_grad = False
# Create a new output layer
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv = nn.Conv2d(512, 2, kernel_size=1)
self.avgpool = nn.AvgPool2d(13)
def forward(self, x):
x = F.dropout(x, training=self.training)
x = self.conv(x)
x = self.avgpool(x)
x = F.log_softmax(x)
x = x.squeeze(dim=3).squeeze(dim=2)
return x
model.classifier = Net()
model.num_classes = 2
model = model.to(device)
optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=LR)
def train(epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = F.cross_entropy(output, target)
loss.backward()
optimizer.step()
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
def test():
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += F.cross_entropy(output, target, reduction='sum').item() # sum up batch loss
pred = output.data.max(1)[1] # get the index of the max log-probability
correct += pred.eq(target.data.view_as(pred)).cpu().sum()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
if __name__ == '__main__':
for epoch in range(1, 2):
train(epoch)
print("Running test...")
test()
# 1 epoch gives 93% in 13 minutes