forked from ZFTurbo/Weighted-Boxes-Fusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_oid.py
321 lines (277 loc) · 10.7 KB
/
example_oid.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
# coding: utf-8
__author__ = 'ZFTurbo: https://kaggle.com/zfturbo'
import os
import time
import pickle
import numpy as np
import pandas as pd
from multiprocessing import Pool, cpu_count
from itertools import repeat
from ensemble_boxes import *
from map_boxes import *
def save_in_file_fast(arr, file_name):
pickle.dump(arr, open(file_name, 'wb'))
def load_from_file_fast(file_name):
return pickle.load(open(file_name, 'rb'))
def get_detections(path):
preds = pd.read_csv(path)
ids = preds['ImageId'].values
preds_strings = preds['PredictionString'].values
ImageID = []
LabelName = []
Conf = []
XMin = []
XMax = []
YMin = []
YMax = []
for j in range(len(ids)):
# print('Go for {}'.format(ids[j]))
id = ids[j]
if str(preds_strings[j]) == 'nan':
continue
arr = preds_strings[j].strip().split(' ')
if len(arr) % 6 != 0:
print('Some problem here! {}'.format(id))
exit()
for i in range(0, len(arr), 6):
ImageID.append(id)
LabelName.append(arr[i])
Conf.append(float(arr[i + 1]))
XMin.append(float(arr[i + 2]))
XMax.append(float(arr[i + 4]))
YMin.append(float(arr[i + 3]))
YMax.append(float(arr[i + 5]))
res = pd.DataFrame(ImageID, columns=['ImageId'])
res['LabelName'] = LabelName
res['Conf'] = Conf
res['XMin'] = XMin
res['XMax'] = XMax
res['YMin'] = YMin
res['YMax'] = YMax
return res
def process_single_id(id, res, weights, params):
run_type = params['run_type']
verbose = params['verbose']
if verbose:
print('Go for ID: {}'.format(id))
boxes_list = []
scores_list = []
labels_list = []
labels_to_use_forward = dict()
labels_to_use_backward = dict()
for i in range(len(res[id])):
boxes = []
scores = []
labels = []
dt = res[id][i]
if str(dt) == 'nan':
boxes = np.zeros((0, 4), dtype=np.float32)
scores = np.zeros((0, ), dtype=np.float32)
labels = np.zeros((0, ), dtype=np.int32)
boxes_list.append(boxes)
scores_list.append(scores)
labels_list.append(labels)
continue
pred = dt.strip().split(' ')
# Empty preds
if len(pred) <= 1:
boxes = np.zeros((0, 4), dtype=np.float32)
scores = np.zeros((0,), dtype=np.float32)
labels = np.zeros((0,), dtype=np.int32)
boxes_list.append(boxes)
scores_list.append(scores)
labels_list.append(labels)
continue
# Check correctness
if len(pred) % 6 != 0:
print('Erorr % 6 {}'.format(len(pred)))
print(dt)
exit()
for j in range(0, len(pred), 6):
lbl = pred[j]
scr = float(pred[j + 1])
box_x1 = float(pred[j + 2])
box_y1 = float(pred[j + 3])
box_x2 = float(pred[j + 4])
box_y2 = float(pred[j + 5])
if box_x1 >= box_x2:
if verbose:
print('Problem with box x1 and x2: {}. Skip it'.format(pred[j:j+6]))
continue
if box_y1 >= box_y2:
if verbose:
print('Problem with box y1 and y2: {}. Skip it'.format(pred[j:j+6]))
continue
if scr <= 0:
if verbose:
print('Problem with box score: {}. Skip it'.format(pred[j:j+6]))
continue
boxes.append([box_x1, box_y1, box_x2, box_y2])
scores.append(scr)
if lbl not in labels_to_use_forward:
cur_point = len(labels_to_use_forward)
labels_to_use_forward[lbl] = cur_point
labels_to_use_backward[cur_point] = lbl
labels.append(labels_to_use_forward[lbl])
boxes = np.array(boxes, dtype=np.float32)
scores = np.array(scores, dtype=np.float32)
labels = np.array(labels, dtype=np.int32)
boxes_list.append(boxes)
scores_list.append(scores)
labels_list.append(labels)
# Empty predictions for all models
if len(boxes_list) == 0:
return np.array([]), np.array([]), np.array([])
if run_type == 'wbf':
merged_boxes, merged_scores, merged_labels = weighted_boxes_fusion(boxes_list, scores_list, labels_list,
weights=weights, iou_thr=params['intersection_thr'],
skip_box_thr=params['skip_box_thr'],
conf_type=params['conf_type'])
elif run_type == 'nms':
iou_thr = params['iou_thr']
merged_boxes, merged_scores, merged_labels = nms(boxes_list, scores_list, labels_list, weights=weights, iou_thr=iou_thr)
elif run_type == 'soft-nms':
iou_thr = params['iou_thr']
sigma = params['sigma']
thresh = params['thresh']
merged_boxes, merged_scores, merged_labels = soft_nms(boxes_list, scores_list, labels_list,
weights=weights, iou_thr=iou_thr, sigma=sigma, thresh=thresh)
elif run_type == 'nmw':
merged_boxes, merged_scores, merged_labels = non_maximum_weighted(boxes_list, scores_list, labels_list,
weights=weights, iou_thr=params['intersection_thr'],
skip_box_thr=params['skip_box_thr'])
if verbose:
print(len(boxes_list), len(merged_boxes))
if 'limit_boxes' in params:
limit_boxes = params['limit_boxes']
if len(merged_boxes) > limit_boxes:
merged_boxes = merged_boxes[:limit_boxes]
merged_scores = merged_scores[:limit_boxes]
merged_labels = merged_labels[:limit_boxes]
# Rename labels back
merged_labels_string = []
for m in merged_labels:
merged_labels_string.append(labels_to_use_backward[m])
merged_labels = np.array(merged_labels_string, dtype=np.str)
# Create IDs array
ids_list = [id] * len(merged_labels)
return merged_boxes, merged_scores, merged_labels, ids_list
def ensemble_predictions(pred_filenames, weights, params):
verbose = False
if 'verbose' in params:
verbose = params['verbose']
start_time = time.time()
procs_to_use = max(cpu_count() // 2, 1)
# procs_to_use = 1
if verbose:
print('Use processes: {}'.format(procs_to_use))
res = dict()
ref_ids = None
for j in range(len(pred_filenames)):
s = pd.read_csv(pred_filenames[j])
try:
s.sort_values('ImageId', inplace=True)
except:
s.sort_values('ImageID', inplace=True)
s.reset_index(drop=True, inplace=True)
try:
ids = s['ImageId'].values
except:
ids = s['ImageID'].values
preds = s['PredictionString'].values
if ref_ids is None:
ref_ids = tuple(ids)
else:
if ref_ids != tuple(ids):
print('Different IDs in ensembled CSVs!')
exit()
for i in range(len(ids)):
id = ids[i]
if id not in res:
res[id] = []
res[id].append(preds[i])
p = Pool(processes=procs_to_use)
ids_to_use = sorted(list(res.keys()))
results = p.starmap(process_single_id, zip(ids_to_use, repeat(res), repeat(weights), repeat(params)))
all_ids = []
all_boxes = []
all_scores = []
all_labels = []
for boxes, scores, labels, ids_list in results:
if boxes is None:
continue
all_boxes.append(boxes)
all_scores.append(scores)
all_labels.append(labels)
all_ids.append(ids_list)
all_ids = np.concatenate(all_ids)
all_boxes = np.concatenate(all_boxes)
all_scores = np.concatenate(all_scores)
all_labels = np.concatenate(all_labels)
if verbose:
print(all_ids.shape, all_boxes.shape, all_scores.shape, all_labels.shape)
res = pd.DataFrame(all_ids, columns=['ImageId'])
res['LabelName'] = all_labels
res['Conf'] = all_scores
res['XMin'] = all_boxes[:, 0]
res['XMax'] = all_boxes[:, 2]
res['YMin'] = all_boxes[:, 1]
res['YMax'] = all_boxes[:, 3]
if verbose:
print('Run time: {:.2f}'.format(time.time() - start_time))
return res
if __name__ == '__main__':
if 1:
params = {
'run_type': 'nms',
'iou_thr': 0.5,
'verbose': True,
}
if 1:
params = {
'run_type': 'soft-nms',
'iou_thr': 0.5,
'thresh': 0.0001,
'sigma': 0.1,
'verbose': True,
}
if 1:
params = {
'run_type': 'nmw',
'skip_box_thr': 0.000000001,
'intersection_thr': 0.5,
'limit_boxes': 30000,
'verbose': True,
}
if 1:
params = {
'run_type': 'wbf',
'skip_box_thr': 0.0000001,
'intersection_thr': 0.6,
'conf_type': 'avg',
'limit_boxes': 30000,
'verbose': True,
}
# Files available here: https://github.com/ZFTurbo/Weighted-Boxes-Fusion/releases/download/v1.0/test_data.zip
annotations_path = 'test_data/challenge-2019-validation-detection-bbox-expand_3520.csv'
pred_list = [
'test_data/0.46450_TF_IRV2_atrous_3520.csv',
'test_data/0.52319_mmdet_3520.csv',
'test_data/0.52918_tensorpack1_3520.csv',
'test_data/0.53775_tensorpack2_3520.csv',
'test_data/0.51145_retinanet_3520.csv',
]
weights = [1, 1, 1, 1, 1]
ann = pd.read_csv(annotations_path)
ann = ann[['ImageId', 'LabelName', 'XMin', 'XMax', 'YMin', 'YMax']].values
# Find initial scores
for i in range(len(pred_list)):
det = get_detections(pred_list[i])
det = det[['ImageId', 'LabelName', 'Conf', 'XMin', 'XMax', 'YMin', 'YMax']].values
mean_ap, average_precisions = mean_average_precision_for_boxes(ann, det, verbose=False)
print("File: {} mAP: {:.6f}".format(os.path.basename(pred_list[i]), mean_ap))
ensemble_preds = ensemble_predictions(pred_list, weights, params)
ensemble_preds.to_csv("test_data/debug.csv", index=False)
ensemble_preds = ensemble_preds[['ImageId', 'LabelName', 'Conf', 'XMin', 'XMax', 'YMin', 'YMax']].values
mean_ap, average_precisions = mean_average_precision_for_boxes(ann, ensemble_preds, verbose=True)
print("Ensemble [{}] Weights: {} Params: {} mAP: {:.6f}".format(len(weights), weights, params, mean_ap))