utils_feature.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from collections import OrderedDict
  2. import numpy as np
  3. from .utils_dict import get_dict_first_item as _get_dict_first_item
  4. def convert_feature_dict_to_array(feature_dict):
  5. key_list = []
  6. one_feature = _get_dict_first_item(feature_dict)[1]
  7. feature_array = np.empty((len(feature_dict), len(one_feature)), one_feature.dtype)
  8. for k, (key, value) in enumerate(feature_dict.items()):
  9. key_list.append(key)
  10. feature_array[k] = value
  11. return key_list, feature_array
  12. def convert_feature_array_to_dict(key_list, feature_array):
  13. assert len(feature_array) == len(key_list)
  14. feature_dict = OrderedDict()
  15. for k, key in enumerate(key_list):
  16. feature_dict[key] = feature_array[k]
  17. return feature_dict
  18. def pairwise_distances(x, y, squared=True):
  19. """Compute pairwise (squared) Euclidean distances.
  20. References:
  21. [2016 CVPR] Deep Metric Learning via Lifted Structured Feature Embedding
  22. `euclidean_distances` from sklearn
  23. """
  24. assert isinstance(x, np.ndarray) and x.ndim == 2
  25. assert isinstance(y, np.ndarray) and y.ndim == 2
  26. assert x.shape[1] == y.shape[1]
  27. x_square = np.expand_dims(np.einsum('ij,ij->i', x, x), axis=1)
  28. if x is y:
  29. y_square = x_square.T
  30. else:
  31. y_square = np.expand_dims(np.einsum('ij,ij->i', y, y), axis=0)
  32. distances = np.dot(x, y.T)
  33. # use inplace operation to accelerate
  34. distances *= -2
  35. distances += x_square
  36. distances += y_square
  37. # result maybe less than 0 due to floating point rounding errors.
  38. np.maximum(distances, 0, distances)
  39. if x is y:
  40. # Ensure that distances between vectors and themselves are set to 0.0.
  41. # This may not be the case due to floating point rounding errors.
  42. distances.flat[::distances.shape[0] + 1] = 0.0
  43. if not squared:
  44. np.sqrt(distances, distances)
  45. return distances