result.py 2.4 KB

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