You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

distance.py 2.2 kB

4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright 2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Numpy version of euclidean distance, etc."""
  16. import numpy as np
  17. from utils.metric import cmc, mean_ap
  18. def normalize(nparray, order=2, axis=0):
  19. """Normalize a N-D numpy array along the specified axis."""
  20. norm = np.linalg.norm(nparray, ord=order, axis=axis, keepdims=True)
  21. return nparray / (norm + np.finfo(np.float32).eps)
  22. def compute_dist(array1, array2, dis_type='euclidean'):
  23. """Compute the euclidean or cosine distance of all pairs.
  24. Args:
  25. array1: numpy array with shape [m1, n]
  26. array2: numpy array with shape [m2, n]
  27. type:
  28. one of ['cosine', 'euclidean']
  29. Returns:
  30. numpy array with shape [m1, m2]
  31. """
  32. assert dis_type in ['cosine', 'euclidean']
  33. if dis_type == 'cosine':
  34. array1 = normalize(array1, axis=1)
  35. array2 = normalize(array2, axis=1)
  36. dist = np.matmul(array1, array2.T)
  37. return -1*dist
  38. # shape [m1, 1]
  39. square1 = np.sum(np.square(array1), axis=1)[..., np.newaxis]
  40. # shape [1, m2]
  41. square2 = np.sum(np.square(array2), axis=1)[np.newaxis, ...]
  42. squared_dist = - 2 * np.matmul(array1, array2.T) + square1 + square2
  43. squared_dist[squared_dist < 0] = 0
  44. dist = np.sqrt(squared_dist)
  45. return dist
  46. def compute_score(dist_mat, query_ids, gallery_ids):
  47. mAP = mean_ap(distmat=dist_mat, query_ids=query_ids, gallery_ids=gallery_ids)
  48. cmc_scores, _ = cmc(distmat=dist_mat, query_ids=query_ids, gallery_ids=gallery_ids, topk=10)
  49. return mAP, cmc_scores