Artificial Intelligence Applications in Engineering (MUH-920), week 12 of 14

Learning from Sequences: Time Series, Forecasting and Recurrent Networks

Prof. Dr. Utku Kose, Süleyman Demirel University

Time series in engineering

A time series is a sequence of measurements indexed by time. Its behaviour usually combines a trend, a slow change of level; seasonality, a pattern that repeats with a fixed period such as a day or a year; cycles without a fixed period; and irregular noise. Neighbouring values are correlated, which is the property forecasting exploits and the property that breaks the independence assumption of the random splits used in Weeks 7 and 8. Box and Jenkins built a systematic methodology on autocorrelation and differencing [1], and Hyndman and Athanasopoulos give a modern, practical account of forecasting with open examples [2].

The Keeling curve is a textbook series. Continuous measurements at Mauna Loa since 1958 show the carbon dioxide concentration rising every year, with an annual cycle of a few parts per million caused by the growth and decay of vegetation in the northern hemisphere [3, 4]. The rise itself accelerates, so a straight line underestimates the future.

Check your understanding. Why must the test set of a forecasting problem lie after the training period?

Formulas: Components, differences and autocorrelation

A time series y1,y2,…,yTy_1, y_2, \ldots, y_T is often described as the sum of a trend TtT_t, a seasonal component StS_t that repeats with the period mm, for example m=12m = 12 for monthly data with a yearly cycle, and a remainder RtR_t [2]:

yt=Tt+St+Rty_t = T_t + S_t + R_t

When the seasonal swings grow with the level, a product yt=Tt×St×Rty_t = T_t \times S_t \times R_t fits better, and taking logarithms turns it into a sum. Differences remove a trend or a season:

∇yt=yt−yt−1,    ∇myt=yt−yt−m\nabla y_t = y_t - y_{t-1}, \;\; \nabla_m y_t = y_t - y_{t-m}

The autocorrelation at lag kk measures how strongly the series is correlated with itself kk steps earlier. With the mean y‾\overline{y} of the series [1]:

rk=∑t=k+1T(yt−y‾)(yt−k−y‾)∑t=1T(yt−y‾)2r_k = \frac{\sum_{t=k+1}^{T} (y_t - \overline{y})(y_{t-k} - \overline{y})}{\sum_{t=1}^{T} (y_t - \overline{y})^2}

For a series without any autocorrelation, about 95% of the values rkr_k lie between −1.96/T-1.96/\sqrt{T} and 1.96/T1.96/\sqrt{T} [2]. A seasonal series has large values of rkr_k at multiples of the period, and a trending series has values that decrease slowly with kk.

Worked example: Autocorrelation of a quarterly series

The electricity demand of a small plant, in MWh per quarter over two years, is 52, 40, 45, 60, 56, 43, 48 and 64.

Step 1. Mean and deviations. The mean is y‾=408/8=51\overline{y} = 408/8 = 51. The table lists the deviations dt=yt−51d_t = y_t - 51, their squares and the products of each deviation with the deviation one, two and four quarters earlier:

tt yty_t dtd_t dt2d_t^2 dtdt−1d_t d_{t-1} dtdt−2d_t d_{t-2} dtdt−4d_t d_{t-4}
1 52 1 1
2 40 −11 121 −11
3 45 −6 36 66 −6
4 60 9 81 −54 −99
5 56 5 25 45 −30 5
6 43 −8 64 −40 −72 88
7 48 −3 9 24 −15 18
8 64 13 169 −39 −104 117
Sum 408 0 506 −9 −326 228

Step 2. Lag 1. The seven products of neighbouring deviations add up to −9:

r1=−9506=−0.017787r_1 = \frac{-9}{506} = -0.017787

Step 3. Lag 2. The six products add up to −326:

r2=−326506=−0.644269r_2 = \frac{-326}{506} = -0.644269

Step 4. Lag 4. The four products add up to 228:

r4=228506=0.450593r_4 = \frac{228}{506} = 0.450593

Step 5. Reading the values. The positive r4r_4 shows the yearly pattern: Each quarter resembles the same quarter a year earlier. The strongly negative r2r_2 shows that quarters half a year apart lie on opposite sides of the mean. With only eight values, the band ±1.96/8=±0.692965\pm 1.96/\sqrt{8} = \pm 0.692965 is wide, so such conclusions need longer records. The seasonal differences yt−yt−4y_t - y_{t-4} are 4, 3, 3, 4, nearly constant, which reveals a trend of about 3.5 MWh per year that the season had hidden. Part A of the interactive lab computes autocorrelations and differences of any series.

Baselines and honest evaluation

Every forecasting study needs baselines. The naive forecast repeats the last observation, and the seasonal naive forecast repeats the value from one season earlier, for example the same month of the previous year [2]. A sophisticated model that cannot beat them has learned nothing useful. Evaluation must respect time: The model is trained on data up to a forecast origin and tested on the following horizon. Rolling-origin evaluation repeats this for several origins and averages the errors, which gives a more reliable picture than a single split. Errors grow with the horizon, so results should be reported per horizon or for the horizon that matters for the decision, such as one day ahead for unit commitment in a power system [5].

