- Approaches for model selection
- Cross validation
- Quantifying forecast performance
9 May 2023
Several candidate models might be built based on
Models can be evaluated by their ability to explain data
We can illustrate with an example to the harborSealWA
dataset in MARSS
\(y_{t} = b_{0}+b_{1}*t+e_{t}\)
## ## Call: ## lm(formula = SJI ~ Year, data = harborSealWA) ## ## Residuals: ## Min 1Q Median 3Q Max ## -0.46099 -0.08022 0.06576 0.13286 0.21464 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) -1.392e+02 1.601e+01 -8.697 1.85e-07 *** ## Year 7.397e-02 8.043e-03 9.197 8.69e-08 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 0.1916 on 16 degrees of freedom ## (4 observations deleted due to missingness) ## Multiple R-squared: 0.8409, Adjusted R-squared: 0.831 ## F-statistic: 84.58 on 1 and 16 DF, p-value: 8.693e-08
Our regression model had a pretty good SS
\[SS=\sum _{ i=1 }^{ n }{ { \left( y_{ i }-E[{ y }_{ i }] \right) }^{ 2 } } \]
Lots of metrics have been developed to overcome this issue and penalize complex models
Occam’s razor: “the law of briefness”
Principle of parsimony: choose the simplest possible model that explains the data pretty well
https://www.ncbi.nlm.nih.gov/books/NBK543534/figure/ch8.Fig3/
Akaike’s Information Criterion (AIC, Akaike 1973)
Attempts to balance the goodness of fit of the model against the number of parameters
Based on deviance = minus twice negative log likelihood
Deviance = \[-2\cdot ln\left( L(\underline { \theta } |\underline { y } ) \right)\]
Why the large focus on AIC?
Heavily used in ecology (Burnham and Anderson 2002)[https://www.springer.com/gp/book/9780387953649]
Also the default in many stepwise model selection procedures in R
Many base functions in R support the extraction of AIC
y = cumsum(rnorm(20)) AIC(lm(y~1)) AIC(glm(y~1)) AIC(mgcv::gam(y~1)) AIC(glmmTMB::glmmTMB(y~1)) AIC(lme4::lmer(y~1)) AIC(stats::arima(y)) AIC(forecast::Arima(y)) AIC(MARSS:MARSS(y))
Many *IC approaches to model selection also rely on deviance. Where they differ is how they structure the penalty term.
For AIC, the penalty is 2 * number of parameters (\(k\)),
\[AIC = -2\cdot ln\left( L(\underline { \theta } |\underline { y } ) \right) + 2k\]
Small sample AIC
\[AICc=AIC+\frac { 2k(k+1) }{ n-k-1 }\]
AIC aims to find the best model to predict data generated from the same process that generated your observations
Downside: AIC has a tendency to overpenalize, especially for more complex models
Alternative: Schwarz/Bayesian Information Criterion (SIC/BIC)
BIC is measure of explanatory power (rather than balancing explanation / prediction)
\[BIC = -2\cdot ln\left( L(\underline { \theta } |\underline { y } ) \right) + k\cdot ln(n)\]
Philosophical differences between AIC / BIC
Smallest AIC similar to minimizing one-step ahead forecasts using MSE Rob Hyndman’s blog
AIC approximates LOOCV Stone (1977)
BIC approximates k-fold cross validation Shao (1997)
The big difference between the Bayesian and maximum likelihood approaches are that
Many of the ML methods discussed were designed for models with only fixed effects.
Again, lots of options that have evolved quickly over the last several decades
Recent focus in ecology & fisheries on prediction
Jackknife
Bootstrap
Cross-validation (k-fold)
Data split: test/training sets (e.g. holdout last 5 data pts)
Bootstrap or jackknife approaches are useful
generally used in the context of time series models to generate new or pseudo-datasets
posterior predictive checks in Bayesian models generate new data from posterior draws
state space models: use estimated deviations / errors to simulate, estimate CIs
Examples
MARSS::MARSSboot() MARSS::MARSSinnovationsboot() forecast::bld.mbb.bootstrap() forecast::forecast(..., bootstrap=TRUE)
As an example, we’ll use a time series of body temperature from the beavers
dataset
data(beavers) beaver = dplyr::filter(beaver2, time>200)
set.seed(123) K = 5 beaver$part = sample(1:K, size=nrow(beaver), replace=T) beaver$pred = 0 beaver$pred_se = 0 for(k in 1:K) { y = beaver$temp y[which(beaver$part==k)] = NA mod = MARSS(y, model=list("B"="unequal")) beaver$pred[beaver$part==k] = mod$states[1,which(beaver$part==k)] beaver$pred_se[beaver$part==k] = mod$states.se[1,which(beaver$part==k)] }
How large should K be?
Bias/variance tradeoff:
Low K: low variance, larger bias, quicker to run. ML approaches recommend 5-10
High K (LOOCV): low bias, high variance, computationally expensive
To remove effect of random sampling / partitioning, repeat K-fold cross validation and average predictions for a given data point
caret() package in R does this for some classes of models
train_control = caret::trainControl(method="repeatedcv", number=5, repeats=20)
What about for time series data?
Leave Time Out Cross Validation = leave each year out in turn
Predict using historical and future data
Re-analyze the beaver data using LTOCV
Leave Future Out Cross Validation: only evaluate models on future data
Apply MARSS model to beaver dataset
Assign partitions in order, 1:5
beaver$part = ceiling(5*seq(1,nrow(beaver)) / (nrow(beaver)))
LOOIC (Leave-one out cross validation) + preferred over alternatives
WAIC (widely applicable information criterion)
loo::loo()
Additional reading: https://cran.r-project.org/web/packages/loo/vignettes/loo2-example.html
Why do we need to use anything BUT loo::loo()
?
LOOIC is an approximation (based on importance sampling) that can be unstable for flexible (read: state space) models
Diagnostic: Pareto-k diagnostic, 1 value per point.
“measure of each observation’s influence on the posterior of the model”
Often need to write code ourselves
\[log[p(y^*)]=log[\int p(y^*|\theta)p(\theta)d\theta]\]
Useful for calculating predictive accuracy for out of sample point (LTOCV, LFOCV)
Should act similar to AIC when posterior ~ MVN (more here)
plot(f1)
One of the most widelty used metrics is mean square error (MSE)
\[MSE=E\left[ { e }_{ t }^{ 2 } \right] =E\left[ { \left( { x }_{ t }-{ \hat { x } }_{ t } \right) }^{ 2 } \right]\]
Like with model selection, the bias-variance tradeoff is important
MSE can be rewritten as
\[MSE=Var\left( { \hat { x } }_{ t } \right) +Bias{ \left( { x }_{ t },{ \hat { x } }_{ t } \right) }^{ 2 }\] * Smaller MSE = lower bias + variance
MSE and all forecast metrics can be calculated for
\[MSE={ \frac { \sum _{ t=1 }^{ n }{ { \left( { x }_{ t }-{ \hat { x } }_{ t } \right) }^{ 2 } } }{ n } }\]
Root mean square error, RMSE (quadratic score)
Mean absolute error, MAE (linear score) \[E\left[ \left| { x }_{ t }-{ \hat { x } }_{ t } \right| \right]\]
Median absolute error, MdAE
\[median\left[ \left| { x }_{ t }-{ \hat { x } }_{ t } \right| \right]\]
Better when applying statistics of model(s) to multiple datasets MSE or RMSE will be driven by time series that is larger in magnitude
Percent Error:
\[{ p }_{ t }=\frac { { e }_{ t }\cdot 100 }{ { Y }_{ t } }\]
Mean Absolute Percent Error (MAPE):
\[MAPE\quad =\quad E\left[ \left| { p }_{ t } \right| \right]\] Root Mean Square Percent Error (RMSPE):
\[RMSPE\quad =\quad \sqrt { E\left[ { p }_{ t }^{ 2 } \right] }\]
\[{ p }_{ t }=\frac { { e }_{ t }\cdot 100 }{ { Y }_{ t } }\]
What happens when Y = 0?
Distribution of percent errors tends to be highly skewed / long tails
MAPE tends to put higher penalty on positive errors
See Hyndman & Koehler (2006)
Define scaled error as
\[{ q }_{ t }=\frac { { e }_{ t } }{ \frac { 1 }{ n-1 } \sum _{ i=2 }^{ n }{ \left( { Y }_{ i }-{ Y }_{ i-1 } \right) } }\]
Absolute scaled error (ASE)
\[ASE=\left| { q }_{ t } \right|\] Mean absolute scaled error (MASE)
\[MASE=E\left[ \left| { q }_{ t } \right| \right]\]
All values are relative to the naïve random walk model
Values < 1 indicate better performance than RW model
Values > 1 indicate worse performance than RW model
n = length(airmiles) air.model = auto.arima(log(airmiles[1:(n-3)]))
air.forecast = forecast(air.model, h = 3) plot(air.forecast)
Evaluate RMSE / MASE statistics for 3 holdouts
accuracy(air.forecast, log(airmiles[(n-2):n]), test = 3)
## ME RMSE MAE MPE MAPE MASE ## Test set -0.4183656 0.4183656 0.4183656 -4.051598 4.051598 2.010664
Evaluate RMSE / MASE statistics for only last holdout
accuracy(air.forecast, log(airmiles[(n-2):n]), test = 1)
## ME RMSE MAE MPE MAPE MASE ## Test set -0.1987598 0.1987598 0.1987598 -1.960106 1.960106 0.955239
Raw statistics (e.g. MSE, RMSE) shouldn’t be applied for data of different scale
Percent error metrics (e.g. MAPE) may be skewed & undefined for real zeroes
Scaled error metrics (ASE, MASE) have been shown to be more robust meta-analyses of many datasets + Hyndman & Koehler (2006)
Metrics (RMSE, etc.) evaluate point estimates of predictions vs. observations
But what if we also care about how uncertain our predictions / forecasts are?
limited to applications of parametric methods
Scoring rules
R packages: scoring, scoringRules