forked from GuYuc/WS-DAN.PyTorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.py
145 lines (117 loc) · 5.01 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
145
"""EVALUATION
Created: Nov 22,2019 - Yuchong Gu
Revised: Dec 03,2019 - Yuchong Gu
"""
import os
import logging
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from torch.utils.data import DataLoader
from tqdm import tqdm
import config
from models import WSDAN
from datasets import get_trainval_datasets
from utils import TopKAccuracyMetric, batch_augment
# GPU settings
assert torch.cuda.is_available()
os.environ['CUDA_VISIBLE_DEVICES'] = config.GPU
device = torch.device("cuda")
torch.backends.cudnn.benchmark = True
# visualize
visualize = config.visualize
savepath = config.eval_savepath
if visualize:
os.makedirs(savepath, exist_ok=True)
ToPILImage = transforms.ToPILImage()
MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
def generate_heatmap(attention_maps):
heat_attention_maps = []
heat_attention_maps.append(attention_maps[:, 0, ...]) # R
heat_attention_maps.append(attention_maps[:, 0, ...] * (attention_maps[:, 0, ...] < 0.5).float() + \
(1. - attention_maps[:, 0, ...]) * (attention_maps[:, 0, ...] >= 0.5).float()) # G
heat_attention_maps.append(1. - attention_maps[:, 0, ...]) # B
return torch.stack(heat_attention_maps, dim=1)
def main():
logging.basicConfig(
format='%(asctime)s: %(levelname)s: [%(filename)s:%(lineno)d]: %(message)s',
level=logging.INFO)
warnings.filterwarnings("ignore")
try:
ckpt = config.eval_ckpt
except:
logging.info('Set ckpt for evaluation in config.py')
return
##################################
# Dataset for testing
##################################
_, test_dataset = get_trainval_datasets(config.tag, resize=config.image_size)
test_loader = DataLoader(test_dataset, batch_size=config.batch_size, shuffle=False,
num_workers=2, pin_memory=True)
##################################
# Initialize model
##################################
net = WSDAN(num_classes=test_dataset.num_classes, M=config.num_attentions, net=config.net)
# Load ckpt and get state_dict
checkpoint = torch.load(ckpt)
state_dict = checkpoint['state_dict']
# Load weights
net.load_state_dict(state_dict)
logging.info('Network loaded from {}'.format(ckpt))
##################################
# use cuda
##################################
net.to(device)
if torch.cuda.device_count() > 1:
net = nn.DataParallel(net)
##################################
# Prediction
##################################
raw_accuracy = TopKAccuracyMetric(topk=(1, 5))
ref_accuracy = TopKAccuracyMetric(topk=(1, 5))
raw_accuracy.reset()
ref_accuracy.reset()
net.eval()
with torch.no_grad():
pbar = tqdm(total=len(test_loader), unit=' batches')
pbar.set_description('Validation')
for i, (X, y) in enumerate(test_loader):
X = X.to(device)
y = y.to(device)
# WS-DAN
y_pred_raw, _, attention_maps = net(X)
# Augmentation with crop_mask
crop_image = batch_augment(X, attention_maps, mode='crop', theta=0.1, padding_ratio=0.05)
y_pred_crop, _, _ = net(crop_image)
y_pred = (y_pred_raw + y_pred_crop) / 2.
if visualize:
# reshape attention maps
attention_maps = F.upsample_bilinear(attention_maps, size=(X.size(2), X.size(3)))
attention_maps = torch.sqrt(attention_maps.cpu() / attention_maps.max().item())
# get heat attention maps
heat_attention_maps = generate_heatmap(attention_maps)
# raw_image, heat_attention, raw_attention
raw_image = X.cpu() * STD + MEAN
heat_attention_image = raw_image * 0.5 + heat_attention_maps * 0.5
raw_attention_image = raw_image * attention_maps
for batch_idx in range(X.size(0)):
rimg = ToPILImage(raw_image[batch_idx])
raimg = ToPILImage(raw_attention_image[batch_idx])
haimg = ToPILImage(heat_attention_image[batch_idx])
rimg.save(os.path.join(savepath, '%03d_raw.jpg' % (i * config.batch_size + batch_idx)))
raimg.save(os.path.join(savepath, '%03d_raw_atten.jpg' % (i * config.batch_size + batch_idx)))
haimg.save(os.path.join(savepath, '%03d_heat_atten.jpg' % (i * config.batch_size + batch_idx)))
# Top K
epoch_raw_acc = raw_accuracy(y_pred_raw, y)
epoch_ref_acc = ref_accuracy(y_pred, y)
# end of this batch
batch_info = 'Val Acc: Raw ({:.2f}, {:.2f}), Refine ({:.2f}, {:.2f})'.format(
epoch_raw_acc[0], epoch_raw_acc[1], epoch_ref_acc[0], epoch_ref_acc[1])
pbar.update()
pbar.set_postfix_str(batch_info)
pbar.close()
if __name__ == '__main__':
main()