softmax.cc 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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/ocr/ppocr/utils/ocr_utils.h"
  15. namespace ultra_infer {
  16. namespace vision {
  17. namespace ocr {
  18. static inline float FastExp(float x) {
  19. union {
  20. uint32_t i;
  21. float f;
  22. } v{};
  23. v.i = (1 << 23) * (1.4426950409 * x + 126.93490512f);
  24. return v.f;
  25. }
  26. std::vector<float> Softmax(std::vector<float> &src) {
  27. int length = src.size();
  28. std::vector<float> dst;
  29. dst.resize(length);
  30. const float alpha =
  31. static_cast<float>(*std::max_element(&src[0], &src[0 + length]));
  32. float denominator{0};
  33. for (int i = 0; i < length; ++i) {
  34. dst[i] = FastExp(src[i] - alpha);
  35. denominator += dst[i];
  36. }
  37. for (int i = 0; i < length; ++i) {
  38. dst[i] /= denominator;
  39. }
  40. return dst;
  41. }
  42. } // namespace ocr
  43. } // namespace vision
  44. } // namespace ultra_infer