result.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # Copyright (c) 2024 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. import io
  15. from typing import Any
  16. import matplotlib.pyplot as plt
  17. from PIL import Image
  18. from ...common.result import BaseTSResult
  19. def visualize(predicted_label, input_ts, target_cols):
  20. """
  21. Visualize time series data and its prediction results.
  22. Parameters:
  23. - input_ts: A DataFrame containing the input_ts.
  24. - predicted_label: A list of predicted class labels.
  25. Returns:
  26. - image: An image object containing the visualization result.
  27. """
  28. # 设置图形大小
  29. plt.figure(figsize=(12, 6))
  30. input_ts.columns
  31. input_ts.index = input_ts.index.astype(str)
  32. length = len(input_ts)
  33. value = predicted_label.loc[0, "classid"]
  34. plt.plot(
  35. input_ts.index,
  36. input_ts[target_cols[0]],
  37. label=f"Predicted classid: {value}",
  38. color="blue",
  39. )
  40. # 设置图形标题和标签
  41. plt.title("Time Series input_ts with Predicted Labels")
  42. plt.xlabel("Time")
  43. plt.ylabel("Value")
  44. plt.legend()
  45. plt.grid(True)
  46. plt.xticks(ticks=range(0, length, 10))
  47. plt.xticks(rotation=45)
  48. # 保存图像到内存
  49. buf = io.BytesIO()
  50. plt.savefig(buf, bbox_inches="tight")
  51. buf.seek(0)
  52. plt.close()
  53. image = Image.open(buf)
  54. return image
  55. class TSClsResult(BaseTSResult):
  56. """A class representing the result of a time series classification task."""
  57. def _to_img(self) -> Image.Image:
  58. """apply"""
  59. classification = self["classification"]
  60. ts_input = self["input_ts_data"]
  61. return {"res": visualize(classification, ts_input, self["target_cols"])}
  62. def _to_csv(self) -> Any:
  63. """
  64. Converts the classification results to a CSV format.
  65. Returns:
  66. Any: The classification data formatted for CSV output, typically a DataFrame or similar structure.
  67. """
  68. return {"res": self["classification"]}