Animation: From a series to training examples

A window of past values forms the input and the next values form the target. Sliding the window through the training period creates the examples on which a model is trained. Change the window and horizon lengths.

Formulas: Baselines and error measures

A forecast made at the origin TT for the horizon hh is written y^T+h∣T\hat{y}_{T+h \vert T}. The naive forecast repeats the last observation, the seasonal naive forecast repeats the observation of the same season one period earlier, here for horizons up to one period, and the drift method extends the average change of the past [2]:

y^T+h∣T=yT,    y^T+h∣T=yT+h−m,    y^T+h∣T=yT+h yT−y1T−1\hat{y}_{T+h \vert T} = y_T, \;\; \hat{y}_{T+h \vert T} = y_{T+h-m}, \;\; \hat{y}_{T+h \vert T} = y_T + h\, \frac{y_T - y_1}{T - 1}

With the errors et=yt−y^te_t = y_t - \hat{y}_t of the nn test values, the common error measures are

MAE=1n∑∣et∣,    RMSE=1n∑et2,    MAPE=100n∑∣etyt∣\text{MAE} = \frac{1}{n} \sum \vert e_t \vert, \;\; \text{RMSE} = \sqrt{\frac{1}{n} \sum e_t^2}, \;\; \text{MAPE} = \frac{100}{n} \sum \Big\vert \frac{e_t}{y_t} \Big\vert

MAE is in the unit of the data, RMSE weighs large errors more, and MAPE is a percentage that fails when values come close to zero. The mean absolute scaled error divides the MAE by the in-sample MAE of the seasonal naive forecast on the training data, so that values below 1 beat that baseline [2]:

MASE=MAE1T−m∑t=m+1T∣yt−yt−m∣\text{MASE} = \frac{\text{MAE}}{\frac{1}{T - m} \sum_{t=m+1}^{T} \vert y_t - y_{t-m} \vert}

Rolling-origin evaluation repeats the forecast for several origins T1<T2<⋯T_1 < T_2 < \cdots and averages the errors for each horizon.

Worked example: Three baselines and four error measures

The two years of quarterly demand of the previous example form the training data, and the third year, with 59, 47, 51 and 68 MWh, is the test period.

Step 1. Forecasts and errors. The naive forecast repeats the last value, 64. The seasonal naive forecast repeats the four quarters of the second year. A seasonal naive forecast with drift adds the mean yearly change of the training data, the mean of the seasonal differences 4, 3, 3 and 4, which is 14/4=3.514/4 = 3.5:

Method Forecasts Errors yt−y^ty_t - \hat{y}_t
Naive 64, 64, 64, 64 −5, −17, −13, 4
Seasonal naive 56, 43, 48, 64 3, 4, 3, 4
Seasonal naive with drift 59.5, 46.5, 51.5, 67.5 −0.5, 0.5, −0.5, 0.5

Step 2. MAE and RMSE.

MAEnaive=5+17+13+44=9.75\text{MAE}_{\text{naive}} = \frac{5 + 17 + 13 + 4}{4} = 9.75
RMSEnaive=25+289+169+164=124.75=11.169154\text{RMSE}_{\text{naive}} = \sqrt{\frac{25 + 289 + 169 + 16}{4}} = \sqrt{124.75} = 11.169154
MAEseasonal=3+4+3+44=3.5,    RMSEseasonal=9+16+9+164=12.5=3.535534\text{MAE}_{\text{seasonal}} = \frac{3 + 4 + 3 + 4}{4} = 3.5, \;\; \text{RMSE}_{\text{seasonal}} = \sqrt{\frac{9 + 16 + 9 + 16}{4}} = \sqrt{12.5} = 3.535534

and for the forecast with drift every error has the size 0.5, so its MAE and RMSE are both 0.5.

Step 3. MAPE. For the naive forecast, the relative errors are 5/595/59, 17/4717/47, 13/5113/51 and 4/684/68:

MAPEnaive=1004×(0.084746+0.361702+0.254902+0.058824)\text{MAPE}_{\text{naive}} = \frac{100}{4} \times (0.084746 + 0.361702 + 0.254902 + 0.058824)
MAPEnaive=25×0.760174=19.00435%\text{MAPE}_{\text{naive}} = 25 \times 0.760174 = 19.00435\%

The same computation gives 6.34% for the seasonal naive forecast and 0.9067% with drift.

Step 4. MASE. The in-sample seasonal naive errors of the training data are 4, 3, 3 and 4, with the mean 3.5, so the MASE is 9.75/3.5=2.7857149.75/3.5 = 2.785714 for the naive forecast, 3.5/3.5=13.5/3.5 = 1 for the seasonal naive forecast and 0.5/3.5=0.1428570.5/3.5 = 0.142857 with drift. Only the forecast that respects both season and trend beats the seasonal naive baseline clearly. Part B of the interactive lab computes all baselines and measures for any series. Part C compares the naive, seasonal naive, moving average, trend-and-season regression and Holt-Winters forecasts of a generated series on a held-out final period, and Part D repeats the comparison over rolling origins and shows how the error grows with the horizon.

