-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_few_shot.py
144 lines (119 loc) · 4.98 KB
/
test_few_shot.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
import argparse
import yaml
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import scipy.stats
from tqdm import tqdm
from torch.utils.data import DataLoader
from sklearn.metrics import roc_auc_score
import datasets
import models
import utils
import utils.few_shot as fs
from datasets.samplers import CategoriesSampler
import os
import time
os.environ['MKL_THREADING_LAYER'] = 'GNU'
os.environ['MKL_SERVICE_FORCE_INTEL'] = '1'
def mean_confidence_interval(data, confidence=0.95):
a = 1.0 * np.array(data)
n = len(a)
se = scipy.stats.sem(a)
h = se * scipy.stats.t.ppf((1 + confidence) / 2., n - 1)
return h
def main(config):
# dataset
dataset = datasets.make(config['dataset'], **config['dataset_args'])
utils.log('dataset: {} (x{}), {}'.format(
dataset[0][0].shape, len(dataset), dataset.n_classes))
if not args.sauc:
n_way = 5
else:
n_way = 2
n_shot, n_query = args.shot, 15
n_batch = 200
ep_per_batch = 4
batch_sampler = CategoriesSampler(
dataset.label, n_batch, n_way, n_shot + n_query,
ep_per_batch=ep_per_batch)
loader = DataLoader(dataset, batch_sampler=batch_sampler,
num_workers=8, pin_memory=True)
# model
if config.get('load') is None:
model = models.make('meta-baseline', encoder=None)
else:
model = models.load(torch.load(config['load']))
if config.get('load_encoder') is not None:
encoder = models.load(torch.load(config['load_encoder'])).encoder
model.encoder = encoder
if config.get('_parallel'):
model = nn.DataParallel(model)
if config.get('_parallel'):
model = nn.DataParallel(model)
model.eval()
print('num params: {}'.format(utils.compute_n_params(model)))
# testing
aves_keys = ['vl', 'va']
aves = {k: utils.Averager() for k in aves_keys}
test_epochs = args.test_epochs
np.random.seed(0)
va_lst = []
time_total = 0
for epoch in range(1, test_epochs + 1):
for data, _ in tqdm(loader, leave=False):
x_shot, x_query = fs.split_shot_query(
data.cuda(), n_way, n_shot, n_query,
ep_per_batch=ep_per_batch)
with torch.no_grad():
if not args.sauc:
start =time.perf_counter()
logits = model(x_shot, x_query)
logits = logits.view(-1, n_way)
end= time.perf_counter()
time_total += end-start
label = fs.make_nk_label(n_way, n_query,
ep_per_batch=ep_per_batch).cuda()
loss = F.cross_entropy(logits, label)
acc = utils.compute_acc(logits, label)
aves['vl'].add(loss.item(), len(data))
aves['va'].add(acc, len(data))
va_lst.append(acc)
else:
x_shot = x_shot[:, 0, :, :, :, :].contiguous()
shot_shape = x_shot.shape[:-3]
img_shape = x_shot.shape[-3:]
bs = shot_shape[0]
p = model.encoder(x_shot.view(-1, *img_shape)).reshape(
*shot_shape, -1).mean(dim=1, keepdim=True)
q = model.encoder(x_query.view(-1, *img_shape)).view(
bs, -1, p.shape[-1])
p = F.normalize(p, dim=-1)
q = F.normalize(q, dim=-1)
s = torch.bmm(q, p.transpose(2, 1)).view(bs, -1).cpu()
for i in range(bs):
k = s.shape[1] // 2
y_true = [1] * k + [0] * k
acc = roc_auc_score(y_true, s[i])
aves['va'].add(acc, len(data))
va_lst.append(acc)
print('test epoch {}: acc={:.2f} +- {:.2f} (%), loss={:.4f} (@{})'.format(
epoch, aves['va'].item() * 100,
mean_confidence_interval(va_lst) * 100,
aves['vl'].item(), _[-1]))
print('Running time: %s Seconds'%(time_total))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--config', default='./configs/test_few_shot.yaml')
parser.add_argument('--shot', type=int, default=5)
parser.add_argument('--test-epochs', type=int, default=1)
parser.add_argument('--sauc', action='store_true')
parser.add_argument('--load', default='./save/meta_mini-imagenet-1shot_meta-baseline-resnet12/_original/max-va.pth')
parser.add_argument('--gpu', default='1')
args = parser.parse_args()
config = yaml.load(open(args.config, 'r'), Loader=yaml.FullLoader)
if len(args.gpu.split(',')) > 1:
config['_parallel'] = True
utils.set_gpu(args.gpu)
main(config)