-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimagenet_np.py
153 lines (114 loc) · 4.39 KB
/
imagenet_np.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
import json
import torch.optim.lr_scheduler
from torch import optim
import time
import argparse
from torch.utils.data import DataLoader
from datasets import *
from loss import *
batch_size_ft = 256
v_batch_size = 50
ft_epoch = 30
max_train_ft = 140000
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
torch.backends.cudnn.benchmark = True
def eval(model):
model.eval()
val_loss = []
val_acc = []
i = 1
for imgs, lbls in val_ds:
imgs = imgs.to(device)
lbls = lbls.to(device)
outputs = model(imgs)
val_loss.append(criterion(outputs, lbls).detach().cpu())
val_acc.append(((outputs.argmax(dim=1) == lbls).sum() / lbls.shape[0]).detach().cpu())
print('{}/{} val loss {:5.02f} val acc {:5.02f}'.format(i, n_val, torch.stack(val_loss).mean(), 100. * torch.stack(val_acc).mean()), end='\r')
i += 1
print()
return torch.stack(val_loss).mean().item(), 100. * torch.stack(val_acc).mean().item()
#############
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", help="path to imagenet")
parser.add_argument("--eval_pretrained", type=bool, default=False)
parser.add_argument("--output", default="results_imagenet.json")
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--nb_seeds", type=int, default=10)
args = parser.parse_args()
data = []
train, val = build_imagenet(args.data_dir, size=192)
val_ds = DataLoader(val, batch_size=v_batch_size, num_workers=10)
n_val = len(val_ds)
for s in range(args.seed, args.seed + args.nb_seeds):
print('doing seed {}'.format(s))
torch.manual_seed(s)
np.random.seed(s)
tr_loss = []
tr_acc = []
ft_loss = []
ft_acc = []
# build model
model = torchvision.models.resnet50(pretrained=False)
model.to(device)
# optimization hparams
criterion = nn.CrossEntropyLoss()
if not args.eval_pretrained:
criterion2 = CrossEntropyLabelSmooth(num_classes=1000, epsilon=0.1)
print('Fine tuning all layers')
start = time.time()
# new dataset batch_size
train_ds = DataLoader(train, batch_size=batch_size_ft, num_workers=10, shuffle=True)
n_train = len(train_ds)
# train all model
for p in model.parameters():
p.requires_grad = True
# new optim and sched
optimizer = optim.SGD(model.parameters(), lr=0.02, momentum=0.9, nesterov=True, weight_decay=0.00001)
# optimizer = optim.Adam(model.parameters(), lr=0.1, weight_decay=0.0002)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_train_ft//2000, eta_min=0.001)
sched = torch.optim.lr_scheduler.StepLR(optimizer, step_size=30)
i = 1
for e in range(ft_epoch):
running_loss = []
running_acc = []
for imgs, lbls in train_ds:
imgs = imgs.to(device)
lbls = lbls.to(device)
optimizer.zero_grad()
outputs = model(imgs)
loss = criterion(outputs, lbls)
loss = loss + criterion2(outputs, lbls)
loss.backward()
optimizer.step()
# print statistics
running_loss.append(loss.detach().cpu())
running_acc.append(((outputs.argmax(dim=1) == lbls).sum() / lbls.shape[0]).detach().cpu())
print('{}/{} loss: {:5.02f} acc: {:5.02f} in {:6.01f}'.format(i, n_train, torch.stack(running_loss).mean(),
100 * torch.stack(running_acc).mean(),
time.time() - start), end='\r')
if i % 2000 == 0:
print()
l, a = eval(model)
ft_loss.append(l)
ft_acc.append(a)
model.train()
sched.step()
if i >= max_train_ft:
break
i += 1
if i >= max_train_ft:
break
# eval
if args.eval_pretrained:
eval(model)
d = { 'seed': s,
'tr_loss': tr_loss,
'tr_acc': tr_acc,
'ft_loss': ft_loss,
'ft_acc': ft_acc,
'time': time.time() - start
}
data.append(d)
print(d)
with open(args.output, 'w') as fp:
json.dump(data, fp)