CoolFace
Apppublic

sdikici/Prophet_Electricty_Load_Forecasting

sourceHugging Facemitupdated 2y agoView on Hugging Face
1likes
app.py211 linesDownload Raw Back to root
1# -*- coding: utf-8 -*-2"""Huggingface_Prototype.ipynb3 4Automatically generated by Colab.5 6Original file is located at7    https://colab.research.google.com/drive/1i--A21QuJPKdv-HM2kUrFSwj89Qfv4cb8"""9 10#! mkdir ~/.kaggle11#! cp kaggle.json ~/.kaggle/12#! chmod 600 ~/.kaggle/kaggle.json13 14#!kaggle datasets download -d sercandikici/merged-dataset-electricty-weather-for-modelling15#! unzip merged-dataset-electricty-weather-for-modelling.zip16 17#pip install gradio18 19'''20Use the files.upload() function to upload files from the local system.21'''22 23#from google.colab import files24#uploaded = files.upload()25 26'''27Read the CSV file "merged_data.csv" into a DataFrame df.28Drop the column 'is_holiday' from the DataFrame df using the drop() function with axis=1.29Save the modified DataFrame df to a new CSV file named "merged_data_huggingface.csv" using the to_csv() function with index=False.30Download the CSV file "merged_data_huggingface.csv" using the files.download() function from the google.colab module.31'''32 33#df = pd.read_csv("merged_data.csv")34#df.drop('is_holiday', axis=1, inplace=True)35#df.to_csv('merged_data_huggingface.csv', index=False)36#from google.colab import files37#files.download('merged_data_huggingface.csv')38 39from prophet import Prophet40import numpy as np41import pandas as pd42import matplotlib.pyplot as plt43import gradio as gr44 45def forecast_plot(forecast_days,test_days, days):46    '''47    Plot the forecasted values from forecast_days with a green line and label "Forecast".48    Plot the actual values from test_days with orange points and label "Actual".49    Set the x-axis label to "Date" and the y-axis label to "MGW".50    Set the title of the plot using f-string formatting, including the model number and the days horizon.51    Add a legend to the plot.52    Return the figure object.53    '''54 55    fig, ax = plt.subplots(figsize=(14, 4))56    ax.plot(forecast_days['ds'], forecast_days['yhat'], label='Forecast', color='green')57    ax.scatter(test_days['ds'], test_days['y'], label='Actual', color='orange')58    ax.set_xlabel('Date')59    ax.set_ylabel('MGW')60    plt.title(f'Prophet Forecast - Model 3 - {days} days horizon')61    plt.legend()62 63    return fig64 65def mean_absolute_percentage_error(y_true, y_pred):66    '''Calculate and return the Mean Absolute Percentage Error (MAPE) between actual values (y_true) and predicted values (y_pred).'''67    y_true, y_pred = np.array(y_true), np.array(y_pred)68    mape = np.mean(np.abs((y_true - y_pred) / y_true))69    return mape70 71def root_mean_squared_error(y_true, y_pred):72    '''Calculate and return the Root Mean Squared Error (RMSE) between actual values (y_true) and predicted values (y_pred).'''73    y_true, y_pred = np.array(y_true), np.array(y_pred)74    mse = np.mean((y_true - y_pred) ** 2)75    rmse = np.sqrt(mse)76    return rmse77 78def r_squared(y_true, y_pred):79    '''Calculate and return the coefficient of determination (R-squared) value showing the proportion of variance in the dependent variable predictable from the independent variable.'''80    y_true, y_pred = np.array(y_true), np.array(y_pred)81    mean_y_true = np.mean(y_true)82    ss_total = np.sum((y_true - mean_y_true) ** 2)83    ss_residual = np.sum((y_true - y_pred) ** 2)84    r2 = 1 - (ss_residual / ss_total)85    return r286 87def predict_and_evaluate(csv_file, days_to_predict,freq, country_name):88    '''89    The function predict_and_evaluate is designed to forecast electricity demand using the Prophet time series forecasting model and evaluate the forecast accuracy.90    91    Parameters:92    - csv_file: Path to the CSV file containing the historical electricity demand data with columns "ds" (datetime), "y" (target variable), and "temp" (temperature).93    - days_to_predict: Number of days into the future to make predictions for.94    - freq: Frequency of the time series data.95    - country_name: Name of the country code for which the forecast is being made.96    97    Steps:98    1. Read the CSV file into a DataFrame and parse the datetime column.99    2. Split the data into training and testing sets.100    3. Set default values for frequency, days to predict, and country name.101    4. Set parameters for the Prophet model including MCMC samples, changepoint prior scale, and seasonality prior scale.102    5. Fit the Prophet model on the training data, adding country holidays and temperature as regressors.103    6. Create a future DataFrame for prediction, setting regressors for both training and testing data.104    7. Predict future values using the fitted model and calculate forecast metrics including MAPE, RMSE, and R-squared.105    8. Plot the forecast using the forecast_plot function.106    9. Return the forecast metrics and the plot.107    '''108 109    df_model = pd.read_csv(csv_file)110    df_model.columns = ["ds", "y", "temp"]111    df_model['ds'] = pd.to_datetime(df_model['ds'])112 113    #Set parameters for the Prophet model114    split_from = 90 * 12115    train_data = df_model[:-split_from]116    test_data = df_model[-split_from:]117    freq = freq118    seasonality_prior_scale = 0.01119    changepoint_prior_scale = 0.05120    mcmc_samples = 50121    periods = days_to_predict * 12122    #Train and fit the Prophet model123 124    m = Prophet(mcmc_samples=mcmc_samples, changepoint_prior_scale=changepoint_prior_scale,125                seasonality_prior_scale=seasonality_prior_scale)126    m.add_country_holidays(country_name=country_name)127    m.add_regressor("temp", mode="additive")128    m.fit(train_data)129    #Create a future DataFrame for prediction, setting regressors for both training and testing data130 131    future = m.make_future_dataframe(periods=periods, freq=freq)132    train_idx = future["ds"].isin(train_data.ds)133    test_idx = ~train_idx134 135    reg = ["temp"]136    for r in reg:137        future.loc[train_idx, r] = train_data[r].to_list()138    for r in reg:139        future.loc[test_idx, r] = test_data.iloc[:periods][r].to_list()140 141    forecast = m.predict(future)142    forecast_days = forecast[forecast["ds"] >= test_data["ds"].iloc[0]]143    test_days = test_data[(test_data["ds"] >= test_data["ds"].iloc[0]) & (144                test_data["ds"] <= forecast_days["ds"].iloc[-1])]145    #Plot the forecast using the forecast_plot function146 147    plot = forecast_plot(forecast_days, test_days, days_to_predict)148    #Predict future values using the fitted model and calculate forecast metrics149 150    mape = mean_absolute_percentage_error(test_days["y"], forecast_days["yhat"])151    rmse = root_mean_squared_error(test_days["y"], forecast_days["yhat"])152    rsqr = r_squared(test_days["y"], forecast_days["yhat"])153 154    metrics = {155        "MAPE": round(mape,3),156        "RMSE": round(rmse,1),157        "R-squared": round(rsqr,3)158    }159 160    return metrics,plot161 162csv_name = "merged_data_huggingface.csv"163#df_merged['settlement_date'] = pd.to_datetime(df_merged['settlement_date'])164#df_model = df_merged[["tsd", "settlement_date", "temp"]]165#df_model.columns = ["y", "ds", "temp"]166 167days_to_predict = 15  # Set the default value for days to predict168country_name = "UK" # Set the default value for country to predict169freq = "2H" # Set the default value for country to predict170 171predict_and_evaluate(csv_name, days_to_predict, freq, country_name)172 173 174''' 175This Gradio interface uses the `predict_and_evaluate` function to forecast electricity demand and evaluate the forecast accuracy. 176Users can upload a CSV file containing historical electricity demand data, specify the number of days to predict, 177and provide the data frequency and country code for holidays.178 179The interface displays evaluation metrics (MAPE, RMSE, R-squared) and a plot comparing forecasted values against actual values.180 181Example usage: 182- Upload the file "merged_data_huggingface.csv"183- Set "Days to Predict" to 30184- Enter "2H" for data frequency185- Enter "UK" for the country code186'''187 188 189iface = gr.Interface(190    fn=predict_and_evaluate,191    inputs=[192        gr.File(label="CSV File"),193        gr.Slider(1, 90, value=30, step=1, label="Days to Predict"),194        gr.Textbox(label="Data Frequency", placeholder="Enter frequency (e.g., 2H for 2 hourly)"),195        gr.Textbox(label="Country Code", placeholder="Enter country code (e.g., UK)")196    ],197    outputs=[198        gr.Textbox(label=" Evaluation Metrics"),199        "plot"200 201    ],202    title="Prophet Electricty Load Forecasting Model",203    description="Upload a CSV file of time series data to generate electricty demand forecasts using Prophet. Update country code(eg UK or DE) for holidays and data frequency",204 205 206    examples=[207        ["merged_data_huggingface.csv", 30, "2H", "UK"]208        ]209)210 211iface.launch()