-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathextract_features.py
170 lines (131 loc) · 4.6 KB
/
extract_features.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
from __future__ import print_function
import json
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as f
from torchvision import transforms
from dataset import (ClassificationImageDataset,
MultilabelClassificationImageDataset, MultispectralResize,
RGB2Lab, ScalerPCA)
from models.alexnet import alexnet, multispectral_alexnet
from models.resnet import ResNetV2, multispectral_ResNetV2
from util import parse_option
def get_loader(args):
folder = args.data_folder
image_list = args.image_list
if not args.multispectral:
multilabel_targets = None
target_transform = None
if args.multilabel_targets:
with open(args.multilabel_targets, 'r') as f:
multilabel_targets = json.load(f)
target_transform = torch.tensor
normalize = transforms.Normalize(mean=[(0 + 100) / 2, (-86.183 + 98.233) / 2, (-107.857 + 94.478) / 2],
std=[(100 - 0) / 2, (86.183 + 98.233) / 2, (107.857 + 94.478) / 2])
dataset = ClassificationImageDataset(
folder,
image_list,
transforms.Compose([
transforms.Resize((224, 224)),
RGB2Lab(),
transforms.ToTensor(),
normalize
]),
target_transform=target_transform,
multilabel_targets=multilabel_targets
)
else:
target_transform = None
if args.multispectral_dataset == 'BigEarthNet':
target_transform = torch.tensor
dataset = MultilabelClassificationImageDataset(
folder,
image_list,
transforms.Compose([
MultispectralResize((224, 224)),
ScalerPCA('./scaler_pca', args.pca),
transforms.ToTensor(),
]),
target_transform=target_transform,
dataset=args.multispectral_dataset
)
print('number of images: {}'.format(len(dataset)))
loader = torch.utils.data.DataLoader(
dataset, batch_size=args.batch_size, shuffle=False,
num_workers=args.num_workers, pin_memory=True)
return loader
def set_model(args):
if args.model == 'alexnet':
if args.multispectral:
model = multispectral_alexnet(args.feat_dim)
else:
model = alexnet(args.feat_dim)
elif args.model == 'resnet50':
if args.multispectral:
model = multispectral_ResNetV2(args.model)
else:
model = ResNetV2(args.model)
else:
raise NotImplementedError(args.model)
print('==> loading pre-trained model')
ckpt = torch.load(args.resume)
state_dict = ckpt['model']
has_module = False
for k, v in state_dict.items():
if k.startswith('module'):
has_module = True
if has_module:
from collections import OrderedDict
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k[7:] # remove `module.`
new_state_dict[name] = v
model.load_state_dict(new_state_dict)
else:
model.load_state_dict(state_dict)
if args.model == 'resnet50':
model = nn.DataParallel(model)
print('==> done')
model.eval()
if torch.cuda.is_available():
model = model.cuda()
cudnn.benchmark = True
return model
def validate(val_loader, model, opt):
"""
evaluation
"""
features = []
targets = []
# switch to evaluate mode
model.eval()
with torch.no_grad():
for idx, (input, target) in enumerate(val_loader):
print(idx)
input = input.float()
targets.append(target.numpy())
if torch.cuda.is_available():
input = input.cuda()
target = target.cuda()
feat_l, feat_ab = model(input, opt.layer)
feat = torch.cat((feat_l, feat_ab), dim=1)
ff = f.adaptive_avg_pool2d(feat, (1, 1))
features.append(ff.view(ff.size(0), -1).cpu().numpy())
return features, targets
def main():
# parsing args
args = parse_option()
# set the model
model = set_model(args)
# set the data loader
loader = get_loader(args)
features, targets = validate(loader, model, args)
features = np.concatenate(features, axis = 0)
targets = np.concatenate(targets, axis = 0)
print(features.shape)
print(targets.shape)
np.savez(args.features_path, features, targets)
if __name__ == '__main__':
main()