Regression models for time series

Linear regression becomes a forecasting model when its inputs describe time. A polynomial trend captures slow change, and pairs of sine and cosine terms with the seasonal period, called Fourier terms, capture a smooth seasonal pattern with few parameters. Lagged values of the series itself, the value one month ago or twelve months ago, turn forecasting into ordinary supervised learning, so that ridge regression, random forests or gradient boosting can be used. For horizons longer than one step, the model is applied recursively, feeding its own forecasts back as lags, or a separate model is trained for each horizon. Exponential smoothing and ARIMA models are classical alternatives with well understood behaviour and prediction intervals [1, 2].

Check your understanding. A monthly series has a yearly cycle. Which pair of features represents the first harmonic of the season?

Formulas: Trend and Fourier terms, autoregression and exponential smoothing

A regression on time describes the trend by powers of tt and a season of period mm by pairs of sine and cosine terms, the Fourier terms [2]:

yt=β0+β1t+β2t2+∑k=1K[aksin⁡2πktm+bkcos⁡2πktm]+εty_t = \beta_0 + \beta_1 t + \beta_2 t^2 + \sum_{k=1}^{K} \Big[ a_k \sin\frac{2 \pi k t}{m} + b_k \cos\frac{2 \pi k t}{m} \Big] + \varepsilon_t

The pair of order k=1k = 1 describes one smooth wave per period. Since asin⁡θ+bcos⁡θ=Asin⁡(θ+ϕ)a \sin \theta + b \cos \theta = A \sin(\theta + \phi) with A=a2+b2A = \sqrt{a^2 + b^2}, the pair has the amplitude AA, and its phase sets the season of the peak; higher orders sharpen the shape.

An autoregression predicts a value from the pp values before it, which turns forecasting into ordinary regression on lagged inputs [1]:

yt=c+ϕ1yt−1+ϕ2yt−2+⋯+ϕpyt−p+εty_t = c + \phi_1 y_{t-1} + \phi_2 y_{t-2} + \cdots + \phi_p y_{t-p} + \varepsilon_t

For p=1p = 1, least squares on the pairs (xt,yt)=(yt−1,yt)(x_t, y_t) = (y_{t-1}, y_t) gives ϕ=Sxy/Sxx\phi = S_{xy}/S_{xx} and c=y‾−ϕ x‾c = \overline{y} - \phi\, \overline{x}, with

Sxy=∑xtyt−1n∑xt∑yt,    Sxx=∑xt2−1n(∑xt)2S_{xy} = \sum x_t y_t - \frac{1}{n} \sum x_t \sum y_t, \;\; S_{xx} = \sum x_t^2 - \frac{1}{n} \Big(\sum x_t\Big)^2

for the nn pairs. Forecasts for several steps use earlier forecasts as inputs, recursively. For ∣ϕ∣<1\vert \phi \vert < 1 they approach the mean μ=c/(1−ϕ)\mu = c/(1 - \phi) geometrically, since y^T+h−μ=ϕh(yT−μ)\hat{y}_{T+h} - \mu = \phi^h (y_T - \mu).

Exponential smoothing forms a level ℓt\ell_t as a weighted average of the newest value and the previous level, with a smoothing factor 0<α≤10 < \alpha \le 1; unrolled, the weights of the past values α,α(1−α),α(1−α)2,…\alpha, \alpha(1 - \alpha), \alpha(1 - \alpha)^2, \ldots decay geometrically. Holt's method adds a trend btb_t with its own factor β\beta [2]:

ℓt=αyt+(1−α)(ℓt−1+bt−1),    bt=β(ℓt−ℓt−1)+(1−β)bt−1\ell_t = \alpha y_t + (1 - \alpha)(\ell_{t-1} + b_{t-1}), \;\; b_t = \beta (\ell_t - \ell_{t-1}) + (1 - \beta) b_{t-1}
y^T+h∣T=ℓT+h bT\hat{y}_{T+h \vert T} = \ell_T + h\, b_T

Without the trend, bt=0b_t = 0, this is simple exponential smoothing, whose forecast is the last level for every horizon. The Holt-Winters method adds a third equation for the seasonal component.

Worked example: Fourier terms of a monthly cycle

A model of a monthly carbon dioxide record contains the first Fourier pair with the illustrative coefficients a=1.5a = 1.5 and b=−2.6b = -2.6 ppm. Time is counted in months from January, so that the terms with 2πt/122 \pi t/12 depend only on the month of the year.

Step 1. The features of May and November. For May, 2π×5/122\pi \times 5/12 is 150 degrees, so sin⁡=0.5\sin = 0.5 and cos⁡=−0.866025\cos = -0.866025. For November, 330 degrees give sin⁡=−0.5\sin = -0.5 and cos⁡=0.866025\cos = 0.866025. The seasonal terms are

