transforms.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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. import os
  15. import numpy as np
  16. import pandas as pd
  17. from ....utils import logging
  18. from ...base import BaseTransform
  19. from ...base.predictor.io.writers import TSWriter
  20. from .keys import TSFCKeys as K
  21. __all__ = ["SaveTSClsResults"]
  22. class SaveTSClsResults(BaseTransform):
  23. """SaveSegResults"""
  24. def __init__(self, save_dir):
  25. super().__init__()
  26. self.save_dir = save_dir
  27. self._writer = TSWriter(backend="pandas")
  28. def apply(self, data):
  29. """apply"""
  30. pred_ts = data[K.PRED]
  31. pred_ts -= np.max(pred_ts, axis=-1, keepdims=True)
  32. pred_ts = np.exp(pred_ts) / np.sum(np.exp(pred_ts), axis=-1, keepdims=True)
  33. classid = np.argmax(pred_ts, axis=-1)
  34. pred_score = pred_ts[classid]
  35. result = {"classid": [classid], "score": [pred_score]}
  36. result = pd.DataFrame.from_dict(result)
  37. result.index.name = "sample"
  38. file_name = os.path.basename(data[K.TS_PATH])
  39. ts_save_path = os.path.join(self.save_dir, file_name)
  40. self._write_ts(ts_save_path, result)
  41. return data
  42. @classmethod
  43. def get_input_keys(cls):
  44. """get input keys"""
  45. return [K.PRED]
  46. @classmethod
  47. def get_output_keys(cls):
  48. """get output keys"""
  49. return []
  50. def _write_ts(self, path, ts):
  51. """write ts"""
  52. if os.path.exists(path):
  53. logging.warning(f"{path} already exists. Overwriting it.")
  54. self._writer.write(path, ts)
  55. @staticmethod
  56. def _add_suffix(path, suffix):
  57. """add suffix"""
  58. stem, ext = os.path.splitext(path)
  59. return stem + suffix + ext
  60. @staticmethod
  61. def _replace_ext(path, new_ext):
  62. """replace ext"""
  63. stem, _ = os.path.splitext(path)
  64. return stem + new_ext