cosine_similarity.cc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  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. #include "ultra_infer/vision/utils/utils.h"
  15. namespace ultra_infer {
  16. namespace vision {
  17. namespace utils {
  18. float CosineSimilarity(const std::vector<float> &a, const std::vector<float> &b,
  19. bool normalized) {
  20. FDASSERT((a.size() == b.size()) && (a.size() != 0),
  21. "The size of a and b must be equal and >= 1.");
  22. size_t num_val = a.size();
  23. if (normalized) {
  24. float mul_a = 0.f, mul_b = 0.f, mul_ab = 0.f;
  25. for (size_t i = 0; i < num_val; ++i) {
  26. mul_a += (a[i] * a[i]);
  27. mul_b += (b[i] * b[i]);
  28. mul_ab += (a[i] * b[i]);
  29. }
  30. return (mul_ab / (std::sqrt(mul_a) * std::sqrt(mul_b)));
  31. }
  32. auto norm_a = L2Normalize(a);
  33. auto norm_b = L2Normalize(b);
  34. float mul_a = 0.f, mul_b = 0.f, mul_ab = 0.f;
  35. for (size_t i = 0; i < num_val; ++i) {
  36. mul_a += (norm_a[i] * norm_a[i]);
  37. mul_b += (norm_b[i] * norm_b[i]);
  38. mul_ab += (norm_a[i] * norm_b[i]);
  39. }
  40. return (mul_ab / (std::sqrt(mul_a) * std::sqrt(mul_b)));
  41. }
  42. } // namespace utils
  43. } // namespace vision
  44. } // namespace ultra_infer