Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| Created on 2024-07-24 22:03:58 Wednesday | |
| @author: Nikhil Kapila | |
| """ | |
| import torch | |
| import numpy as np | |
| import pandas as pd | |
| from utils.forecasting_utils import sliding_windows | |
| from sklearn.metrics import mean_absolute_percentage_error | |
| def model_predict_lookback(model, scaler, hourly_data, lookback): | |
| initial_window_X = hourly_data[-lookback:][hourly_data.columns[0]].values.reshape(1, lookback ,1) | |
| initial_window_scaled = scaler.transform(initial_window_X.reshape(-1,1)).reshape(-1, lookback, 1) | |
| initial_window = torch.tensor(initial_window_scaled, dtype=torch.float32) | |
| future_predictions=[] | |
| model.eval() | |
| current_window = initial_window | |
| for _ in range(lookback): | |
| with torch.no_grad(): | |
| next_pred = model(current_window) | |
| future_predictions.append(next_pred.item()) | |
| next_pred = next_pred.reshape(1, 1, 1) | |
| current_window = torch.cat((current_window[:, 1:, :], next_pred), dim=1) | |
| future_dates = pd.date_range(start=hourly_data.index[-1] + pd.Timedelta(hours=1), periods=lookback, freq='h') | |
| future_df = pd.DataFrame(future_predictions, index=future_dates, columns=['Predicted']) | |
| future_df_1 = scaler.inverse_transform(future_df) | |
| predicted = pd.DataFrame({'timestamp': pd.Index(future_df.index), 'Predicted': future_df_1.flatten()}) | |
| predicted.set_index('timestamp', inplace=True) | |
| return predicted | |
| def model_predict_full_input(model, scaler, hourly_data, lookback): | |
| X, y, timestamp = sliding_windows(hourly_data, lookback) | |
| X_scaled = scaler.transform(X.reshape(-1, 1)).reshape(-1, lookback, 1) | |
| X_tensor = torch.tensor(X_scaled, dtype=torch.float32) | |
| val_preds = [] | |
| with torch.no_grad(): | |
| output = model(X_tensor) | |
| val_preds.extend(output.view(-1).tolist()) | |
| val_preds = np.array(val_preds).reshape(-1, 1) | |
| predicted = scaler.inverse_transform(val_preds) | |
| return predicted, mean_absolute_percentage_error(y, predicted)*100 | |