Skip to content

Instantly share code, notes, and snippets.

@kperry2215
Created January 4, 2020 23:41
Show Gist options
  • Save kperry2215/61c9b18438f4701586ffdd55aa84cc32 to your computer and use it in GitHub Desktop.
Save kperry2215/61c9b18438f4701586ffdd55aa84cc32 to your computer and use it in GitHub Desktop.
def fit_predictions(model_fit, steps_out_to_predict, actual_values):
"""
This function predicts the SARIMA model out a certain designated number of steps,
and compares the predictions to the actual values. The root mean squared error and
the mean absolute error are calculated, comparing the predicted and actual values.
The function returns the predicted values and their respective confidence intervals.
Args:
model_fit: SARIMA model.
steps_out_to_predict: Int. Number of steps out to predict the time series.
actual_values: Series of actual time series values.
Outputs:
mean_predicted_values: Series of predicted time series values.
confidence_interval_predicted_values: Dataframe, containing upper and lower thresholds of the
confidence interval
"""
predicted_values = model_fit.get_forecast(steps=steps_out_to_predict)
mean_predicted_values = predicted_values.predicted_mean
confidence_interval_predicted_values = predicted_values.conf_int()
#Compare the actual to the predicted values using RMSE and MAE metrics
rmse, mae = quantify_rmse_mae(mean_predicted_values, actual_values)
print("Root mean squared error: ", str(rmse))
print("Mean absolute error: ", str(mae))
return mean_predicted_values, confidence_interval_predicted_values
def quantify_rmse_mae(predicted_values, actual_values):
"""
This function calculates the root mean squared error and mean absolute error for
the predicted values, when compared to the actual values. These helps help us to
gauge model performance.
Args:
predicted_values: Series of predicted time series values.
actual_values: Corresponding series of actual time series values.
Outputs:
rmse: Float. Root mean squared error.
mae: Float. Mean absolute error.
"""
#calcuate the mean squared error of the model
rmse = math.sqrt(mean_squared_error(actual_values, predicted_values))
#Calculate the mean absolute error of the model
mae = mean_absolute_error(actual_values, predicted_values)
#Return the MSE and MAE for the model
return rmse, mae
### EXECUTE IN THE MAIN FUNCTION ###
#Run the data on the test set to gauge model performance
mean_predicted_values, confidence_interval_predicted_values = fit_predictions(best_model,
len(test_set),
test_set)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment