pacman::p_load(
tidyverse, # ggplot, mutate(), cleaning...
tsibble, # as_tsibble()
fable, # model(...), forecast(), tidy(), glance()...
feasts, # ACF(), PACF()
ggtime, # autoplot() for tsibbles
rio, # import()
pander, # pander() markdown tables
patchwork # + and / for ggplots
)Log Transformations, Model Selection, and Bias Correction
Chapter 5: Lesson 2
Learning Outcomes
Apply logarithmic transformations to time series
- Explain when to use a log-transformation
- Explain how a logarithm turns a multiplicative model into an additive model
- Explain how a logarithm linearizes an exponential trend
- Fit a regression model with seasonal indicator variables to a log-transformed time series
Apply model selection criteria
- Explain why adding terms to a model always improves the in-sample fit
- State the general structure of an information criterion as a measure of fit plus a penalty for complexity
- Compare candidate models using AIC, AICc, and BIC
- Explain why information criteria should inform, not replace, judgment when choosing a model
- Identify when information criteria cannot be compared across models
Fit regression models with autocorrelated errors
- Use the correlogram and partial correlogram of the residuals to choose an \(AR(p)\) model for the errors
- Fit a regression model with \(AR(p)\) errors as a single model
- Compare OLS standard errors to those from a model with \(AR(p)\) errors
Forecast from a log-transformed model
- Forecast using the inverse transformation of a log-transformed model
- Explain why back-transforming the forecasted mean of the logarithm gives a biased forecast
- Explain that fable applies a bias adjustment to the forecasted mean automatically
- State the log-normal and empirical bias correction factors
Preparation
- Read Sections 5.7, 5.9-5.11
Learning Journal Exchange (10 min)
Review another student’s journal
What would you add to your learning journal after reading another student’s?
What would you recommend the other student add to their learning journal?
Sign the Learning Journal review sheet for your peer
Packages
Class Activity: Why Take the Logarithm? (10 min)
In this lesson, we will build one model from start to finish. Each section answers one question:
- Why take the logarithm? The log turns a multiplicative series into an additive one that a linear model can fit.
- What shape is the trend? We fit several candidate trends and compare them.
- Which candidate should we use? Information criteria help us weigh fit against complexity.
- Are the errors autocorrelated? If so, we add an \(AR(p)\) model for the errors.
- How do we forecast on the original scale? We undo the logarithm and account for the bias that introduces.
The Air Passenger Data
The textbook uses this data set in Section 5.7. It gives the monthly totals of international airline passengers (in thousands) from January 1949 to December 1960. The data come with R as a ts object called AirPassengers, so we convert them to a tsibble.
Show the code
air_ts <- as_tsibble(AirPassengers) |>
rename(date = index, passengers = value) |>
mutate(
t = row_number(), # t = 1 is January 1949
years_elapsed = t / 12, # years since Dec 1948 (not the calendar year)
month = factor(month.abb[month(date)], levels = month.abb) # January is the reference month
)Figure 1 shows the time series (left) and the natural logarithm of the time series (right).
Show the code
air_plot_raw <- air_ts |>
autoplot(.vars = passengers) +
labs(
x = "Month",
y = "Passengers (Thousands)",
title = "Airline Passengers"
) +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5))
air_plot_log <- air_ts |>
autoplot(.vars = log(passengers)) +
labs(
x = "Month",
y = "log(Passengers)",
title = "Logarithm of Airline Passengers"
) +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5))
air_plot_raw | air_plot_logLook at the left plot. The trend bends upward, and the seasonal swings get larger as the level of the series increases. In Chapter 3 Lesson 5, we called this multiplicative seasonality. A multiplicative model has the form
\[ x_t = m_t \cdot s_t \cdot z_t \]
The linear models from Chapter 5 Lesson 1 are additive. They add the trend, seasonal, and random components together. We cannot fit a multiplicative model directly with TSLM(). However, taking the logarithm of both sides turns the products into sums:
\[ \log(x_t) = \log(m_t) + \log(s_t) + \log(z_t) \]
The logarithm also straightens out an exponential trend. If \(m_t = e^{\alpha_0 + \alpha_1 t}\), then \(\log(m_t) = \alpha_0 + \alpha_1 t\), which is linear in the parameters.
Now look at the right plot. After taking the logarithm, the seasonal swings are roughly the same size throughout, and the trend looks close to a straight line. This is a series we can model with the tools from the last lesson. From here on, our response variable is \(\log(x_t)\), not \(x_t\).
Class Activity: Candidate Models for the Trend (10 min)
The log-transformed series looks linear, but our eyes are not a precise tool. A slight curve in the trend is easy to miss. Rather than assume a shape, we will fit a few reasonable candidate models and let the data help us choose among them. We will consider a linear, quadratic, and cubic trend.
The Model
All three candidates have the same structure as the models in Chapter 5 Lesson 1, but the response is \(\log(x_t)\):
\[ \log(x_t) = m_t + s_t + z_t \]
The seasonal component \(s_t\) uses indicator variables with January as the reference month, so each \(\Delta\beta_i\) is the difference between that month and January:
\[ s_t = \begin{cases} 0, & t = 1, 13, 25, \ldots ~~~~ ~~(January) \\ \Delta\beta_2, & t = 2, 14, 26, \ldots ~~~~ ~~(February) \\ \Delta\beta_3, & t = 3, 15, 27, \ldots ~~~~ ~~(March) \\ ~~~~⋮ & ~~~~~~~~~~~~⋮ \\ \Delta\beta_{12}, & t = 12, 24, 36, \ldots ~~~~ (December) \end{cases} \]
The candidates differ only in the trend, \(m_t\). Here \(u_t\) is the time elapsed in years since December 1948, stored in air_ts as years_elapsed. We look more closely at this choice, and at what the coefficients mean, after we choose a model.
| Candidate | Trend, \(m_t\) |
|---|---|
| Linear | \(\alpha_0 + \alpha_1 u_t\) |
| Quadratic | \(\alpha_0 + \alpha_1 u_t + \alpha_2 u_t^2\) |
| Cubic | \(\alpha_0 + \alpha_1 u_t + \alpha_2 u_t^2 + \alpha_3 u_t^3\) |
Fitting the Candidates
We fit all three candidates at once. Each model is fitted with ordinary least squares (OLS).
air_models <- air_ts |>
model(
linear = TSLM(log(passengers) ~ years_elapsed + month),
quadratic = TSLM(log(passengers) ~ years_elapsed + I(years_elapsed^2) + month),
cubic = TSLM(log(passengers) ~ years_elapsed + I(years_elapsed^2) + I(years_elapsed^3) + month)
)The tabs below give the estimated trend parameters for each candidate. The 11 monthly terms are left out to save space. Delete the filter() line to see them.
Show the code
air_models |>
select(linear) |>
tidy() |>
filter(!str_detect(term, "month")) |>
mutate(sig = p.value < 0.05)# A tibble: 2 × 7
.model term estimate std.error statistic p.value sig
<chr> <chr> <dbl> <dbl> <dbl> <dbl> <lgl>
1 linear (Intercept) 4.73 0.0189 250. 1.97e-177 TRUE
2 linear years_elapsed 0.121 0.00143 84.4 4.56e-116 TRUE
Show the code
air_models |>
select(quadratic) |>
tidy() |>
filter(!str_detect(term, "month")) |>
mutate(sig = p.value < 0.05)# A tibble: 3 × 7
.model term estimate std.error statistic p.value sig
<chr> <chr> <dbl> <dbl> <dbl> <dbl> <lgl>
1 quadratic (Intercept) 4.65 0.0179 260. 1.45e-178 TRUE
2 quadratic years_elapsed 0.158 0.00467 33.9 2.27e- 66 TRUE
3 quadratic I(years_elapsed^2) -0.00309 0.000374 -8.26 1.41e- 13 TRUE
The quadratic term is statistically significant, and its estimate is negative. On the log scale, the trend bends slightly downward. In other words, the growth rate of passengers slows a little over time.
Show the code
air_models |>
select(cubic) |>
tidy() |>
filter(!str_detect(term, "month")) |>
mutate(sig = p.value < 0.05)# A tibble: 4 × 7
.model term estimate std.error statistic p.value sig
<chr> <chr> <dbl> <dbl> <dbl> <dbl> <lgl>
1 cubic (Intercept) 4.66 0.0207 225. 3.15e-169 TRUE
2 cubic years_elapsed 0.150 0.0119 12.6 2.84e- 24 TRUE
3 cubic I(years_elapsed^2) -0.00142 0.00228 -0.621 5.35e- 1 FALSE
4 cubic I(years_elapsed^3) -0.0000924 0.000124 -0.744 4.58e- 1 FALSE
The cubic term is not statistically significant. Notice that the quadratic term is not significant in this model either, even though it was in the quadratic model. The terms \(u_t\), \(u_t^2\), and \(u_t^3\) rise together and are highly correlated, so the model struggles to separate their individual effects. This is one reason we compare whole models in the next section rather than relying only on individual p-values.
TSLM() estimates its parameters with ordinary least squares, exactly like lm(). As we saw in Chapter 5 Lesson 1, if the errors are autocorrelated, these standard errors and p-values are too small. We will check the residuals and account for any autocorrelation after we choose a trend.
Model Selection Information Criteria: Balancing Fit and Complexity (15 min)
We now have three candidate models. How do we choose?
Why We Need a Penalty
Adding terms to a regression model never makes the in-sample fit worse. The \(R^2\) value can only go up, and the residual sum of squares can only go down. If we chose models by \(R^2\) alone, we would always choose the most complicated model. But a model that follows the training data too closely (overfitting) often forecasts poorly, because some of what it learned was noise.
You may remember adjusted \(R^2\) from a regression course, which does include a penalty for extra terms. Its penalty is weak, though. Adjusted \(R^2\) goes up whenever a new term has a t-statistic larger than 1 in absolute value, so it still tends to keep terms that add little. It is also specific to regression. It does not exist for the models with autocorrelated errors that we fit later in this lesson. Information criteria solve both problems.
The idea behind information criteria is parsimony: when two models explain the data about equally well, we prefer the simpler one. Every information criterion has the same structure:
\[ \text{IC} = \underbrace{-2 \log(\mathcal{L})}_{\text{lack of fit}} + \underbrace{\text{penalty}(k)}_{\text{complexity}} \]
where \(\mathcal{L}\) is the likelihood of the data under the model (how probable the observed data are, given the fitted model) and \(k\) is the number of estimated parameters. Better fit makes the first term smaller. More parameters make the second term larger. Smaller values are better.
Three Common Criteria
AIC (Akaike Information Criterion)
\[ AIC = -2 \log(\mathcal{L}) + 2k \]
The AIC estimates how much information is lost when we use the model to represent the process that generated the data. It is designed to choose the model that will predict new data best, so it is well suited to forecasting.
AICc (Corrected AIC)
\[ AICc = AIC + \frac{2k(k+1)}{n - k - 1} \]
When the sample size \(n\) is small relative to \(k\), the AIC tends to choose models that are too complex. The AICc adds an extra penalty to correct for this. As \(n\) grows, the correction shrinks and the AICc approaches the AIC. Because time series are often short, the AICc is a good default.
BIC (Bayesian Information Criterion)
\[ BIC = -2 \log(\mathcal{L}) + k \ln(n) \]
The BIC penalizes each parameter by \(\ln(n)\) instead of 2. Since \(\ln(n) > 2\) whenever \(n > 7\), the BIC is stricter than the AIC and tends to choose simpler models. It is often preferred when the goal is to understand or explain a process rather than to forecast it.
Comparing the Candidates
Table 1 gives \(R^2\), adjusted \(R^2\), and the three information criteria for each candidate. The lowest value in each criterion column is in bold.
Show the code
air_ic <- air_models |>
glance() |>
select(.model, r_squared, adj_r_squared, AIC, AICc, BIC)
air_ic| Model | R-squared | Adj. R-squared | AIC | AICc | BIC |
|---|---|---|---|---|---|
| linear | 0.9835 | 0.9820 | -799.2 | -796 | -757.7 |
| quadratic | 0.9892 | 0.9881 | **-858.1** | **-854.3** | **-813.5** |
| cubic | 0.9892 | 0.9880 | -856.7 | -852.4 | -809.2 |
Notice the following:
- \(R^2\) increases with every term we add, as expected. It cannot tell us when to stop. Adjusted \(R^2\) barely separates the quadratic and cubic models.
- The linear model is far behind the other two on every criterion. The quadratic term is earning its keep.
- The quadratic model has the lowest AIC, AICc, and BIC. Adding a cubic term improves the fit slightly, but not enough to justify the extra parameter.
Reading Information Criteria Carefully
It is tempting to treat information criteria as a score to optimize: fit everything, choose the smallest number, and stop. Resist this. The criteria are one piece of evidence in a broader discussion of what the model is for and what trade-offs you are willing to make.
- Only differences matter. The value of the AIC on its own means nothing. What matters is how far apart two models are. As a rough guide, models within about 2 units of each other are about equally supported by the data. A difference of 10 or more is strong evidence for the lower model.
- A small difference is a tie. When two models are close, the criteria have not chosen for you. Use other considerations, such as simplicity, interpretability, and whether the model makes sense for the process.
- The criteria can disagree. The AICc leans toward models that forecast well, and the BIC leans toward simpler models. A disagreement tells you something about the trade-off. It is not a problem to be resolved by picking a favorite.
- They say nothing about assumptions. A model can have the lowest AICc and still have autocorrelated residuals. You still need to check the residuals.
- Think about the purpose. The quadratic model has a negative \(u_t^2\) term. If we extended it far enough into the future, it would predict that air travel eventually declines. For a forecast a few years ahead, this is not a concern. For a forecast decades ahead, the linear model might be the more sensible choice, even though it fits these data worse.
- Only compare models fitted to the same response. See the example below.
The last point deserves an example. Below, we compare a quadratic model fitted to the original series with the same model fitted to the logarithm.
Show the code
# Shift that puts the log model's AICc in the units of x_t (explained below)
log_shift <- 2 * sum(log(air_ts$passengers))
air_scale_ic <- air_ts |>
model(
original = TSLM(passengers ~ years_elapsed + I(years_elapsed^2) + month),
log = TSLM(log(passengers) ~ years_elapsed + I(years_elapsed^2) + month)
) |>
glance()
air_scale_ic |>
transmute(
Model = c("Quadratic, original scale", "Quadratic, log scale"),
Response = c("x_t", "log(x_t)"),
"Units of response" = c("thousands of passengers", "log(thousands of passengers)"),
AICc = round(AICc, 1),
"AICc in units of x_t" = round(AICc + c(0, log_shift), 1)
) |>
pander(split.table = Inf)| Model | Response | Units of response | AICc | AICc in units of x_t |
|---|---|---|---|---|
| Quadratic, original scale | x_t | thousands of passengers | 931.2 | 931.2 |
| Quadratic, log scale | log(x_t) | log(thousands of passengers) | -854.3 | 741.8 |
Look at the AICc column first. The two values are about 1,800 units apart. Taken at face value, this would be overwhelming evidence for the log model, but the comparison is not fair.
The likelihood measures how probable the observed data are, so it is measured in the units of the response. A density for \(\log(x_t)\) and a density for \(x_t\) are on different scales. Converting from one to the other multiplies the density of each observation by \(1/x_t\). Over the whole series, that shifts \(-2\log(\mathcal{L})\), and therefore the AICc, by
\[ 2 \sum_{t=1}^{n} \log(x_t) = 1596.1 \]
for these data. Adding this amount to the log model’s AICc puts both models in the units of \(x_t\), as shown in the last column. On a common scale, the log model is still better, but by about 189 units, not 1,800. Most of the original gap came from the change of units, not from the models.
In practice, we rarely make this adjustment. We choose a transformation based on the time plot and the residuals, and then use information criteria to compare models that share that transformation.
Our Decision
We will use the quadratic trend. It has the lowest value on all three criteria, the quadratic term is meaningful, and the cubic term adds nothing. Its slowing growth rate is reasonable for the short-term forecasts we will make.
Interpreting the Coefficients
Now that we have chosen the quadratic model, what do its coefficients tell us about airline travel?
Measuring Time
The answer depends on how we measured time. A trend needs a variable that measures time. When we created air_ts, we made two:
tcounts months. \(t = 1\) is January 1949, \(t = 2\) is February 1949, and so on.years_elapsed\(= u_t = t/12\) counts the same months in units of years.
years_elapsed is not the calendar year. It is the time elapsed since December 1948, the month before the data begin. Each month adds \(1/12\):
| Month | t |
years_elapsed |
|---|---|---|
| Jan 1949 | 1 | 0.083 |
| Feb 1949 | 2 | 0.167 |
| Dec 1949 | 12 | 1.000 |
| Jan 1950 | 13 | 1.083 |
| Dec 1960 | 144 | 12.000 |
So \(u_t = 0\) is December 1948, and a one-unit change in \(u_t\) is one year.
years_elapsed and Not trend() or the Calendar Year?
fable’s trend(). fable has shortcuts for these variables. trend() creates t, counting observations 1, 2, 3, … in the units of the data, which here are months. season() creates the month indicators with January as the reference. The code below fits the linear candidate both ways.
air_units <- air_ts |>
model(
years_elapsed = TSLM(log(passengers) ~ years_elapsed + month),
trend = TSLM(log(passengers) ~ trend() + season())
)Show the code
units_coef <- tidy(air_units) |>
filter(term %in% c("(Intercept)", "years_elapsed", "trend()", "monthFeb", "season()year2"))
units_coef |>
select(Model = .model, Term = term, Estimate = estimate) |>
round_df(4) |>
display_table()
slope_years <- units_coef |> filter(term == "years_elapsed") |> pull(estimate)
slope_months <- units_coef |> filter(term == "trend()") |> pull(estimate)
fitted_diff <- max(abs(
fitted(air_units |> select(years_elapsed))$.fitted -
fitted(air_units |> select(trend))$.fitted
))years_elapsed and month or with trend() and season()
| Model | Term | Estimate |
|---|---|---|
| years_elapsed | (Intercept) | 4.7268 |
| years_elapsed | years_elapsed | 0.1208 |
| years_elapsed | monthFeb | -0.0221 |
| trend | (Intercept) | 4.7268 |
| trend | trend() | 0.0101 |
| trend | season()year2 | -0.0221 |
These are the same model. Their fitted values differ by less than \(10^{-12}\), which is rounding error, so they also give the same forecasts. The intercepts match. The February coefficients match too; season()year2 is fable’s name for monthFeb. Only the slopes differ, by a factor of 12:
trend()counts months, so its slope, 0.0101, is the change in \(\log(x_t)\) per month.years_elapsedcounts years, so its slope, 0.1208 \(= 12 \times\) 0.0101, is the change per year.
We use years_elapsed in this lesson for two reasons. Its coefficients describe change per year, which is easier to talk about. It also keeps powers of time small: by the end of the series, \(u_t^3 = 1{,}728\), while \(t^3\) is about 3,000,000. Numbers that large can cause numerical problems, including in the regression with \(AR(1)\) errors we fit later in this lesson. The cost is that when we forecast, we must create the future values of years_elapsed ourselves. trend() would do that for us.
The calendar year. For the global temperatures in Chapter 5 Lesson 1, we measured time with the calendar year (stats_time = 1970.00, 1970.08, …). That works for a straight line, but it breaks down here.
Show the code
air_calendar <- air_ts |>
mutate(calendar_year = year(date) + (month(date) - 1) / 12) |>
model(
linear = TSLM(log(passengers) ~ calendar_year + month),
quadratic = TSLM(log(passengers) ~ calendar_year + I(calendar_year^2) + month),
cubic = TSLM(log(passengers) ~ calendar_year + I(calendar_year^2) + I(calendar_year^3) + month)
)
tidy(air_calendar) |>
filter(!str_detect(term, "^month")) |>
select(Model = .model, Term = term, Estimate = estimate) |>
mutate(Estimate = map_chr(Estimate, \(x) format(signif(x, 3), scientific = FALSE, big.mark = ","))) |>
display_table()| Model | Term | Estimate |
|---|---|---|
| linear | (Intercept) | -231 |
| linear | calendar_year | 0.121 |
| quadratic | (Intercept) | -12,100 |
| quadratic | calendar_year | 12.2 |
| quadratic | I(calendar_year^2) | -0.00309 |
| cubic | (Intercept) | -12,100 |
| cubic | calendar_year | 12.2 |
| cubic | I(calendar_year^2) | -0.00309 |
| cubic | I(calendar_year^3) | NA |
- The intercept is the value in year 0 AD. In the linear model, \(\alpha_0\) is the predicted log number of passengers two thousand years before airplanes.
- With a quadratic, \(\alpha_1\) becomes the slope in year 0 AD. It is about 12 per year, a growth rate that never happened anywhere near the data.
- The powers are nearly identical. Over 1949–1960,
calendar_yearand its square have a correlation of 0.9999997.TSLM()cannot separate the cubic term from the others, so it silently drops that term and reportsNA.
Measuring time from the start of the series avoids all three problems.
Reading the Estimates
Table 3 gives the trend coefficients and one seasonal coefficient from the quadratic model. These are the OLS estimates. When we add \(AR(1)\) errors in the next activity, the estimates barely change, so the interpretation below still holds.
Show the code
quad_coef <- air_models |>
select(quadratic) |>
tidy() |>
filter(term %in% c("(Intercept)", "years_elapsed", "I(years_elapsed^2)", "monthJul"))
quad_coef |>
select(Term = term, Estimate = estimate) |>
round_df(4) |>
display_table()
get_est <- function(name) quad_coef |> filter(term == name) |> pull(estimate)
a0 <- get_est("(Intercept)")
a1 <- get_est("years_elapsed")
a2 <- get_est("I(years_elapsed^2)")
jul <- get_est("monthJul")
slope_start <- a1 # slope of the trend at u_t = 0
slope_end <- a1 + 2 * a2 * 12 # slope of the trend at u_t = 12 (Dec 1960)
pct <- function(x) round(100 * (exp(x) - 1), 1)| Term | Estimate |
|---|---|
| (Intercept) | 4.6514 |
| years_elapsed | 0.1582 |
| I(years_elapsed^2) | -0.0031 |
| monthJul | 0.3000 |
Because the response is \(\log(x_t)\), a change of \(c\) on the log scale multiplies \(x_t\) by \(e^c\). That turns each coefficient into a statement about percent change.
- The intercept. \(\hat\alpha_0 =\) 4.651 is the fitted value of \(\log(x_t)\) at \(u_t = 0\) for the reference month, January. On the original scale, \(e^{\hat\alpha_0} \approx\) 105 thousand passengers. This is where the trend starts, just before the data begin.
- The trend. With a quadratic, the slope of the trend changes over time. It is \(\hat\alpha_1 + 2\hat\alpha_2 u_t\), so \(\hat\alpha_1\) alone is only the slope at \(u_t = 0\). At the start of the series, the trend grows by about 17.1% per year. By December 1960 (\(u_t = 12\)), the growth rate has slowed to about 8.8% per year. This is the slowing growth that the negative quadratic term describes.
- The seasonal terms. \(\Delta\hat\beta_7 =\) 0.3 for July. Holding the trend fixed, July has about 35% more passengers than January, every year. On the original scale, the seasonal terms multiply the trend instead of adding to it, so the seasonal swings grow as the series grows. This is the pattern in Figure 1 that led us to take the logarithm.
Class Activity: Forecasting and Bias Correction (10 min)
Forecasting on the Original Scale
Our model describes \(\log(x_t)\), but we want forecasts of the number of passengers. Because we wrote log(passengers) in the model formula, fable undoes the transformation for us. The forecasts it returns are already on the original scale.
To forecast, we need future values of every predictor in the model. Because we measured time with years_elapsed instead of fable’s trend(), we have to build these ourselves; trend() would have extended itself automatically. We create three years of future months, continue the time index \(t\) from where the data end, and assign each future month its month label.
Show the code
n_months_forecast <- 36
air_future <- new_data(air_ts, n = n_months_forecast) |>
mutate(
t = nrow(air_ts) + row_number(),
years_elapsed = t / 12,
month = factor(month.abb[month(date)], levels = month.abb)
)
air_fc <- air_ar |>
forecast(new_data = air_future)Figure 4 shows the fitted values (blue) and the forecasts with a 95% prediction interval.
Show the code
air_fc |>
autoplot(air_ts, level = 95) +
geom_line(
data = augment(air_ar),
aes(x = date, y = .fitted),
color = "#56B4E9"
) +
labs(
x = "Month",
y = "Passengers (Thousands)",
title = "Airline Passengers with Three-Year Forecast",
subtitle = "Quadratic trend, monthly indicators, and AR(1) errors fitted to log(passengers)"
) +
theme_minimal() +
theme(
plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)
)Notice that the prediction interval is not symmetric. It stretches farther above the forecast than below it. A symmetric interval on the log scale becomes lopsided when we exponentiate it.
Why Back-Transforming Introduces Bias
The model gives us a forecast distribution for \(\log(x_t)\) with a mean, \(\mu\), and a variance, \(\sigma^2\). The simplest way to get back to the original scale is to compute \(e^{\mu}\). But averaging and exponentiating do not commute: the exponential of the mean is not the mean of the exponential.
On the log scale, the forecast distribution is symmetric, so \(\mu\) is both its mean and its median. Exponentiating keeps values in the same order, so \(e^{\mu}\) is still the median on the original scale. But the exponential function stretches large values more than small ones, which pulls the mean above the median. Using \(e^{\mu}\) as a forecast of the mean would be biased low. If the log values are normally distributed, the mean on the original scale is
\[ e^{\mu + \frac{1}{2}\sigma^2} = e^{\mu} \cdot e^{\frac{1}{2}\sigma^2} \]
The factor \(e^{\frac{1}{2}\sigma^2}\) is the bias correction.
fable Corrects the Bias for You
When the model formula contains a transformation, the .mean column that fable returns is already bias-adjusted. The forecast distribution column, passengers, holds the full distribution, so we can also ask it for the median, \(e^{\mu}\). Table 5 compares the two.
Show the code
air_bias <- air_fc |>
as_tibble() |>
mutate(
median = median(passengers), # e^mu: back-transformed, no correction
ratio = .mean / median # the bias correction fable applied
) |>
select(date, median, .mean, ratio)
air_bias| Month | Median (no correction) | Mean (fable .mean) | Ratio |
|---|---|---|---|
| 1961 Jan | 445.0474 | 445.331 | 1.0006 |
| 1961 Feb | 440.1291 | 440.5371 | 1.0009 |
| 1961 Mar | 506.202 | 506.7381 | 1.0011 |
| 1961 Apr | 494.9101 | 495.4639 | 1.0011 |
| ⋮ | ⋮ | ⋮ | ⋮ |
| 1963 Nov | 489.0402 | 489.6119 | 1.0012 |
| 1963 Dec | 551.7405 | 552.3855 | 1.0012 |
The .mean column is slightly larger than the median, and the ratio between them is the bias correction. The correction grows slightly with the forecast horizon, because the forecast variance \(\sigma^2\) grows as we forecast farther ahead. For these data, the correction is small (well under 1%), because the model fits the log series closely. For a noisier series, it can be much larger.
- fable’s forecast
.meanis already bias-corrected when the model formula includes a transformation likelog(). - Do not multiply
.meanby a correction factor. That corrects the bias twice. - The fitted values from
augment()are back-transformed without a correction. They are medians, not means.
Section 5.10 of the textbook gives two correction factors for back-transformed values. Both multiply the uncorrected (median) value, \(e^{\mu}\). fable uses a version of the first one.
Log-normal correction. If the residuals on the log scale are approximately normal with variance \(\sigma^2\):
\[ \hat x_t' = e^{\frac{1}{2} \sigma^2} \cdot e^{\widehat{\log x_t}} \]
Empirical correction. If the residuals are not approximately normal (for example, if they are noticeably skewed), we replace the normal-theory factor with the average of the exponentiated residuals:
\[ \hat x_t' = e^{\widehat{\log x_t}} \cdot \frac{1}{n} \sum_{t=1}^{n} e^{w_t} \]
where \(\{w_t\}\) is the residual series on the log scale.
To decide which applies, we look at the shape of the residuals. Figure 5 gives a histogram of the innovation residuals with a normal curve for comparison.
Show the code
air_innov <- air_ar |>
augment() |>
pull(.innov)
tibble(x = air_innov) |>
mutate(density = dnorm(x, mean(air_innov), sd(air_innov))) |>
ggplot(aes(x = x)) +
geom_histogram(aes(y = after_stat(density)),
color = "white", fill = "#56B4E9", bins = 20) +
geom_line(aes(y = density)) +
labs(
x = "Innovation Residual",
y = "Density",
title = "Histogram of Innovation Residuals"
) +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5))We can also measure the asymmetry with the skewness, the average cubed standardized residual:
\[ \text{skewness} = \frac{1}{n} \sum_{t=1}^{n} \left( \frac{w_t - \bar w}{s_w} \right)^3 \]
Show the code
air_skew <- mean(((air_innov - mean(air_innov)) / sd(air_innov))^3)The skewness of the residuals is -0.219. A skewness between -0.5 and 0.5 suggests the distribution is roughly symmetric. Skewness between 0.5 and 1 in absolute value is moderate, and above 1 is high.
Show the code
air_sigma2 <- glance(air_ar)$sigma2
tibble(
lognormal_cf = exp(air_sigma2 / 2), # log-normal correction factor
empirical_cf = mean(exp(air_innov)), # empirical correction factor
fable_1_step = air_bias$ratio[1] # ratio fable applied one month ahead
) |>
round_df(5) |>
display_table()| lognormal_cf | empirical_cf | fable_1_step |
|---|---|---|
| 1.00064 | 1.00024 | 1.00064 |
The log-normal factor and the ratio fable applied one month ahead are nearly identical. The textbook factors use the variance of the residuals, so they are appropriate for fitted values and one-step forecasts. fable uses the forecast variance at each horizon, which is why its correction grows over time.
If the residuals were clearly skewed and you wanted the empirical correction instead, you would apply it to the median, not to .mean:
air_fc |>
mutate(empirical_mean = median(passengers) * mean(exp(air_innov)))Small-Group Activity: Industrial Electricity Consumption in Texas (20 min)
These data give the amount of electricity (in megawatt-hours) used each month for industrial purposes in Texas from 2010 through 2023.
Show the code
elec_ts <- rio::import("https://byuistats.github.io/timeseries/data/electricity_tx.csv") |>
dplyr::select(-comments) |>
mutate(
date = yearmonth(my(month)),
t = row_number(),
years_elapsed = t / 12,
month = factor(month.abb[month(date)], levels = month.abb)
) |>
as_tsibble(index = date)
elec_plot_raw <- elec_ts |>
autoplot(.vars = megawatthours) +
labs(
x = "Month",
y = "Megawatt-hours",
title = "Texas Industrial Electricity Use"
) +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5))
elec_plot_log <- elec_ts |>
autoplot(.vars = log(megawatthours)) +
labs(
x = "Month",
y = "log(Megawatt-hours)",
title = "Log of Texas Industrial Electricity Use"
) +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5))
elec_plot_raw | elec_plot_logHomework Preview (5 min)
- Review upcoming homework assignment
- Clarify questions