1
0

algorithms.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # Copyright 2023 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import pickle
  12. import random
  13. from datetime import datetime, timedelta
  14. from typing import Any, Dict
  15. import pandas as pd
  16. n_predictions = 14
  17. def forecast(model, date: datetime):
  18. dates = [date + timedelta(days=i) for i in range(n_predictions)]
  19. forecasts = [f + random.uniform(0, 2) for f in model.forecast(len(dates))]
  20. days = [str(dt.date()) for dt in dates]
  21. res = {"Date": days, "Forecast": forecasts}
  22. return pd.DataFrame.from_dict(res)
  23. def evaluate(cleaned: pd.DataFrame, forecasts: pd.DataFrame, date: datetime) -> Dict[str, Any]:
  24. cleaned = cleaned[cleaned["Date"].isin(forecasts["Date"].tolist())]
  25. forecasts_as_series = pd.Series(forecasts["Forecast"].tolist(), name="Forecast")
  26. res = pd.concat([cleaned.reset_index(), forecasts_as_series], axis=1)
  27. res["Delta"] = abs(res["Forecast"] - res["Value"])
  28. return {
  29. "Date": date,
  30. "Dataframe": res,
  31. "Mean_absolute_error": res["Delta"].mean(),
  32. "Relative_error": (res["Delta"].mean() * 100) / res["Value"].mean(),
  33. }
  34. if __name__ == "__main__":
  35. model = pickle.load(open("../my_model.p", "rb"))
  36. day = datetime(2020, 1, 25)
  37. forecasts = forecast(model, day)
  38. historical_temperature = pd.read_csv("../historical_temperature.csv")
  39. evaluation = evaluate(historical_temperature, forecasts, day)
  40. print(evaluation["Dataframe"])
  41. print()
  42. print(f'Mean absolute error : {evaluation["Mean_absolute_error"]}')
  43. print(f'Relative error in %: {evaluation["Relative_error"]}')