forked from yihongXU/deepMOT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloss.py
274 lines (217 loc) · 10.1 KB
/
loss.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
# ==========================================================================
#
# This file is a part of implementation for paper:
# DeepMOT: A Differentiable Framework for Training Multiple Object Trackers.
# This contribution is headed by Perception research team, INRIA.
#
# Contributor(s) : Yihong Xu
# INRIA contact : [email protected]
#
# ===========================================================================
from utils.box_utils import *
import torch.nn.functional as F
# weighted classification loss #
def weighted_binary_focal_entropy(output, target, weights=None, gamma=2):
output = torch.clamp(output, min=1e-12, max=(1 - 1e-12))
if weights is not None:
assert weights.size(1) == 2
# weight is of shape [batch,2, 1, 1]
# weight[:,1] is for positive class, label = 1
# weight[:,0] is for negative class, label = 0
loss = torch.pow(output[0, :], gamma)*target[1, :]*weights[:, 1].item() * torch.log(output[1, :]) + \
target[0, :]*weights[:, 0].item() * torch.log(output[0, :])*torch.pow(output[1, :], gamma)
else:
loss = target[1, :] * torch.log(output[1, :]) + target[0, :] * torch.log(output[0, :])
return torch.neg(torch.mean(loss))
def focaLoss(score_tensor, ancrs, state_curr, gt_ids, gt_boxes, args):
# classification loss
# 1)construct gt target label
gt_label = np.zeros((2, score_tensor.shape[1]))
# a) find gt box by gt_id
searched_id = state_curr['gt_id']
negative_indexes = list(range(gt_label.shape[1]))
positive_indexes = list()
if int(searched_id) in gt_ids:
searched_index = gt_ids.index(int(searched_id))
boxA = gt_boxes[searched_index, -4:]
ious = bb_fast_IOU_v1(boxA, ancrs)
# NEGATIVE EXAMPLES
negative_indexes = np.where(ious < 0.3)[0].tolist()
gt_label[1, negative_indexes] = 0.0
# POSITIVE EXAMPLES
positive_indexes = np.where(ious > 0.6)[0].tolist()
gt_label[1, positive_indexes] = 1.0
gt_label[0, :] = 1.0 - gt_label[1, :]
# remove undecided class
gt_label = gt_label[:, negative_indexes + positive_indexes]
# CALCULATE FOCAL LOSS
# num_positive = how many labels = 1
num_positive = len(positive_indexes)
weight2negative = float(num_positive) / gt_label.shape[1]
# case all zeros, then weight2negative = 1.0
if weight2negative <= 0.0:
weight2negative = 1.0
# case all ones, then weight2negative = 0.0
if num_positive == gt_label.shape[1]:
weight2negative = 0.0
weight = torch.tensor([weight2negative, 1.0 - weight2negative], dtype=torch.float32).unsqueeze(0).contiguous()
# weight = weight.view(-1, 2, 1, 1).contiguous()
if args.is_cuda:
weight = weight.cuda()
# weight = Variable(weight, requires_grad=False)
f_loss = 10.0 * weighted_binary_focal_entropy(
score_tensor[:, negative_indexes + positive_indexes],
torch.tensor(gt_label, dtype=torch.float32).cuda(), weights=weight)
return f_loss
# calculate MOTA #
# basic operations
def rowSoftMax(MunkresOut, scale=100.0, threshold=0.7):
"""
row wise softmax function
:param MunkresOut: MunkresNet Output Variable Matrix of shape [batch, h, w]
:return: row wise Softmax matrix
"""
clutter = torch.ones(MunkresOut.size(0), MunkresOut.size(1), 1).cuda() * threshold
return F.softmax(torch.cat([MunkresOut, clutter], dim=2)*scale, dim=2)
def colSoftMax(MunkresOut, scale=100.0, threshold=0.7):
"""
column wise softmax
:param MunkresOut: MunkresNet Output Variable Matrix of shape [batch, h, w]
:return: column wise Softmax matrix
"""
# threshold 0.5
# if not is_cuda:
# missed = Variable(torch.ones(MunkresOut.size(0), 1, MunkresOut.size(2)) * threshold, requires_grad=False)
# else:
missed = torch.ones(MunkresOut.size(0), 1, MunkresOut.size(2)).cuda() * threshold
# requires grad ?
return F.softmax(torch.cat([MunkresOut, missed], dim=1)*scale, dim=1)
def updateCurrentListV3(softmaxed, gt_ids):
"""
find missed objects from matrix_id, mark as -1
:param softmaxed: column wise softmaxed munkres matrix of shape [batch, h, w]
:param gt_ids: list of shape [number of objects] of current frame
:return: updated gt_ids
"""
# [batch, w]
_, idx = torch.max(softmaxed, dim=1)
out = gt_ids + []
for j in range(idx.size(1)-1, -1, -1):
if int(idx[0, j]) == (softmaxed.size(1)-1):
out[j] = -1 # missed object
return out
def createMatrix(index_h, index_w, size_h, size_w):
"""
create a tensor variable fo size [size_h, size_w] having all zeros except for [index_h, index_w]
:param index_h: list of indexes
:param index_w: list of indexes
:return: a matrix, tensor variable
"""
matrix = torch.zeros(1, size_h, size_w).cuda()
matrix[0, index_h, index_w] = 1.0
return matrix
# identity switching
def missedMatchErrorV3(prev_id, gt_ids, hypo_ids, colsoftmaxed, states, toUpdate):
"""
ID switching error
:param input: MunkresNet Output Variable Matrix of shape [batch, h, w]
:param prev_id: dictionary of [object_id (INT): hypothesis_id(INT)] of previous frame
:param gt_ids: torch tensor of shape [batch size, number of objects] of current frame
:param hypo_ids: torch tensor of shape [batch size, number of hypothesis] of current frame
:return: #id_switching, mask for motp
"""
# softmaxed = colsoftmaxed
pre_id = copy.deepcopy(prev_id)
updated_gt_ids = updateCurrentListV3(colsoftmaxed, gt_ids)
id_switching = torch.zeros(1).float().cuda()
# remove the row of missed class
softmaxed = colsoftmaxed[:, :-1, :]
toputOne_h = []
toputOne_w = []
# to record hypo ids needed to switch target images ex. [1,2, 3,4, 5,6....]
toswitch = []
for w in range(len(updated_gt_ids)):
_, idx = torch.max(softmaxed[0, :, w], dim=0)
if updated_gt_ids[w] == -1 or (gt_ids[w] not in pre_id.keys()): # lost object or new object or both
# print("gt id is lost:", gt_ids[w])
if gt_ids[w] in pre_id.keys(): # not new object but lost
if pre_id[gt_ids[w]] in hypo_ids:
tmp = list(range(len(hypo_ids)))
tmp.pop(hypo_ids.index(pre_id[gt_ids[w]]))
id_switching = id_switching + torch.sum(softmaxed[0, tmp, w])
# print("mm is here")
# print(w)
# print(tmp)
else:
# print("i am here")
id_switching = id_switching + torch.sum(softmaxed[0, :, w])
elif updated_gt_ids[w] != -1: # new object but not lost
# add object id to prev_id, update prev id to current
toputOne_w.append(w)
toputOne_h.append(int(idx))
pre_id[updated_gt_ids[w]] = hypo_ids[int(idx)] + 0
else: # new object and lost
id_switching = id_switching + torch.sum(softmaxed[0, :, w])
# if object w is not assigned to an target int(hypo_ids[idx])
# same as previous target pre_id[int(updated_gt_ids[w])]
elif pre_id[updated_gt_ids[w]] != hypo_ids[int(idx)]:
if pre_id[updated_gt_ids[w]] in hypo_ids:
tmp_idx = hypo_ids.index(pre_id[updated_gt_ids[w]]) # index of previous hypo id to this gt_id
toputOne_w.append(w)
toputOne_h.append(tmp_idx) # we minimize old hypo track
tmp = list(range(len(hypo_ids)))
tmp.pop(tmp_idx)
id_switching = id_switching + torch.sum(softmaxed[0, tmp, w])
# switch target templates
if toUpdate and pre_id[updated_gt_ids[w]] not in toswitch: # if pair not yet switched
toswitch.append(pre_id[updated_gt_ids[w]])
toswitch.append(hypo_ids[int(idx)])
state_to_switch = states[pre_id[updated_gt_ids[w]]]
states[pre_id[updated_gt_ids[w]]] = states[hypo_ids[int(idx)]]
states[hypo_ids[int(idx)]] = state_to_switch
del state_to_switch
else:
id_switching = id_switching + torch.sum(softmaxed[0, :, w]) # todo wrong
toputOne_w.append(w)
toputOne_h.append(int(idx)) # todo
# update prev id to current
pre_id[updated_gt_ids[w]] = hypo_ids[int(idx)] + 0
else: # no id switching, no missed, prev_id[updated_gt_ids[w]] == hypo_ids[int(idx)]
tmp = list(range(len(hypo_ids)))
tmp.pop(int(idx))
id_switching = torch.sum(softmaxed[0, tmp, w]) + id_switching
toputOne_w.append(w)
toputOne_h.append(int(idx))
mask_for_matrix = createMatrix(toputOne_h, toputOne_w, softmaxed.size(1), softmaxed.size(2))
return [id_switching, mask_for_matrix, pre_id]
# false negatives
def missedObjectPerframe(colsoftmaxed):
"""
Frame wise FN != average FN of the sequence
:param input: MunkresNet Output Variable Matrix of shape [batch, h, w]
:return: [number of false negatives(missed), normalized_fn]
"""
fn = torch.sum(colsoftmaxed[:, -1, :])
return fn
# false positives
def falsePositivePerFrame(rowsoftmax):
"""
Frame wise FP != average FP of the sequence
:param input: MunkresNet Output Variable Matrix of shape [batch, h, w]
:return: [number of false positives(alarms), normalized_fp]
"""
fp = torch.sum(rowsoftmax[:, :, -1])
return fp
# calculate MOTP #
def deepMOTPperFrame(D, rowsoftmaxed):
"""
Frame wise MOTP != average MOTP of the sequence
:param input: MunkresNet Output Variable Matrix of shape [batch, h, w]
:param D: distance matrix before inputting to MunkresNet of shape [batch, h, w]
:return: [sum of distance, matched_objects, approximation of mean metric MOTP for THIS FRAME]
"""
distance = D*rowsoftmaxed
sum_distance = torch.sum(distance.view(1, -1), dim=1)
# +eps preventing zero division
matched_objects = torch.sum(rowsoftmaxed.view(1, -1), dim=1) + 1e-8
return [sum_distance, matched_objects]