1.5×0.5+(−2.6)×(−0.866025)=0.75+2.251665=3.0016651.5 \times 0.5 + (-2.6) \times (-0.866025) = 0.75 + 2.251665 = 3.001665
1.5×(−0.5)+(−2.6)×0.866025=−0.75−2.251665=−3.0016651.5 \times (-0.5) + (-2.6) \times 0.866025 = -0.75 - 2.251665 = -3.001665

Step 2. Amplitude. A=1.52+2.62=2.25+6.76=9.01=3.001666A = \sqrt{1.5^2 + 2.6^2} = \sqrt{2.25 + 6.76} = \sqrt{9.01} = 3.001666 ppm, which agrees with the value of May up to rounding. The seasonal term therefore peaks in May at the value AA and reaches its trough, −A-A, six months later in November, as the vegetation of the northern hemisphere takes up carbon dioxide in summer [3].

Step 3. A prediction. With a level of 420 ppm in January and a trend of 0.2 ppm per month, the model predicts for May of the same year 420+0.2×4+3.001665=423.801665420 + 0.2 \times 4 + 3.001665 = 423.801665 ppm.

Worked example: An autoregression fitted by hand

A sensor gives the readings 20, 23, 22, 25, 24, 26 and 25. An autoregression of order 1 uses the six pairs (20, 23), (23, 22), (22, 25), (25, 24), (24, 26) and (26, 25).

Step 1. Sums. ∑xt=140\sum x_t = 140, ∑yt=145\sum y_t = 145, ∑xt2=400+529+484+625+576+676=3290\sum x_t^2 = 400 + 529 + 484 + 625 + 576 + 676 = 3290, and

∑xtyt=460+506+550+600+624+650=3390\sum x_t y_t = 460 + 506 + 550 + 600 + 624 + 650 = 3390

Step 2. Least squares.

Sxy=3390−140×1456=3390−203006=203S_{xy} = 3390 - \frac{140 \times 145}{6} = 3390 - \frac{20300}{6} = \frac{20}{3}
Sxx=3290−14026=3290−196006=703S_{xx} = 3290 - \frac{140^2}{6} = 3290 - \frac{19600}{6} = \frac{70}{3}
ϕ=20/370/3=27=0.285714,    c=1456−27×1406=145−406=17.5\phi = \frac{20/3}{70/3} = \frac{2}{7} = 0.285714, \;\; c = \frac{145}{6} - \frac{2}{7} \times \frac{140}{6} = \frac{145 - 40}{6} = 17.5

Step 3. Recursive forecasts. From the last reading, 25, and with the exact value ϕ=2/7\phi = 2/7:

y^T+1=17.5+27×25=17.5+7.142857=24.642857\hat{y}_{T+1} = 17.5 + \frac{2}{7} \times 25 = 17.5 + 7.142857 = 24.642857
y^T+2=17.5+27×24.642857=17.5+7.040816=24.540816\hat{y}_{T+2} = 17.5 + \frac{2}{7} \times 24.642857 = 17.5 + 7.040816 = 24.540816
y^T+3=17.5+27×24.540816=17.5+7.011662=24.511662\hat{y}_{T+3} = 17.5 + \frac{2}{7} \times 24.540816 = 17.5 + 7.011662 = 24.511662

Step 4. The long run. The mean is μ=17.5/(1−2/7)=17.5/(5/7)=24.5\mu = 17.5/(1 - 2/7) = 17.5/(5/7) = 24.5. The distance of the forecasts from it shrinks by the factor 2/7 per step, from 25−24.5=0.525 - 24.5 = 0.5 to 0.5×2/7=0.1428570.5 \times 2/7 = 0.142857, which is 24.642857−24.524.642857 - 24.5. Part E of the interactive lab fits autoregressions of any series and order.

Worked example: Simple exponential smoothing and Holt's method

The weekly demand for a spare part is 30, 32, 31, 35 and 37 units.

Step 1. Simple exponential smoothing with α=0.5\alpha = 0.5. Starting from ℓ1=30\ell_1 = 30:

Week Demand Level ℓt=0.5 yt+0.5 ℓt−1\ell_t = 0.5\, y_t + 0.5\, \ell_{t-1}
2 32 0.5×32+0.5×30=310.5 \times 32 + 0.5 \times 30 = 31
3 31 0.5×31+0.5×31=310.5 \times 31 + 0.5 \times 31 = 31
4 35 0.5×35+0.5×31=330.5 \times 35 + 0.5 \times 31 = 33
5 37 0.5×37+0.5×33=350.5 \times 37 + 0.5 \times 33 = 35

The forecast for every following week is 35 units: The method follows the level but not the rise.

Step 2. Holt's method with α=0.5\alpha = 0.5 and β=0.3\beta = 0.3. It starts from ℓ1=30\ell_1 = 30 and the first change b1=32−30=2b_1 = 32 - 30 = 2. Each week updates the level and then the trend:

