-
Notifications
You must be signed in to change notification settings - Fork 16
/
HBP_fc_new.py
290 lines (260 loc) · 11.3 KB
/
HBP_fc_new.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Fine-tune the fc layer only for HBP(Hierarchical Bilinear Pooling for Fine-Grained Visual Recognition).
Usage:
CUDA_VISIBLE_DEVICES=0,1,2,3 python HBP_fc.py --base_lr 1.0 --batch_size 128 --epochs 240 --weight_decay 0.000005 | tee 'hbp_fc.log'
"""
import os
import torch
import torchvision
import cub200
import visdom
import argparse
vis = visdom.Visdom(env=u'HBP_fc',use_incoming_socket=False)
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)
class HBP(torch.nn.Module):
def __init__(self):
torch.nn.Module.__init__(self)
# Convolution and pooling layers of VGG-16.
self.features = torchvision.models.vgg16(pretrained=True).features
self.features_conv5_1 = torch.nn.Sequential(*list(self.features.children())
[:-5])
self.features_conv5_2 = torch.nn.Sequential(*list(self.features.children())
[-5:-3])
self.features_conv5_3 = torch.nn.Sequential(*list(self.features.children())
[-3:-1])
self.bilinear_proj_1 = torch.nn.Conv2d(512,8192,kernel_size=1,bias=True)
self.bilinear_proj_2 = torch.nn.Conv2d(512,8192,kernel_size=1,bias=True)
self.bilinear_proj_3 = torch.nn.Conv2d(512,8192,kernel_size=1,bias=True)
# Linear classifier.
self.fc = torch.nn.Linear(8192*3, 200)
# Freeze all previous layers.
for param in self.features_conv5_1.parameters():
param.requires_grad = False
for param in self.features_conv5_2.parameters():
param.requires_grad = False
for param in self.features_conv5_3.parameters():
param.requires_grad = False
# Initialize the fc layers.
torch.nn.init.xavier_normal_(self.fc.weight.data)
if self.fc.bias is not None:
torch.nn.init.constant_(self.fc.bias.data, val=0)
def hbp_1_2(self,conv1,conv2):
N = conv1.size()[0]
proj_1 = self.bilinear_proj_1(conv1)
proj_2 = self.bilinear_proj_2(conv2)
assert(proj_1.size() == (N,8192,28,28))
X = proj_1 * proj_2
assert(X.size() == (N,8192,28,28))
X = torch.sum(X.view(X.size()[0],X.size()[1],-1),dim = 2)
X = X.view(N, 8192)
X = torch.sign(X) * torch.sqrt(torch.abs(X) + 1e-5)
X = torch.nn.functional.normalize(X)
return X
def hbp_1_3(self,conv1,conv3):
N = conv1.size()[0]
proj_1 = self.bilinear_proj_1(conv1)
proj_3 = self.bilinear_proj_3(conv3)
assert(proj_1.size() == (N,8192,28,28))
X = proj_1 * proj_3
assert(X.size() == (N,8192,28,28))
X = torch.sum(X.view(X.size()[0],X.size()[1],-1),dim = 2)
X = X.view(N, 8192)
X = torch.sign(X) * torch.sqrt(torch.abs(X) + 1e-5)
X = torch.nn.functional.normalize(X)
return X
def hbp_2_3(self,conv2,conv3):
N = conv2.size()[0]
proj_2 = self.bilinear_proj_2(conv2)
proj_3 = self.bilinear_proj_3(conv3)
assert(proj_2.size() == (N,8192,28,28))
X = proj_2 * proj_3
assert(X.size() == (N,8192,28,28))
X = torch.sum(X.view(X.size()[0],X.size()[1],-1),dim = 2)
X = X.view(N, 8192)
X = torch.sign(X) * torch.sqrt(torch.abs(X) + 1e-5)
X = torch.nn.functional.normalize(X)
return X
def forward(self, X):
N = X.size()[0]
assert X.size() == (N, 3, 448, 448)
X_conv5_1 = self.features_conv5_1(X)
X_conv5_2 = self.features_conv5_2(X_conv5_1)
X_conv5_3 = self.features_conv5_3(X_conv5_2)
X_branch_1 = self.hbp_1_2(X_conv5_1,X_conv5_2)
X_branch_2 = self.hbp_1_3(X_conv5_1,X_conv5_3)
X_branch_3 = self.hbp_2_3(X_conv5_2,X_conv5_3)
X_branch = torch.cat([X_branch_1,X_branch_2,X_branch_3],dim = 1)
assert X_branch.size() == (N,8192*3)
X = self.fc(X_branch)
assert X.size() == (N, 200)
return X
class HBPManager(object):
def __init__(self, options, path):
self._options = options
self._path = path
# Network.
self._net = torch.nn.DataParallel(HBP()).cuda()
print(self._net)
# Criterion.
self._criterion = torch.nn.CrossEntropyLoss().cuda()
# Solver.
param_to_optim = []
for param in self._net.parameters():
if param.requires_grad == False:
continue
param_to_optim.append(param)
self._solver = torch.optim.SGD(
param_to_optim, lr=self._options['base_lr'],
momentum=0.9, weight_decay=self._options['weight_decay'])
self._scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self._solver)
# milestones = [40,60,80,100]
# self._scheduler = torch.optim.lr_scheduler.MultiStepLR(self._solver,milestones = milestones,gamma=0.25)
train_transforms = torchvision.transforms.Compose([
torchvision.transforms.Resize(size=448), # Let smaller edge match
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.RandomCrop(size=448),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))
])
test_transforms = torchvision.transforms.Compose([
torchvision.transforms.Resize(size=448),
torchvision.transforms.CenterCrop(size=448),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))
])
train_data = cub200.CUB200(
root=self._path['cub200'], train=True, download=True,
transform=train_transforms)
test_data = cub200.CUB200(
root=self._path['cub200'], train=False, download=True,
transform=test_transforms)
self._train_loader = torch.utils.data.DataLoader(
train_data, batch_size=self._options['batch_size'],
shuffle=True, num_workers=4, pin_memory=True)
self._test_loader = torch.utils.data.DataLoader(
test_data, batch_size=16,
shuffle=False, num_workers=4, pin_memory=True)
def train(self):
print('Training.')
best_acc = 0.0
best_epoch = None
print('Epoch\tTrain loss\tTrain acc\tTest acc')
ii = 0
for t in range(self._options['epochs']):
epoch_loss = []
num_correct = 0
num_total = 0
for X, y in self._train_loader:
# Data.
X = torch.autograd.Variable(X.cuda())
y = torch.autograd.Variable(y.cuda(non_blocking = True))
# Clear the existing gradients.
self._solver.zero_grad()
# Forward pass.
score = self._net(X)
loss = self._criterion(score, y)
epoch_loss.append(loss.data[0])
# Prediction.
_, prediction = torch.max(score.data, 1)
num_total += y.size(0)
num_correct += torch.sum(prediction == y.data)
# Backward pass.
loss.backward()
self._solver.step()
ii += 1
x = torch.Tensor([ii])
y = torch.Tensor([loss.data[0]])
vis.line(X=x, Y=y, win='polynomial', update='append' if ii > 0 else None)
num_correct = torch.tensor(num_correct).float().cuda()
num_total = torch.tensor(num_total).float().cuda()
train_acc = 100 * num_correct / num_total
test_acc = self._accuracy(self._test_loader)
self._scheduler.step(test_acc)
if test_acc > best_acc:
best_acc = test_acc
best_epoch = t + 1
print('*', end='')
# Save model onto disk.
torch.save(self._net.state_dict(),
os.path.join(self._path['model'],
'HBP_fc_epoch_%d.pth' % (t + 1)))
print('%d\t%4.3f\t\t%4.2f%%\t\t%4.2f%%' %
(t+1, sum(epoch_loss) / len(epoch_loss), train_acc, test_acc))
print('Best at epoch %d, test accuaray %f' % (best_epoch, best_acc))
def _accuracy(self, data_loader):
self._net.train(False)
num_correct = 0
num_total = 0
for X, y in data_loader:
# Data.
X = torch.autograd.Variable(X.cuda())
y = torch.autograd.Variable(y.cuda(non_blocking = True))
# Prediction.
score = self._net(X)
_, prediction = torch.max(score.data, 1)
num_total += y.size(0)
num_correct += torch.sum(prediction == y.data)
self._net.train(True) # Set the model to training phase
num_correct = torch.tensor(num_correct).float().cuda()
num_total = torch.tensor(num_total).float().cuda()
return 100 * num_correct / num_total
def getStat(self):
print('Compute mean and variance for training data.')
train_data = cub200.CUB200(
root=self._path['cub200'], train=True,
transform=torchvision.transforms.ToTensor(), download=True)
train_loader = torch.utils.data.DataLoader(
train_data, batch_size=1, shuffle=False, num_workers=4,
pin_memory=True)
mean = torch.zeros(3)
std = torch.zeros(3)
for X, _ in train_loader:
for d in range(3):
mean[d] += X[:, d, :, :].mean()
std[d] += X[:, d, :, :].std()
mean.div_(len(train_data))
std.div_(len(train_data))
print(mean)
print(std)
def main():
parser = argparse.ArgumentParser(
description='Train HBP on CUB200.')
parser.add_argument('--base_lr', dest='base_lr', type=float, required=True,
help='Base learning rate for training.')
parser.add_argument('--batch_size', dest='batch_size', type=int,
required=True, help='Batch size.')
parser.add_argument('--epochs', dest='epochs', type=int,
required=True, help='Epochs for training.')
parser.add_argument('--weight_decay', dest='weight_decay', type=float,
required=True, help='Weight decay.')
args = parser.parse_args()
if args.base_lr <= 0:
raise AttributeError('--base_lr parameter must >0.')
if args.batch_size <= 0:
raise AttributeError('--batch_size parameter must >0.')
if args.epochs < 0:
raise AttributeError('--epochs parameter must >=0.')
if args.weight_decay <= 0:
raise AttributeError('--weight_decay parameter must >0.')
options = {
'base_lr': args.base_lr,
'batch_size': args.batch_size,
'epochs': args.epochs,
'weight_decay': args.weight_decay,
}
project_root = os.popen('pwd').read().strip()
path = {
'cub200': os.path.join(project_root, 'data/cub200'),
'model': os.path.join(project_root, 'model'),
}
for d in path:
assert os.path.isdir(path[d])
manager = HBPManager(options, path)
manager.getStat()
manager.train()
if __name__ == '__main__':
main()