ts.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. from pathlib import Path
  15. import numpy as np
  16. import pandas as pd
  17. from ..utils.io import TSWriter
  18. from .base import BaseResult
  19. class TSFcResult(BaseResult):
  20. def __init__(self, data):
  21. super().__init__(data)
  22. self._writer = TSWriter(backend="pandas")
  23. def save_to_csv(self, save_path):
  24. """write ts"""
  25. if not save_path.endswith(".csv"):
  26. save_path = Path(save_path) / f"{Path(self['ts_path']).stem}.csv"
  27. self._writer.write(save_path, self["forecast"])
  28. class TSClsResult(BaseResult):
  29. def __init__(self, data):
  30. super().__init__(
  31. {"ts_path": data["ts_path"], "classification": self.process_data(data)}
  32. )
  33. self._writer = TSWriter(backend="pandas")
  34. def process_data(self, data):
  35. """apply"""
  36. pred_ts = data["forecast"][0]
  37. pred_ts -= np.max(pred_ts, axis=-1, keepdims=True)
  38. pred_ts = np.exp(pred_ts) / np.sum(np.exp(pred_ts), axis=-1, keepdims=True)
  39. classid = np.argmax(pred_ts, axis=-1)
  40. pred_score = pred_ts[classid]
  41. result = {"classid": [classid], "score": [pred_score]}
  42. result = pd.DataFrame.from_dict(result)
  43. result.index.name = "sample"
  44. return result
  45. def save_to_csv(self, save_path):
  46. """write ts"""
  47. if not save_path.endswith(".csv"):
  48. save_path = Path(save_path) / f"{Path(self['ts_path']).stem}.csv"
  49. self._writer.write(save_path, self["classification"])