ℓ2=0.5×32+0.5×(30+2)=32\ell_2 = 0.5 \times 32 + 0.5 \times (30 + 2) = 32
b2=0.3×(32−30)+0.7×2=2b_2 = 0.3 \times (32 - 30) + 0.7 \times 2 = 2
ℓ3=0.5×31+0.5×(32+2)=32.5\ell_3 = 0.5 \times 31 + 0.5 \times (32 + 2) = 32.5
b3=0.3×(32.5−32)+0.7×2=1.55b_3 = 0.3 \times (32.5 - 32) + 0.7 \times 2 = 1.55
ℓ4=0.5×35+0.5×(32.5+1.55)=34.525\ell_4 = 0.5 \times 35 + 0.5 \times (32.5 + 1.55) = 34.525
b4=0.3×(34.525−32.5)+0.7×1.55=1.6925b_4 = 0.3 \times (34.525 - 32.5) + 0.7 \times 1.55 = 1.6925
ℓ5=0.5×37+0.5×(34.525+1.6925)=36.60875\ell_5 = 0.5 \times 37 + 0.5 \times (34.525 + 1.6925) = 36.60875
b5=0.3×(36.60875−34.525)+0.7×1.6925=1.809875b_5 = 0.3 \times (36.60875 - 34.525) + 0.7 \times 1.6925 = 1.809875

Step 3. Forecasts. With ℓ5=36.60875\ell_5 = 36.60875 and b5=1.809875b_5 = 1.809875:

y^6=36.60875+1×1.809875=38.418625\hat{y}_{6} = 36.60875 + 1 \times 1.809875 = 38.418625
y^7=36.60875+2×1.809875=40.2285\hat{y}_{7} = 36.60875 + 2 \times 1.809875 = 40.2285
y^8=36.60875+3×1.809875=42.038375\hat{y}_{8} = 36.60875 + 3 \times 1.809875 = 42.038375

The trend term lets the forecast continue the rise. Part F of the lab runs both methods step by step for any series and factors.

Recurrent neural networks

A recurrent network processes a sequence one step at a time and carries a hidden state from step to step, so that it can summarise the past in a fixed-size vector [6]. Training by backpropagation through time suffers from vanishing and exploding gradients, which makes long-range dependencies hard to learn [7]. The long short-term memory cell adds a memory cell whose input and output gates control what is written into it and read from it, and a forget gate, added in later work, controls what is kept; this design lets information and gradients flow across many steps [8]. The gated recurrent unit is a simpler relative [9]. Convolutional networks over time and attention-based transformers are strong alternatives for sequence modelling [10, 11], and surveys compare these families for forecasting [12].

Deep sequence models need data. A monthly series of about eight hundred values is small for an LSTM, and a well-designed regression with seasonal terms is often as accurate. Recurrent networks show their strength with many related series, such as the load of thousands of feeders, and with long high-frequency records, such as the degradation trajectories of turbofan engines in the C-MAPSS simulation data used for remaining useful life prediction [13].

Check your understanding. What problem does the gating of an LSTM address?

Formulas: The recurrent unit, its gradient and the LSTM cell

A recurrent network reads the inputs x1,x2,…x_1, x_2, \ldots one at a time and updates a hidden state hth_t from the new input and the previous state, with the same weights at every step [6]:

ht=tanh⁡(Wxxt+Whht−1+b),    y^t=Wyht+ch_t = \tanh(W_x x_t + W_h h_{t-1} + b), \;\; \hat{y}_t = W_y h_t + c

Backpropagation through time applies the chain rule along the sequence. For a single unit with the weight whw_h, the derivative of a later state with respect to an earlier one is a product of one factor per step:

∂ht∂ht−k=∏j=t−k+1twh (1−hj2)\frac{\partial h_t}{\partial h_{t-k}} = \prod_{j=t-k+1}^{t} w_h\, (1 - h_j^2)

If the factors are smaller than 1 in size, the product vanishes exponentially with kk; if they are larger, it explodes. Either way, dependencies over many steps are hard to learn [7].

Hochreiter and Schmidhuber introduced a memory cell ctc_t whose content is changed only by addition, protected by gates [8]. The form used today, for example in PyTorch, has an input gate iti_t, a forget gate ftf_t, an output gate oto_t and a candidate gtg_t, each computed from xtx_t and ht−1h_{t-1} with its own weights:

it=σ(Wixt+Uiht−1+bi),    ft=σ(Wfxt+Ufht−1+bf)i_t = \sigma(W_i x_t + U_i h_{t-1} + b_i), \;\; f_t = \sigma(W_f x_t + U_f h_{t-1} + b_f)
gt=tanh⁡(Wgxt+Ught−1+bg),    ot=σ(Woxt+Uoht−1+bo)g_t = \tanh(W_g x_t + U_g h_{t-1} + b_g), \;\; o_t = \sigma(W_o x_t + U_o h_{t-1} + b_o)
ct=ft ct−1+it gt,    ht=ottanh⁡(ct)c_t = f_t\, c_{t-1} + i_t\, g_t, \;\; h_t = o_t \tanh(c_t)

