-
Notifications
You must be signed in to change notification settings - Fork 17
/
test_singlenet_phase.py
327 lines (270 loc) · 11.6 KB
/
test_singlenet_phase.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
import torch.nn.init as init
import torchvision
from torchvision import datasets, models, transforms, utils
from torch.utils.data import Dataset, DataLoader
from torchvision.datasets import ImageFolder
from torch.nn import DataParallel
import os
from PIL import Image
import time
import pickle
import numpy as np
import argparse
from torchvision.transforms import Lambda
parser = argparse.ArgumentParser(description='lstm testing')
parser.add_argument('-g', '--gpu', default=[1], nargs='+', type=int, help='index of gpu to use, default 1')
parser.add_argument('-s', '--seq', default=4, type=int, help='sequence length, default 4')
parser.add_argument('-t', '--test', default=800, type=int, help='test batch size, default 800')
parser.add_argument('-w', '--work', default=2, type=int, help='num of workers to use, default 2')
parser.add_argument('-n', '--name', type=str, help='name of model')
parser.add_argument('-c', '--crop', default=1, type=int, help='0 rand, 1 cent, 5 five_crop, 10 ten_crop, default 1')
args = parser.parse_args()
gpu_usg = ",".join(list(map(str, args.gpu)))
os.environ["CUDA_VISIBLE_DEVICES"] = gpu_usg
sequence_length = args.seq
test_batch_size = args.test
workers = args.work
model_name = args.name
crop_type = args.crop
model_pure_name, _ = os.path.splitext(model_name)
num_gpu = torch.cuda.device_count()
use_gpu = torch.cuda.is_available()
print('number of gpu : {:6d}'.format(num_gpu))
print('sequence length : {:6d}'.format(sequence_length))
print('test batch size : {:6d}'.format(test_batch_size))
print('num of workers : {:6d}'.format(workers))
print('test crop type : {:6d}'.format(crop_type))
print('name of this model: {:s}'.format(model_name)) # so we can store all result in the same file
def pil_loader(path):
with open(path, 'rb') as f:
with Image.open(f) as img:
return img.convert('RGB')
class CholecDataset(Dataset):
def __init__(self, file_paths, file_labels, transform=None,
loader=pil_loader):
self.file_paths = file_paths
self.file_labels_1 = file_labels[:, range(7)]
self.file_labels_2 = file_labels[:, -1]
self.transform = transform
# self.target_transform=target_transform
self.loader = loader
def __getitem__(self, index):
img_names = self.file_paths[index]
labels_1 = self.file_labels_1[index]
labels_2 = self.file_labels_2[index]
imgs = self.loader(img_names)
if self.transform is not None:
imgs = self.transform(imgs)
return imgs, labels_1, labels_2
def __len__(self):
return len(self.file_paths)
class CholecDataset(Dataset):
def __init__(self, file_paths, file_labels, transform=None,
loader=pil_loader):
self.file_paths = file_paths
self.file_labels_1 = file_labels[:, range(7)]
self.file_labels_2 = file_labels[:, -1]
self.transform = transform
# self.target_transform=target_transform
self.loader = loader
def __getitem__(self, index):
img_names = self.file_paths[index]
labels_1 = self.file_labels_1[index]
labels_2 = self.file_labels_2[index]
imgs = self.loader(img_names)
if self.transform is not None:
imgs = self.transform(imgs)
return imgs, labels_1, labels_2
def __len__(self):
return len(self.file_paths)
class resnet_lstm(torch.nn.Module):
def __init__(self):
super(resnet_lstm, self).__init__()
resnet = models.resnet50(pretrained=True)
self.share = torch.nn.Sequential()
self.share.add_module("conv1", resnet.conv1)
self.share.add_module("bn1", resnet.bn1)
self.share.add_module("relu", resnet.relu)
self.share.add_module("maxpool", resnet.maxpool)
self.share.add_module("layer1", resnet.layer1)
self.share.add_module("layer2", resnet.layer2)
self.share.add_module("layer3", resnet.layer3)
self.share.add_module("layer4", resnet.layer4)
self.share.add_module("avgpool", resnet.avgpool)
self.lstm = nn.LSTM(2048, 512, batch_first=True)
self.fc = nn.Linear(512, 7)
init.xavier_normal(self.lstm.all_weights[0][0])
init.xavier_normal(self.lstm.all_weights[0][1])
init.xavier_uniform(self.fc.weight)
def forward(self, x):
x = self.share.forward(x)
x = x.view(-1, 2048)
x = x.view(-1, sequence_length, 2048)
self.lstm.flatten_parameters()
y, _ = self.lstm(x)
y = y.contiguous().view(-1, 512)
y = self.fc(y)
return y
def get_useful_start_idx(sequence_length, list_each_length):
count = 0
idx = []
for i in range(len(list_each_length)):
for j in range(count, count + (list_each_length[i] + 1 - sequence_length)):
idx.append(j)
count += list_each_length[i]
return idx
def get_data(data_path):
with open(data_path, 'rb') as f:
train_test_paths_labels = pickle.load(f)
train_paths = train_test_paths_labels[0]
val_paths = train_test_paths_labels[1]
test_paths = train_test_paths_labels[2]
train_labels = train_test_paths_labels[3]
val_labels = train_test_paths_labels[4]
test_labels = train_test_paths_labels[5]
train_num_each = train_test_paths_labels[6]
val_num_each = train_test_paths_labels[7]
test_num_each = train_test_paths_labels[8]
print('train_paths : {:6d}'.format(len(train_paths)))
print('train_labels : {:6d}'.format(len(train_labels)))
print('valid_paths : {:6d}'.format(len(val_paths)))
print('valid_labels : {:6d}'.format(len(val_labels)))
print('test_paths : {:6d}'.format(len(test_paths)))
print('test_labels : {:6d}'.format(len(test_labels)))
train_labels = np.asarray(train_labels, dtype=np.int64)
val_labels = np.asarray(val_labels, dtype=np.int64)
test_labels = np.asarray(test_labels, dtype=np.int64)
train_transforms = transforms.Compose([
transforms.RandomCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.3456, 0.2281, 0.2233], [0.2528, 0.2135, 0.2104])
])
if crop_type == 0:
test_transforms = transforms.Compose([
transforms.RandomCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.3456, 0.2281, 0.2233], [0.2528, 0.2135, 0.2104])
])
elif crop_type == 1:
test_transforms = transforms.Compose([
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.3456, 0.2281, 0.2233], [0.2528, 0.2135, 0.2104])
])
elif crop_type == 5:
test_transforms = transforms.Compose([
transforms.FiveCrop(224),
Lambda(lambda crops: torch.stack([transforms.ToTensor()(crop) for crop in crops])),
Lambda(
lambda crops: torch.stack(
[transforms.Normalize([0.3456, 0.2281, 0.2233], [0.2528, 0.2135, 0.2104])(crop) for crop in crops]))
])
elif crop_type == 10:
test_transforms = transforms.Compose([
transforms.TenCrop(224),
Lambda(lambda crops: torch.stack([transforms.ToTensor()(crop) for crop in crops])),
Lambda(
lambda crops: torch.stack(
[transforms.Normalize([0.3456, 0.2281, 0.2233], [0.2528, 0.2135, 0.2104])(crop) for crop in crops]))
])
train_dataset = CholecDataset(train_paths, train_labels, train_transforms)
val_dataset = CholecDataset(val_paths, val_labels, test_transforms)
test_dataset = CholecDataset(test_paths, test_labels, test_transforms)
return train_dataset, train_num_each, val_dataset, val_num_each, test_dataset, test_num_each
def test_model(test_dataset, test_num_each):
num_test = len(test_dataset)
test_useful_start_idx = get_useful_start_idx(sequence_length, test_num_each)
num_test_we_use = len(test_useful_start_idx)
# num_test_we_use = 804
# num_test_we_use = len(test_useful_start_idx) // (test_batch_size // sequence_length) * (
# test_batch_size // sequence_length)
test_we_use_start_idx = test_useful_start_idx[0:num_test_we_use]
test_idx = []
for i in range(num_test_we_use):
for j in range(sequence_length):
test_idx.append(test_we_use_start_idx[i] + j)
num_test_all = len(test_idx)
print('num test start idx : {:6d}'.format(len(test_useful_start_idx)))
print('last idx test start: {:6d}'.format(test_useful_start_idx[-1]))
print('num of test dataset: {:6d}'.format(num_test))
print('num of test we use : {:6d}'.format(num_test_we_use))
print('num of all test use: {:6d}'.format(num_test_all))
test_loader = DataLoader(
test_dataset,
batch_size=test_batch_size,
sampler=test_idx,
num_workers=workers,
pin_memory=False
)
model = resnet_lstm()
model = DataParallel(model)
model.load_state_dict(torch.load(model_name))
if use_gpu:
model = model.cuda()
# 应该可以直接多gpu计算
# model = model.module #要测试一下
criterion = nn.CrossEntropyLoss(size_average=False)
model.eval()
test_loss = 0.0
test_corrects = 0
test_start_time = time.time()
all_preds = []
for data in test_loader:
inputs, labels_1, labels_2 = data
labels_2 = labels_2[(sequence_length - 1)::sequence_length]
if use_gpu:
inputs = Variable(inputs.cuda(), volatile=True)
labels = Variable(labels_2.cuda(), volatile=True)
else:
inputs = Variable(inputs, volatile=True)
labels = Variable(labels_2, volatile=True)
if crop_type == 0 or crop_type == 1:
outputs = model.forward(inputs)
elif crop_type == 5:
inputs = inputs.permute(1, 0, 2, 3, 4).contiguous()
inputs = inputs.view(-1, 3, 224, 224)
outputs = model.forward(inputs)
outputs = outputs.view(5, -1, 7)
outputs = torch.mean(outputs, 0)
elif crop_type == 10:
inputs = inputs.permute(1, 0, 2, 3, 4).contiguous()
inputs = inputs.view(-1, 3, 224, 224)
outputs = model.forward(inputs)
outputs = outputs.view(10, -1, 7)
outputs = torch.mean(outputs, 0)
outputs = outputs[sequence_length - 1::sequence_length]
_, preds = torch.max(outputs.data, 1)
for i in range(len(preds)):
all_preds.append(preds[i])
print(len(all_preds))
loss = criterion(outputs, labels)
test_loss += loss.data[0]
test_corrects += torch.sum(preds == labels.data)
test_elapsed_time = time.time() - test_start_time
test_accuracy = test_corrects / num_test_we_use
test_average_loss = test_loss / num_test_we_use
print('type of all_preds:', type(all_preds))
print('leng of all preds:', len(all_preds))
save_test = int("{:4.0f}".format(test_accuracy * 10000))
pred_name = model_pure_name + '_test_' + str(save_test) + '_crop_' + str(crop_type) + '.pkl'
with open(pred_name, 'wb') as f:
pickle.dump(all_preds, f)
print('test elapsed: {:2.0f}m{:2.0f}s'
' test loss: {:4.4f}'
' test accu: {:.4f}'
.format(test_elapsed_time // 60,
test_elapsed_time % 60,
test_average_loss, test_accuracy))
print()
def main():
_, _, _, _, test_dataset, test_num_each = get_data('train_val_test_paths_labels.pkl')
test_model(test_dataset, test_num_each)
if __name__ == "__main__":
main()
print('Done')
print()