45 lines
1.5 KiB
Python
Raw Normal View History

2020-05-21 23:58:35 +08:00
"""Numpy version of euclidean distance, etc.
Notice the input/output shape of methods, so that you can better understand
the meaning of these methods."""
import torch
import numpy as np
def normalize(nparray, order=2, axis=0):
"""Normalize a N-D numpy array along the specified axis."""
norm = np.linalg.norm(nparray, ord=order, axis=axis, keepdims=True)
return nparray / (norm + np.finfo(np.float32).eps)
2020-07-10 16:27:22 +08:00
def compute_dsr_dist(array1, array2, distmat, scores, topk=30):
2020-05-21 23:58:35 +08:00
""" Compute the sptial feature reconstruction of all pairs
array: [M, N, C] M: the number of query, N: the number of spatial feature, C: the dimension of each spatial feature
array2: [M, N, C] M: the number of gallery
:return:
numpy array with shape [m1, m2]
"""
2020-07-10 16:27:22 +08:00
2020-05-21 23:58:35 +08:00
dist = 100 * torch.ones(len(array1), len(array2))
dist = dist.cuda()
2020-07-10 16:27:22 +08:00
index = np.argsort(distmat, axis=1)
2020-05-21 23:58:35 +08:00
for i in range(0, len(array1)):
q = torch.FloatTensor(array1[i])
q = q.view(q.size(0), q.size(1))
q = q.cuda()
2020-07-10 16:27:22 +08:00
score = scores[i]
2020-06-29 16:41:58 +08:00
for j in range(topk):
2020-07-10 16:27:22 +08:00
g = array2[index[i, j]]
2020-05-21 23:58:35 +08:00
g = torch.FloatTensor(g)
g = g.view(g.size(0), g.size(1))
g = g.cuda()
2020-07-10 16:27:22 +08:00
sim = torch.matmul(q.t(), g)
min_value, min_index = (1 - sim).min(1)
dist[i, index[i, j]] = (min_value * score).sum()
2020-05-21 23:58:35 +08:00
dist = dist.cpu()
dist = dist.numpy()
2020-07-12 13:31:21 +08:00
dist = 0.98 * dist + 0.02 * distmat
2020-05-21 23:58:35 +08:00
return dist