The derivative of the new cell state with respect to the old one along the direct path is the forget gate itself, ∂ct/∂ct−1=ft\partial c_t / \partial c_{t-1} = f_t, so a gate close to 1 carries information and gradients across many steps. An LSTM layer with dd inputs and nn hidden units has four sets of weights and, in PyTorch, two bias vectors per set:

PLSTM=4n(d+n)+8nP_{\text{LSTM}} = 4 n (d + n) + 8 n

Worked example: A recurrent unit and its vanishing gradient

A single unit has wx=0.5w_x = 0.5, wh=0.8w_h = 0.8 and no bias, starts from h0=0h_0 = 0 and reads the inputs 1, 0.5 and −1:

h1=tanh⁡(0.5×1+0.8×0)=tanh⁡(0.5)=0.462117h_1 = \tanh(0.5 \times 1 + 0.8 \times 0) = \tanh(0.5) = 0.462117
h2=tanh⁡(0.5×0.5+0.8×0.462117)=tanh⁡(0.25+0.369694)h_2 = \tanh(0.5 \times 0.5 + 0.8 \times 0.462117) = \tanh(0.25 + 0.369694)
h2=tanh⁡(0.619694)=0.550915h_2 = \tanh(0.619694) = 0.550915
h3=tanh⁡(0.5×(−1)+0.8×0.550915)=tanh⁡(−0.5+0.440732)h_3 = \tanh(0.5 \times (-1) + 0.8 \times 0.550915) = \tanh(-0.5 + 0.440732)
h3=tanh⁡(−0.059268)=−0.059199h_3 = \tanh(-0.059268) = -0.059199

The gradient. The two factors are

∂h3∂h2=0.8×(1−0.003505)=0.797196\frac{\partial h_3}{\partial h_2} = 0.8 \times (1 - 0.003505) = 0.797196
∂h2∂h1=0.8×(1−0.303507)=0.557194\frac{\partial h_2}{\partial h_1} = 0.8 \times (1 - 0.303507) = 0.557194

so ∂h3/∂h1=0.797196×0.557194=0.444193\partial h_3 / \partial h_1 = 0.797196 \times 0.557194 = 0.444193. Over 20 steps with a typical factor of 0.6, the gradient shrinks to 0.620=3.66×10−50.6^{20} = 3.66 \times 10^{-5}; with a factor of 1.2 it grows to 1.220=38.341.2^{20} = 38.34.

Worked example: One step of an LSTM cell

A cell with one input and one hidden unit has the state ht−1=0.2h_{t-1} = 0.2 and ct−1=0.5c_{t-1} = 0.5 and receives xt=1x_t = 1.

Step 1. The gates. Each gate forms its weighted sum wxt+uht−1+bw x_t + u h_{t-1} + b with its own weights ww, uu and bias bb, and applies its function:

Gate Weighted sum Value
iti_t 0.5×1+(−0.3)×0.2+0=0.5−0.06+0=0.440.5 \times 1 + (-0.3) \times 0.2 + 0 = 0.5 - 0.06 + 0 = 0.44 σ(0.44)=0.608259\sigma(0.44) = 0.608259
ftf_t 0.8×1+0.4×0.2+1=0.8+0.08+1=1.880.8 \times 1 + 0.4 \times 0.2 + 1 = 0.8 + 0.08 + 1 = 1.88 σ(1.88)=0.867611\sigma(1.88) = 0.867611
gtg_t 1.2×1+0.6×0.2+(−0.2)=1.2+0.12−0.2=1.121.2 \times 1 + 0.6 \times 0.2 + (-0.2) = 1.2 + 0.12 - 0.2 = 1.12 tanh⁡(1.12)=0.807569\tanh(1.12) = 0.807569
oto_t 0.9×1+(−0.5)×0.2+0.1=0.9−0.1+0.1=0.90.9 \times 1 + (-0.5) \times 0.2 + 0.1 = 0.9 - 0.1 + 0.1 = 0.9 σ(0.9)=0.71095\sigma(0.9) = 0.71095

Step 2. The new states.

ct=0.867611×0.5+0.608259×0.807569=0.433806+0.491211=0.925017c_t = 0.867611 \times 0.5 + 0.608259 \times 0.807569 = 0.433806 + 0.491211 = 0.925017
ht=0.71095×tanh⁡(0.925017)=0.71095×0.728262=0.517758h_t = 0.71095 \times \tanh(0.925017) = 0.71095 \times 0.728262 = 0.517758

Step 3. The path through the cell. Along the cell state, the gradient is multiplied by the forget gate, 0.867611 here. With forget gates of 0.95, it keeps 0.9520=0.3584860.95^{20} = 0.358486 of its size over 20 steps, compared with 3.66×10−53.66 \times 10^{-5} for the simple unit.

