Sure, here is a Python code snippet using Facebook's Prophet library to forecast time-series data. This class includes methods for training, plotting, and calculating mean absolute percentage error. It also allows for hyperparameters to be adjusted during instantiation.
from fbprophet import Prophet
from sklearn.metrics import mean_absolute_percentage_error
import matplotlib.pyplot as plt
class ProphetForecast:
def __init__(self, data, test_size, hyperparameters={}):
self.data = data
self.test_size = test_size
self.model = Prophet(**hyperparameters)
def train(self):
train_data = self.data[:-self.test_size]
self.model.fit(train_data)
def forecast(self):
future = self.model.make_future_dataframe(periods=self.test_size)
self.forecast_data = self.model.predict(future)
def plot(self):
fig1 = self.model.plot(self.forecast_data)
fig2 = self.model.plot_components(self.forecast_data)
plt.show()
def calculate_error(self):
test_data = self.data[-self.test_size:]
y_true = test_data['y'].values
y_pred = self.forecast_data['yhat'][-self.test_size:].values
error = mean_absolute_percentage_error(y_true, y_pred)
print(f'MAPE: {error}')
return error
You can use this class as follows:
# Instantiate the class
prophet_forecast = ProphetForecast(data, test_size=100, hyperparameters={'daily_seasonality': True})
# Train the model
prophet_forecast.train()
# Forecast the data
prophet_forecast.forecast()
# Plot the forecast
prophet_forecast.plot()
# Calculate the error
prophet_forecast.calculate_error()
Please note that this is a basic class and it might not cover all your needs. For example, it assumes that your dataframe has columns ds and y as required by Prophet. You might need to adjust the code according to your requirements. Also, the error is calculated using mean absolute percentage error (MAPE) because it's a common metric for time series forecasting, but you might prefer a different metric.