Choosing ER Time Series Models (part 2): How to Fairly Compare ARIMA and XGBoost?
From the publisher’s feed, collected in the ZeroLabs newsroom.
An emergency department forecasting examplePhoto by Raquel Martínez on UnsplashHow does a hospital decision maker know which model to trust for forecasting? In part 1 of my series, I explored this question with an emergency department example aimed at predicting patient arrivals by first understanding the building blocks of ARIMA, a traditional time series technique for forecasting. Here I compare ARIMA with a machine learning algorithm, XGBoost, which can capture non-linear patterns, handle missing values well and has the flexibility to add features to improve predictive accuracy. Let’s look at how to run a fair comparison between the two models.Feature engineeringXGBoost although powerful, does not intuitively understand the temporal dependence of time series data like ARIMA and would need a few tweaks. That is where feature engineering comes in.Lag featureFirst, a lag feature is added to the XGBoost model to capture the autoregressive component of the ARIMA model, which helps predict future values based on past data.I add both a lag of 1 and lag of 7 as features since there is a weekly seasonal trend to the ER time series based on findings in part 1, which identified weekly fluctuations in patient arrivals.Rolling mean featureAnother feature I added was a 7-day moving average, which smooths short-term fluctuations in the data. ARIMA already takes this into account.Other calendar featuresFinally, I added calendar features (day of week, month, holidays, week of year, etc) to both the XGBoost and ARIMA models as these were found to improve predictive accuracy based on past studies of ER forecasting of patient arrivals.# find holidaysyears can_holidays unique( unlist( lapply(years, function(y) as.Date(timeDate::holidayTSX(y))) ) ))pre_holidays post_holidays # feature engineeringtsed_features % arrange(date) %>% mutate( # calendar features dayofweek = wday(date), quarter = quarter(date), month = month(date), year = year(date), dayofyear = yday(date), dayofmonth = mday(date), weekofyear = isoweek(date), # holiday features holiday = ifelse(date %in% can_holidays, 1, 0), pre_holiday = ifelse(date %in% pre_holidays, 1, 0), post_holiday = ifelse(date %in% post_holidays, 1, 0), # lag features lag_1 = lag(daily_count, 1), lag_7 = lag(daily_count, 7), # rolling average feature roll7 = rollmean( daily_count, 7, fill = NA, align = "right" ) ) Train, test splitNext, I use the same 80/20 train, test split for both models. Instead of random splitting I used temporal splitting to preserve the forecasting logic and correlated nature of time series data.# create function to do train, test splitsplit_ts n train_end list( train = y[1:train_end], test = y[(train_end+1):n] )}# xgboosty_split train_idx test_idx X_train X_test y_train y_test dtrain xgb_model params = list(objective = "reg:squarederror"), data = dtrain, nrounds = 500, verbose = 1)# arimaX_train_arima X_test_arima arimax_model y_train, xreg = X_train_arima)Here is how the split looks graphically:Evaluation metricsThen I used three evaluation metrics to compare both models. These were chosen as they provide insights into different aspect of model performance:MAE (Mean Absolute Error) is intuitive and is simply the average of the absolute value of the difference between actual and predicted values.RMSE (Root Mean Square Error) penalizes large errors where outliers contribute disproportionately to the metric by squaring the difference between actual and predicted values before the average is taken.MAPE (Mean Absolute Percentage Error) provides relative accuracy.A lower value indicates better performance.# evaluation metricsmae mean(abs(actual - pred))}rmse sqrt(mean((actual - pred)^2))}mape idx mean( abs((actual[idx] - pred[idx]) / actual[idx]) ) * 100}# calculate metrics for xgboost and arimax hold out test set cat( "XGBoost Test RMSE:", rmse(y_test, pred_test), "MAE:", mae(y_test, pred_test), "MAPE:", mape(y_test, pred_test), "\n")cat( "ARIMAX Test RMSE:", rmse(y_test, pred_test_arima), "MAE:", mae(y_test, pred_test_arima), "MAPE:", mape(y_test, pred_test_arima), "\n")After training both models on the same training set, I evaluated their forecasts on the hold-out test set. The results are as follows:XGBoost Test RMSE: 11.54509 MAE: 9.102592 MAPE: 7.992696 ARIMAX Test RMSE: 12.90757 MAE: 10.11242 MAPE: 8.927907 XGBoost performs marginally better than ARIMA on all metrics. MAE shows that on average, predictions differ from the actual values by 9 patients for XGBoost, compared to 10 patients for ARIMA. RMSE shows that due to some outliers present in the data on average, predictions are off by 12 patients for XGBoost and 13 patients for ARIMA. Lastly, MAPE shows that forecasts on average are off 8% from the actual value for XGBoost and 9% for ARIMA. Note, these metrics penalize equally for under and over forecasting.Reflections on approachWhat surprised me? An advanced forecasting technique like XGBoost only added a marginal predictive benefit compared to ARIMA.What would I do differently? Use a train, validation and test split for cross validation and hyperparameter tuning to better calibrate XGBoost to mimic the auto.arima() function used to select the optimal ARIMA model.Bottom line, adding complexity to model building for time series forecasting can add better predictive accuracy. In this case, the difference is 1 patient per day between models. Does this small difference translate to a tangible, value-add for a hospital decision maker looking at which model to deploy? How do operational considerations come into play? Stay tuned for the final part of the series.Technical stackR statistical software (code on my Github)Key R packages: timeDate, tseries, forecast, xgboostFurther readingVollmer MAC, Glampson B, Mellan T, Mishra S, Mercuri L, Costello C, Klaber R, Cooke G, Flaxman S, Bhatt S. A unified machine learning approach to time series forecasting applied to demand at emergency departments. BMC Emerg Med. 2021 Jan 18;21(1):9.Mulla R. Time Series Forecasting with Machine Learning [Internet]. Kaggle; 2022 [cited 2026 Mar 13].Wu Y. Forecasting with ARMA, ARIMA, and SARIMA in R [Internet]. Kaggle; 2025 [cited 2026 Mar 13].Questions or feedback? I write to learn. If you tried something similar or have a suggestion on what I can look into next, please share.Choosing ER Time Series Models (part 2): How to Fairly Compare ARIMA and XGBoost? was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.