Step 4. Size of the notebook's model. The LSTM of the notebook has d=1d = 1 input and n=32n = 32 hidden units, so

PLSTM=4×32×(1+32)+8×32=4224+256=4480P_{\text{LSTM}} = 4 \times 32 \times (1 + 32) + 8 \times 32 = 4224 + 256 = 4480

and its linear output layer adds 32+1=3332 + 1 = 33, for 4513 parameters, which the 24-month windows of the training period must determine. Part G of the interactive lab runs both cells over a sequence.

Forecasts for decisions

A forecast serves a decision: scheduling generation, sizing a reservoir release, ordering spare parts, or setting emission targets. Point forecasts should therefore come with uncertainty, as prediction intervals or quantiles, and probabilistic forecasting competitions in energy have made this standard practice [5]. The forecast horizon, the update frequency and the cost of errors in each direction belong in the problem statement, as the costs of misses and false alarms did in Week 8.

Recursive multi-step forecasts of an LSTM and of a ridge regression on lag windows for the same test period, compared with the observations.
Figure 12.1. Recursive multi-step forecasts of an LSTM and of a ridge regression on lag windows for the same test period, compared with the observations.

Formulas: Prediction intervals, quantiles and costs

If the forecast errors are roughly normal with the standard deviation σh\sigma_h at the horizon hh, the interval

y^T+h∣T±z σh\hat{y}_{T+h \vert T} \pm z\, \sigma_h

contains the future value with the chosen probability, where z=1.96z = 1.96 for 95% and z=1.28z = 1.28 for 80%. The spread grows with the horizon; for the naive forecast of a series whose changes are independent with the standard deviation σ\sigma, it is σh=σh\sigma_h = \sigma \sqrt{h} [2]. The share of test values that fall inside the intervals, the coverage, should be close to the nominal level.

A quantile forecast qτq_\tau states a value that the observation stays below with the probability τ\tau. It is scored with the pinball loss, which energy forecasting competitions use [5]:

Lτ(y,q)=τ (y−q) if y≥q,    Lτ(y,q)=(1−τ)(q−y) if y<qL_\tau(y, q) = \tau\, (y - q) \text{ if } y \ge q, \;\; L_\tau(y, q) = (1 - \tau)(q - y) \text{ if } y < q

When an underestimate costs cuc_u per unit and an overestimate coc_o per unit, the expected cost of a decision qq is cu E[max⁡(0,Y−q)]+co E[max⁡(0,q−Y)]c_u\, \text{E}[\max(0, Y - q)] + c_o\, \text{E}[\max(0, q - Y)]. Raising qq by a small amount saves cuc_u with the probability P(Y>q)P(Y > q) and costs coc_o with the probability P(Y<q)P(Y < q), so the best decision balances both:

co P(Y≤q⋆)=cu (1−P(Y≤q⋆)),    P(Y≤q⋆)=cucu+coc_o\, P(Y \le q^{\star}) = c_u\, (1 - P(Y \le q^{\star})), \;\; P(Y \le q^{\star}) = \frac{c_u}{c_u + c_o}

The best decision is the quantile of the level cu/(cu+co)c_u/(c_u + c_o) of the forecast distribution, not its mean.

Worked example: Intervals for a load forecast

Step 1. One step ahead. A forecast of tomorrow's peak load is 48 MW, and the one-step errors of the past have the standard deviation 2 MW. The 95% interval is

48±1.96×2=48±3.92,    from 44.08 to 51.92 MW48 \pm 1.96 \times 2 = 48 \pm 3.92, \;\; \text{from } 44.08 \text{ to } 51.92 \text{ MW}

Step 2. Four steps ahead. For a naive forecast four days ahead, σ4=2×4=4\sigma_4 = 2 \times \sqrt{4} = 4 MW, and the interval widens to 48±1.96×4=48±7.8448 \pm 1.96 \times 4 = 48 \pm 7.84 MW.

Step 3. Coverage. If 18 of 20 test days fall inside their 95% intervals, the coverage is 18/20=90%18/20 = 90\%. Over many such checks, a coverage persistently below the nominal 95% means that the intervals are too narrow.

Worked example: Pinball loss and the cost of errors

Step 1. Scoring three quantiles. For tomorrow's peak load, the quantile forecasts are q0.1=45q_{0.1} = 45, q0.5=50q_{0.5} = 50 and q0.9=56q_{0.9} = 56 MW, and the observed peak is 53 MW:

L0.1=0.1×(53−45)=0.8,    L0.5=0.5×(53−50)=1.5L_{0.1} = 0.1 \times (53 - 45) = 0.8, \;\; L_{0.5} = 0.5 \times (53 - 50) = 1.5
L0.9=(1−0.9)×(56−53)=0.3L_{0.9} = (1 - 0.9) \times (56 - 53) = 0.3

with the mean (0.8+1.5+0.3)/3=0.866667(0.8 + 1.5 + 0.3)/3 = 0.866667. The 90% quantile is penalised lightly because the observation lies below it, as it should with the probability 0.9.

