-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.py
144 lines (119 loc) · 4.22 KB
/
eval.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
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision import datasets, transforms
import time
import os
import argparse
from torch.utils.data import Dataset, DataLoader
from torch.optim.swa_utils import AveragedModel, SWALR
from utils import AverageMeter, ProgressMeter, accuracy, LabelSmoothingLoss, Cutout
from seresnet import get_seresnet_cifar
import pandas as pd
SAVEPATH = './weight/'
WEIGHTDECAY = 1e-4
MOMENTUM = 0.9
BATCHSIZE = 128
LR = 0.1
EPOCHS = 300
PRINTFREQ = 100
LABELSMOOTH = True
SWA = True
SWA_LR = 0.02
SWA_START = 200
CUTOUT = True
CUTOUTSIZE = 8
ACTIVATION = 'mish' # 'relu', 'swish', 'mish'
class TestImageFolder(torchvision.datasets.ImageFolder):
def __getitem__(self, index):
# return image path
return super(TestImageFolder, self).__getitem__(index), self.imgs[index][0].split('/')[-1]
def main():
print('save path:', SAVEPATH)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print('device:', device)
print('weight_decay:', WEIGHTDECAY)
print('momentum:', MOMENTUM)
print('batch_size:', BATCHSIZE)
print('lr:', LR)
print('epoch:', EPOCHS)
print('Label smoothing:', LABELSMOOTH)
print('Stochastic Weight Averaging:', SWA)
if SWA:
print('Swa lr:', SWA_LR)
print('Swa start epoch:', SWA_START)
print('Cutout augmentation:', CUTOUT)
if CUTOUT:
print('Cutout size:', CUTOUTSIZE)
print('Activation:', ACTIVATION)
model = get_seresnet_cifar(activation=ACTIVATION)
if SWA:
swa_model = AveragedModel(model)
normalize = transforms.Normalize(mean=[0.47889522, 0.47227842, 0.43047404],
std=[0.24205776, 0.23828046, 0.25874835])
if SWA:
if CUTOUT:
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
Cutout(size=CUTOUTSIZE)
])
else:
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize
])
train_dataset = torchvision.datasets.ImageFolder(
'/content/train', transform=train_transform)
train_loader = DataLoader(train_dataset,
batch_size=BATCHSIZE, shuffle=True,
num_workers=4, pin_memory=True)
print('swa data ready')
if os.path.isfile(os.path.join(SAVEPATH, 'latest_checkpoint.pth')):
checkpoint = torch.load(os.path.join(SAVEPATH, 'latest_checkpoint.pth'))
model.load_state_dict(checkpoint['model'])
model = model.to(device)
model.eval()
if SWA:
print('swa update batch norm')
swa_model.load_state_dict(checkpoint['swa_model'])
swa_model = swa_model.to(device)
torch.optim.swa_utils.update_bn(train_loader, swa_model, device)
swa_model.eval()
print('model ready')
test_transform = transforms.Compose([
transforms.ToTensor(),
normalize
])
test_dataset = TestImageFolder('/content/test', transform=test_transform)
test_loader = DataLoader(test_dataset, batch_size=BATCHSIZE, num_workers=4, shuffle=False)
print('test data ready')
print('Make an evaluation csv file for kaggle submission...')
Category = []
Id = []
with torch.no_grad():
for data in test_loader:
(input, _), name = data
input = input.to(device)
output = swa_model(input)
output = torch.argmax(output, dim=1)
Id = Id + list(name)
Category = Category + output.tolist()
#Id = list(range(0, 90000))
samples = {
'Id': Id,
'Target': Category
}
df = pd.DataFrame(samples, columns=['Id', 'Target'])
df.to_csv(os.path.join(SAVEPATH, 'submission.csv'), index=False)
print('Done!!')
if __name__ == "__main__":
main()