l2_normalize.cc 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. std::vector<float> L2Normalize(const std::vector<float> &values) {
  19. size_t num_val = values.size();
  20. if (num_val == 0) {
  21. return {};
  22. }
  23. std::vector<float> norm;
  24. float l2_sum_val = 0.f;
  25. for (size_t i = 0; i < num_val; ++i) {
  26. l2_sum_val += (values[i] * values[i]);
  27. }
  28. float l2_sum_sqrt = std::sqrt(l2_sum_val);
  29. norm.resize(num_val);
  30. for (size_t i = 0; i < num_val; ++i) {
  31. norm[i] = values[i] / l2_sum_sqrt;
  32. }
  33. return norm;
  34. }
  35. } // namespace utils
  36. } // namespace vision
  37. } // namespace ultra_infer