Step 2. The best quantile. A utility buys any shortfall on the balancing market for 60 per MWh more than planned energy, and a surplus loses 20 per MWh, illustrative values. The best plan is the quantile of the level

cucu+co=6060+20=0.75\frac{c_u}{c_u + c_o} = \frac{60}{60 + 20} = 0.75

Step 3. The planned load. If the forecast distribution is normal with the mean 50 MW and the standard deviation 4 MW, the 75% quantile is 50+0.6745×4=52.69850 + 0.6745 \times 4 = 52.698 MW, about 2.7 MW above the mean forecast. Part H of the interactive lab computes intervals, pinball losses and cost-optimal quantiles.

Python step 12: Time-indexed data, baselines and exceptions

The Python step of this week is part of the Colab notebook, where every explanation stands next to a cell that runs it and the step closes with a quick check and exercises with immediate feedback. The printable lecture notes contain the same step together with the outputs of its code. The Colab button below opens the notebook at the step. Run the setup cell just above the step first, since the exercises use its check function.

Open Python step 12 in Colab View the notebook on GitHub

Review cards

Select a card to turn it over.

Seasonality
A pattern that repeats with a fixed, known period, such as a day, a week or a year.
Seasonal naive forecast
The value from one season earlier; a mandatory baseline for seasonal data [2].
Fourier terms
Sine and cosine pairs with the seasonal period, a compact way to model smooth seasonality.
Rolling origin
Repeated train-then-forecast evaluation with successive forecast origins.
LSTM
Recurrent cell with input, forget and output gates and a memory cell [8].
shift and sliding_window_view
pandas and NumPy tools to create lag features and input windows.

Continue the week

The week continues with the simulation and the self-assessment of the interactive lab and with the Python step and the hands-on work of the Colab notebook. The week overview lists the discipline challenges, the weekly task and the research assignment.

Interactive lab Colab notebook Self-assessment Week overview and tasks

References

[1] Box, G. E. P., Jenkins, G. M., Reinsel, G. C., & Ljung, G. M. (2015). Time Series Analysis: Forecasting and Control (5th ed.). Wiley.

[2] Hyndman, R. J., & Athanasopoulos, G. (2021). Forecasting: Principles and Practice (3rd ed.). OTexts. https://otexts.com/fpp3/

[3] Keeling, C. D., Bacastow, R. B., Bainbridge, A. E., Ekdahl, C. A., Guenther, P. R., Waterman, L. S., & Chin, J. F. S. (1976). Atmospheric carbon dioxide variations at Mauna Loa Observatory, Hawaii. Tellus, 28(6), 538-551. https://doi.org/10.1111/j.2153-3490.1976.tb00701.x

[4] Lan, X., & Keeling, R. (2026). Trends in atmospheric carbon dioxide: Mauna Loa CO2 monthly mean data. NOAA Global Monitoring Laboratory and Scripps Institution of Oceanography. https://gml.noaa.gov/ccgg/trends/

[5] Hong, T., Pinson, P., Fan, S., Zareipour, H., Troccoli, A., & Hyndman, R. J. (2016). Probabilistic energy forecasting: Global Energy Forecasting Competition 2014 and beyond. International Journal of Forecasting, 32(3), 896-913. https://doi.org/10.1016/j.ijforecast.2016.02.001

[6] Elman, J. L. (1990). Finding structure in time. Cognitive Science, 14(2), 179-211. https://doi.org/10.1207/s15516709cog1402_1

[7] Bengio, Y., Simard, P., & Frasconi, P. (1994). Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2), 157-166. https://doi.org/10.1109/72.279181

[8] Hochreiter, S., & Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8), 1735-1780. https://doi.org/10.1162/neco.1997.9.8.1735

[9] Cho, K., van Merriënboer, B., Gulcehre, C., et al. (2014). Learning phrase representations using RNN encoder-decoder for statistical machine translation. In Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP) (pp. 1724-1734). https://doi.org/10.3115/v1/D14-1179

[10] Bai, S., Kolter, J. Z., & Koltun, V. (2018). An empirical evaluation of generic convolutional and recurrent networks for sequence modeling. arXiv preprint arXiv:1803.01271. https://arxiv.org/abs/1803.01271

[11] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention is all you need. In Advances in Neural Information Processing Systems 30 (pp. 5998-6008). https://arxiv.org/abs/1706.03762

[12] Lim, B., & Zohren, S. (2021). Time-series forecasting with deep learning: A survey. Philosophical Transactions of the Royal Society A, 379(2194), 20200209. https://doi.org/10.1098/rsta.2020.0209

[13] Saxena, A., Goebel, K., Simon, D., & Eklund, N. (2008). Damage propagation modeling for aircraft engine run-to-failure simulation. In 2008 International Conference on Prognostics and Health Management (pp. 1-9). IEEE. https://doi.org/10.1109/PHM.2008.4711414