# Time Series with Deep Learning Quick Bite
> Time Series with Deep Learning Quick Bite
A book on forecasting time series with deep learning, from the fundamentals of time series and neural networks to RNN, transformer, VAE, GAN, neural ODE and diffusion forecasters. Many pages come with a notebook; the notebooks are jupytext Python files under dl/notebooks/ in https://github.com/emptymalei/deep-learning. Every page below links to its Markdown version.
# Home
# Time Series Forecasting using Deep Learning
> [!NOTE]
>
> Order my new book: [Time Series with PyTorch: Modern Deep Learning Toolkit for Real-World Forecasting Challenges](). [More about the book]().
Forecasting the future is an extremely valuable superpower. The forecasting game has been dominated by statisticians who are real experts in time series problems. As the amount of data increases, many of the statistical methods are not squeezing enough out of the massive datasets. Consequently, time series forecasting using deep learning emerges and became a fast-growing field. It is trendy, not only in LinkedIn debates but also in academic papers. We plotted the number of related publications per year using [the keyword "deep learning forecasting" on dimensions.ai]()) [^/#bib-dimensionsai].
![deep-learning-forecasting-dimension-ai]()
This chart is obtained on 2022-08-06, from Digital Science’s Dimensions platform, available at https://app.dimensions.ai
On the other hand, deep learning methods are not yet winning all the games of forecasting. Time series forecasting is a complicated problem with a great variety of data generating processes (DGP). Some argue that we don't need deep learning to forecast since well tuned statistical models and trees are already performing well and are faster and more interpretable than deep neural networks[^/#bib-Elsayed2021-ug] [^/#bib-Grinsztajn2022-mu]. Ensembles of statistical models performing great, even outperforming many deep learning models on the [M3 data]()[^/#nixtla-m3-ensemble].
However, deep learning models are picking up speed. In the [M5 competition](), deep learning "have shown forecasting potential, motivating further research in this direction"[^/#bib-Makridakis2022-hb]. As the complexity and size of time series data are growing and more and more deep learning forecasting models are being developed, forecasting with deep learning is on the path to be an important alternative to statistical forecasting methods.
In [Coding Tips](), we provide coding tips to help some readers set up the development environment. In [Deep Learning Fundamentals](), we introduce the fundamentals of deep neural networks and their practices. For completeness, we also provide code and derivations for the models. With these two parts, we introduce time series data and statistical forecasting models in [Time Series Forecasting Fundamentals](), where we discuss methods to analyze time series data, several universal data generating processes of time series data, and some statistical forecasting methods. Finally, we fulfill our promise in the title in [Time Series Forecasting with Deep Learning]().
## Where to Start
Pick the path that fits what you came for.
- **I want to forecast with deep learning.** [Time Series Forecasting with Deep Learning]() → [Forecasting with MLP]() → [Forecasting with RNN]() → [Forecasting with Transformers]()
- **I am new to time series.** [Terminologies of Time Series Data]() → [Time Series Forecasting Tasks]() → [Naive Forecasts]() → [Statistical Models]()
- **I need to judge a forecast.** [Time Series Forecasting Evaluation]() → [Time Series Forecasting Metrics]() → [CRPS]()
- **I want the theory behind the models.** [Neural Networks]() → [Recurrent Neural Networks]() → [Vanilla Transformers]() → [Diffusion Models]()
Or see the whole book at once: the **[Map of the Book]()** shows every page as a dot and every link between two pages as a line.
## Blueprint
The following is my first version of the blueprint.
- [x] Engineering Tips
- [x] Environment, VSCode, Git, ...
- [x] Python Project Tips
- [x] Fundamentals of Time Series Forecasting
- [x] Time Series Data and Terminologies
- [x] Transformation of Time Series
- [x] Two-way Fixed Effects
- [x] Time Delayed Embedding
- [x] Data Generating Process (DGP)
- [x] DGP: Langevin Equation
- [x] Kindergarten Models for Time Series Forecasting
- [x] Statistical Models
- [x] Statistical Model: AR
- [x] Statistical Model: VAR
- [x] Synthetic Datasets
- [x] Synthetic Time Series
- [x] Creating Synthetic Dataset
- [x] Data Augmentation
- [x] Forecasting
- [x] Time Series Forecasting Tasks
- [x] Naive Forecasts
- [x] Evaluation and Metrics
- [x] Time Series Forecasting Evaluation
- [x] Time Series Forecasting Metrics
- [x] CRPS
- [x] Hierarchical Time Series
- [x] Hierarchical Time Series Data
- [x] Hierarchical Time Series Reconciliation
- [x] Some Useful Datasets
- [x] Trees
- [x] Tree-based Models
- [x] Random Forest
- [x] Gradient Boosted Trees
- [x] Forecasting with Trees
- [ ] Fundamentals of Deep Learning
- [x] Deep Learning Introduction
- [x] Learning from Data
- [x] Neural Networks
- [x] Recurrent Neural Networks
- [x] Convolutional Neural Networks
- [x] Transformers
- [x] Dynamical Systems
- [x] Why Dynamical Systems
- [x] Neural ODE
- [x] Energy-based Models
- [x] Diffusion Models
- [x] Generative Models
- [x] Autoregressive Model
- [x] Auto-Encoder
- [x] Variational Auto-Encoder
- [x] Flow
- [x] Generative Adversarial Network (GAN)
- [ ] Time Series Forecasting with Deep Learning
- [x] A Few Datasets
- [x] Forecasting with MLP
- [x] Forecasting with RNN
- [x] Forecasting with Transformers
- [ ] TFT
- [ ] DLinear
- [ ] NLinear
- [ ] Forecasting with CNN
- [ ] Forecasting with VAE
- [ ] Forecasting with Flow
- [ ] Forecasting with GAN
- [x] Forecasting with Neural ODE
- [x] Forecasting with Diffusion Models
- [ ] Extras Topics, Supplementary Concepts, and Code
- [x] DTW and DBA
- [x] f-GAN
- [x] Info-GAN
- [ ] Spatial-temporal Models, e.g., GNN
- [ ] Conformal Prediction
- [ ] Graph Neural Networks
- [ ] Spiking Neural Networks
- [x] Deep Infomax
- [x] Contrastive Predictive Coding
- [ ] MADE
- [ ] MAF
- [ ] ...
[^/#nixtla-m3-ensemble]: Nixtla. statsforecast/experiments/m3 at main · Nixtla/statsforecast. In: GitHub \[Internet\]. \[cited 12 Dec 2022\]. Available: [https://github.com/Nixtla/statsforecast/tree/main/experiments/m3]()
[^/#bib-dimensionsai]: Hook D.W., Porter S.J., Herzog C.. Dimensions: Building Context for Search and Evaluation. *Frontiers in Research Metrics and Analytics*. 2018. [https://app.dimensions.ai/details/publication/pub.1106289502]()
[^/#bib-Elsayed2021-ug]: Elsayed S., Thyssens D., Rashed A. et al.. Do We Really Need Deep Learning Models for Time Series Forecasting?. 2021. [http://arxiv.org/abs/2101.02118]()
[^/#bib-Grinsztajn2022-mu]: Grinsztajn L., Oyallon E., Varoquaux G.. Why do tree-based models still outperform deep learning on tabular data?. 2022. [http://arxiv.org/abs/2207.08815]()
[^/#bib-Makridakis2022-hb]: Makridakis S., Spiliotis E., Assimakopoulos V.. M5 accuracy competition: Results, findings, and conclusions. *International journal of forecasting*. 2022. [https://www.sciencedirect.com/science/article/pii/S0169207021001874]()
# Engineering Tips
# Coding Tips
> [!NOTE]
>
> **In one minute**
>
> The engineering practices this book assumes, kept out of the main chapters: two references on writing good research code, and a checklist of tools for a Python deep learning project, covering the coding environment, code quality and the main packages.
In this book, we use Python as our programming language. In the main chapters, we will focus on the theories and actual code and skip the basic concepts. To make sure we are on the same page, we shove all the tech stack related topics into this chapter for future reference. It is not necessary to read this chapter before reading the main chapters. However, we recommend the readers go through this chapter at some point to make sure they are not missing some basic engineering concepts.
> [!NOTE]
>
> **Info**
>
> This chapter is not aiming to be a comprehensive note on these technologies but a few key components that may be missing in many research-oriented tech stacks. We assume the readers have worked with the essential technologies in a Python-based deep learning project.
## Good References for Coding in Research
Some skills only take a while to learn but people benefit from them for their whole life. Managing code falls exactly into this bucket, for programmers.
[The Good Research Code Handbook]() is a very good and concise guide to building good coding habits. This should be a good first read.
The Alan Turing Institute also has a [Research Software Engineering with Python course](). This is a comprehensive generic course for boosting Python coding skills in research.
> [!NOTE]
>
> **A Checklist of Tech Stack**
>
> We provide a concise list of tools for coding. Most of them are probably already integrated into most people's workflows. Hence we provide no descriptions but only the list itself.
>
> > In the following diagrams, we highlight the recommended tools using orange color. Clicking on them takes us to the corresponding website.
>
> The first set of checklists is to help us set up a good coding environment.
>
> ```
> flowchart TD
> classDef highlight fill:#f96;
>
> env["Setting up Coding Environment"]
> git["fa:fa-star Git"]:::highlight
> precommit["pre-commit"]:::highlight
> ide["Integrated Development Environment (IDE)"]
> vscode["Visual Studio Code"]:::highlight
> pycharm["PyCharm"]
> jupyter["Jupyter Notebooks"]
> python["Python Environment"]
> py_env["Python Environment Management"]
> conda["Anaconda"]
> pyenv_venv["Pyenv + venv + pip"]
> pyenv_poetry["Pyenv + poetry"]
> poetry["Poetry"]:::highlight
> pyenv["pyenv"]:::highlight
> venv["venv"]
>
> click git "https://git-scm.com/" "Git"
> click precommit "https://pre-commit.com/" "pre-commit"
> click vscode "https://code.visualstudio.com/" "Visual Studio Code"
> click jupyter "https://jupyter.org/" "Jupyter Lab"
> click pycharm "https://www.jetbrains.com/pycharm/" "PyCharm"
> click conda "https://www.anaconda.com/" "Anaconda"
> click pyenv "https://github.com/pyenv/pyenv" "pyenv"
> click venv "https://docs.python.org/3/library/venv.html" "venv"
> click poetry "https://python-poetry.org/" "poetry"
>
> env --- git
> git --- precommit
>
> env --- ide
> ide --- vscode
> ide --- jupyter
> ide --- pycharm
>
> env --- python
> python --- py_env
> py_env --- conda
> py_env --- pyenv_venv
> py_env --- pyenv_poetry
>
> pyenv_venv --- pyenv
> pyenv_venv --- venv
>
> pyenv_poetry --- pyenv
> pyenv_poetry --- poetry
> ```
>
> The second set of checklists is to boost our code quality.
>
> ```
> flowchart TD
> classDef highlight fill:#f96;
>
> python["Python Code Quality"]
> test["Test Your Code"]
> formatter["Formatter"]
> linter["Linter"]
> pytest["pytest"]:::highlight
> black["black"]:::highlight
> isort["isort"]:::highlight
> pylint["pylint"]
> flake8["flake8"]
> pylama["pylama"]
> mypy["mypy"]:::highlight
>
> click pytest "https://pytest.org/" "pytest"
> click black "https://github.com/psf/black" "black"
> click isort "https://github.com/pycqa/isort"
> click mypy "http://mypy-lang.org/"
> click pylint "https://pylint.pycqa.org/"
> click flake8 "https://flake8.pycqa.org/en/latest/"
> click pylama "https://github.com/klen/pylama"
>
> python --- test
> test --- pytest
>
> python --- formatter
> formatter --- black
> formatter --- isort
>
> python --- linter
> linter --- mypy
> linter --- pylint
> linter --- flake8
> linter ---pylama
> ```
>
> Finally, we also mention the primary python packages used here.
>
> ```
> flowchart TD
> classDef highlight fill:#f96;
>
> dataml["Data and Machine Learning"]
> pandas["Pandas"]:::highlight
> pytorch["PyTorch"]:::highlight
> lightning["PyTorch Lightning"]:::highlight
> much_more["and more ..."]
>
> click pandas "https://pandas.pydata.org/"
> click pytorch "https://pytorch.org/"
> click lightning "https://www.pytorchlightning.ai/"
>
> dataml --- pandas
> dataml --- pytorch
> dataml --- lightning
> dataml --- much_more
> ```
---
**Related:** [Python]() · [Notebooks and Utilities for Tutorials]()
# Python
> [!NOTE]
>
> **In one minute**
>
> How to set up a Python project: pyenv for Python versions, poetry for dependencies and environments (with conda as the all-in-one alternative), pyproject.toml for the dependency list, pre-commit hooks such as black, isort and mypy for a consistent style, and docstrings and tests.
We assume the readers have a good understanding of the Python programming language, as Python will be the primary programming language for demos and tutorials in this book. For engineering tips, we will cover a few topics here, including
- Environment management;
- Dependency management;
- [`pre-commit`]().
> [!NOTE]
>
> **TL;DR**
>
> 1. Use [pyenv]() to manage Python versions;
> 2. Use [poetry]() to manage dependencies;
> 3. Always set up [`pre-commit`]() for your git repository.
## Python Environment Management
Environment management is never easy, and the same is true for the Python ecosystem. People have developed a lot of tools to make environment management easier. As you could imagine, this also means we have a zoo of tools to choose from.
There are three things to manage in a Python project:
1. Python version,
2. Dependencies of the project, and
3. An environment where we install our dependencies.
Some tools can manage all three, and some tools focus on one or two of them. We discuss two popular sets of tools: `conda` and `pyenv` + `poetry`.
### `conda`
Many data scientists started with the simple and out-of-the-box choice called [`conda`](). `conda` is an all-in-one toolkit to manage Python versions, environments, and project dependencies.
> [!NOTE]
>
> **`conda` cheatsheet**
>
> The most useful commands for conda are the following.
>
> 1. Create an environment: `conda create -n my-env-name python=3.9 pip`, where
>
> 1. `my-env-name` is the name of the environment,
> 2. `python=3.9` specifies the version of Python,
> 3. `pip` at the end is telling `conda` to install `pip` in this new environment.
> 2. Activate an environment: `conda activate my-env-name`
> 3. Install new dependency: `conda install pandas`
> 4. List all available environments: `conda env list`
>
> Anaconda provides [a nice cheatsheet]().
### `pyenv` + `poetry`
`conda` is powerful, but it is too powerful for a simple Python project. As of 2024, if you ask around, many Python developers will recommend [`poetry`]().
`poetry` manages dependencies and environments. We just need a tool like [`pyenv`]() to manage Python versions.
> [!NOTE]
>
> **The `poetry` workflow**
>
> To work with poetry in an existing project `my_kuhl_project`
>
> 1. `poetry init` to initialize the project and follow the instructions;
> 2. `poetry env use 3.10` to specify the Python version. In this example, we use `3.10`;
> 3. `poetry add pandas` to add a package called `pandas`.
>
> Everything we specified will be written into the `pyproject.toml` file.
>
> `poetry` provides [a nice tutorial]() on its website.
## Dependency Specifications
We have a few choices to specify the dependencies. The most used method at the moment is `requirements.txt`. However, specifying dependencies in `pyproject.toml` is a much better choice.
Python introduced `pyproject.toml` in [PEP518]() which can be used together with [`poetry`]() to [manage dependencies]().
While tutorials on how to use `poetry` are beyond the scope of this book, we highly recommend using `poetry` in a formal project.
> [!WARNING]
>
> **`poetry` is sometimes slow**
>
> `poetry` can be very slow as it has to load many different versions of the packages to try out in some cases[^/engineering/python/#slowpoetry][^/engineering/python/#poery_faq].
> [!NOTE]
>
> **`conda` with `pip`**
>
> If one insists on using `conda`, here we provide a few tips for `conda` users.
>
> `conda` [provides its own requirement specification using `environment.yaml`](). However, many projects still prefer `requirements.txt` even though `conda`'s `environment.yaml` is quite powerful.
>
> To use `requirements.txt` and `pip`, we always install `pip` when creating a new environment, e.g., `conda create -n my-env-name python=3.9 pip`.
>
> Once the environment is activated (`conda activate my-env-name`), we can use `pip` to install dependencies, e.g., `pip install -r requirements.txt`.
## Python Styles and `pre-commit`
In a Python project, it is important to have certain conventions or styles. To be consistent, one could follow some style guides for Python. There are official proposals, such as [PEP8](), and "third party" style guides, such as [Google Python Style Guide]() [^/engineering/python/#pep8][^/engineering/python/#gpsg].
We also recommend [`pre-commit`](). `pre-commit` helps us manage git hooks to be executed before each commit. Once installed, every time we run `git commit -m "my commit message here"`, a series of commands will be executed first based on the configurations.
`pre-commit` [officially provides some hooks]() already, e.g., `trailing-whitespace` [^/engineering/python/#pch].
We also recommend the following hooks,
- `black`, which formats the code based on pre-defined styles,
- `isort`, which orders the Python imports[^/engineering/python/#isort],
- `mypy`, which is a linter for Python.
The following is an example `.pre-commit-config.yaml` file for a Python project.
```
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.2.0
hooks:
- id: check-added-large-files
- id: debug-statements
- id: detect-private-key
- id: end-of-file-fixer
- id: requirements-txt-fixer
- id: trailing-whitespace
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.960
hooks:
- id: mypy
args:
- "--no-strict-optional"
- "--ignore-missing-imports"
- repo: https://github.com/ambv/black
rev: 22.6.0
hooks:
- id: black
language: python
args:
- "--line-length=120"
- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
- id: isort
name: isort (python)
args: ["--profile", "black"]
```
## Write docstrings
Writing [docstrings]() for functions and classes can help our future self understand them more easily. There are different styles for docstrings. Two of the popular ones are
- [reStructuredText Docstring Format](), and
- [Google style docstrings]().
## Test Saves Time
Adding tests to our code can save us time. We will not list all these benefits of having tests. But tests can help us debug our code and ship results more confidently. For example, suppose we are developing a function and spot a bug. One of the best ways of debugging it is to write a test and put a debugger breakpoint at the suspicious line of the code. With the help of IDEs such as Visual Studio Code, this process can save us a lot of time in debugging.
> [!NOTE]
>
> **Use `pytest`**
>
> Use [pytest](). RealPython provides a [good short introduction](). The Alan Turing Institute provides [some lectures on testing and pytest]().
---
**Related:** [Coding Tips]() · [Notebooks and Utilities for Tutorials]()
[^/engineering/python/#isort]: Pre Commit. In: isort \[Internet\]. \[cited 22 Jul 2022\]. Available: [https://pycqa.github.io/isort/docs/configuration/pre-commit.html]()
[^/engineering/python/#pch]: pre-commit-config-pre-commit-hooks.yaml. In: Gist \[Internet\]. \[cited 22 Jul 2022\]. Available: [https://gist.github.com/lynnkwong/f7591525cfc903ec592943e0f2a61ed9]()
[^/engineering/python/#pep8]: Guido van Rossum, Barry Warsaw, Nick Coghlan. PEP 8 – Style Guide for Python Code. In: peps.python.org \[Internet\]. 5 Jul 2001 \[cited 23 Jul 2022\]. Available: [https://peps.python.org/pep-0008/]()
[^/engineering/python/#gpsg]: Google Python Style Guide. In: Google Python Style Guide \[Internet\]. \[cited 22 Jul 2022\]. Available: [https://google.github.io/styleguide/pyguide.html]()
[^/engineering/python/#slowpoetry]: Poetry is extremely slow when resolving the dependencies · Issue \#2094 · python-poetry/poetry. In: GitHub \[Internet\]. \[cited 23 Jul 2022\]. Available: [https://github.com/python-poetry/poetry/issues/2094]()
[^/engineering/python/#poery_faq]: FAQ. In: Poetry - Python dependency management and packaging made easy \[Internet\]. \[cited 29 Jan 2024\]. Available: [https://python-poetry.org/docs/faq/\#why-is-the-dependency-resolution-process-slow]()
# Fundamentals of Time Series Forecasting
# Time Series Data and Statistical Forecasting Methods
> [!NOTE]
>
> **In one minute**
>
> This chapter sets up the forecasting problem: use the last K steps of the targets and covariates, plus features known in advance, to predict the next H steps. It also shows how forecasting methods can be categorized.
## Time Series Data
Time series data comes from a variety of data generating processes. There are also different formulations and views of time series data.
Time series data can be formulated as a sequence of vector functions of time [^/time-series/#bib-Dorffner1996-rd]. There are many different types of tasks on time series data, for example,
- classification,
- anomaly detection, and
- forecasting.
In this chapter, we focus on the forecasting problem.
## The Forecasting Problem
To make it easier to formulate the forecasting problem, we group the time series features based on the role they play in a forecasting problem. Given a dataset \\(\\mathcal D\\), with
1. \\(y^{(i)}\_t\\), the sequential variable to be forecasted,
2. \\(x^{(i)}\_t\\), exogenous data for the time series data,
3. \\(u^{(i)}\_t\\), some features that can be obtained or planned in advance,
where \\({}^{(i)}\\) indicates the \\(i\\)th variable, \\({}\_ t\\) denotes time. In a forecasting task, we use \\(y^{(i)} \_ {t-K:t}\\), \\(x^{(i) \_ {t-K:t}}\\), and \\(u^{(i)} \_ {t-K:t+H}\\), to forecast the future \\(y^{(i)} \_ {t+1:t+H}\\). In these notations, \\(K\\) is the input sequence length and \\(H\\) is the forecast horizon.
![time series forecasting problem]()
A forecasting model \\(f\\) will use \\(x^{(i)} \_ {t-K:t}\\) and \\(u^{(i)} \_ {t-K:t+H}\\) to forecast \\(y^{(i)} \_ {t+1:t+H}\\).
In the section [Time Series Forecasting Tasks](), we will discuss more details of the forecasting problem.
## Categories of Forecasting Methods
[Januschowsk et al]() proposed a framework to classify the different forecasting methods[^/time-series/#bib-Januschowski2020-ys]. We illustrate the different methods in the following charts. For simplicity, we simply merge all the possible dimensions in one chart.
```
flowchart LR
classDef subjective fill:#EE8866;
classDef objective fill:#77AADD;
dimensions["Dimensions of Forecasting Methods"]
%% Objective
params_shared["Parameter Shared Accross Series"]:::objective
params_shared --"True"-->Global:::objective
params_shared --"False"-->Local:::objective
uncertainty["Uncertainty in Forecasts"]:::objective
uncertainty --"True"--> Probabilistic["Probabilistic Forecasts:\n forecasts with predictive uncertainty"]:::objective
uncertainty --"False"--> Point["Point Forecasts"]:::objective
computational_complexity["Computational Complexity"]:::objective
linear_convexity["Linear and Convexity"]:::objective
dimensions --> params_shared
dimensions --> uncertainty
dimensions --> computational_complexity
dimensions --> linear_convexity
%% Subjective
structural_assumptions["Strong Structural Assumption"]:::subjective --"Yes"--> model_driven["Model-Driven"]:::subjective
structural_assumptions --"No"--> data_driven["Data-Driven"]:::subjective
model_comb["Model Combinations"]:::subjective
discriminative_generative["Discriminative or Generative"]:::subjective
theoretical_guarantees["Theoretical Guarantees"]:::subjective
predictability_interpretability["Predictability and Interpretibility"]:::subjective
dimensions --> structural_assumptions
dimensions --> model_comb
dimensions --> discriminative_generative
dimensions --> theoretical_guarantees
dimensions --> predictability_interpretability
```
We will mention those different dimensions later in our discussion of different forecasting models. For example, random forest is an ensemble method, which we will discuss in detail later.
---
**Related:** [Time Series Forecasting Tasks]() · [Time Series Analysis]()
[^/time-series/#bib-Dorffner1996-rd]: Dorffner G.. Neural Networks for Time Series Processing. *Neural Network World*. 1996. [http://machine-learning.martinsewell.com/ann/Dorf96.pdf]()
[^/time-series/#bib-Januschowski2020-ys]: Januschowski T., Gasthaus J., Wang Y. et al.. Criteria for classifying forecasting methods. *International journal of forecasting*. 2020. [https://www.sciencedirect.com/science/article/pii/S0169207019301529]()
# Time Series Analysis
> [!NOTE]
>
> **In one minute**
>
> Two ideas from time series analysis that the rest of the book leans on: stationarity (the distribution of the series doesn't change over time, with a weaker form that only looks at the mean and autocorrelation) and serial dependence, measured by autocorrelation. It also notes how terminology differs between fields, such as panel data versus multivariate time series.
Time series analysis is not our focus here. However, it is beneficial to grasp some basic ideas of time series.
## Stationarity
Time series data is stationary if the distribution of the observables do not change[^/time-series/timeseries-data.analysis/#wiki-stationary-process][^/time-series/timeseries-data.analysis/#nist-stationarity][^/time-series/timeseries-data.analysis/#Das2019].
A strict stationary series guarantees the same distribution for a segment \\(\\{x\_{i+1}, \\cdots, x\_{x+k}\\}\\) and a time-shifted segment \\(x\_{i+1+\\Delta}, \\cdots, x\_{x+k+\\Delta}\\}\\) for integer \\(\\Delta\\)[^/time-series/timeseries-data.analysis/#wiki-stationary-process].
A less strict form (WSS) concerns only the mean and autocorrelation[^/time-series/timeseries-data.analysis/#wiki-stationary-process][^/time-series/timeseries-data.analysis/#Shalizi2012], i.e.,
\\\[ \\begin{align} \\mathbb E\[x\_{i+1}\] &= \\mathbb E\[x\_{i+\\Delta}\] \\\\ \\mathbb{Cov}\[x\_{i+1}, x\_{i+k}\] &= \\mathbb{Cov}\[x\_{i+1+\\Delta}, x\_{x+k+\\Delta}\] \\end{align} \\\]
In deep learning, a lot of models require the training data to be I.I.D.[^/time-series/timeseries-data.analysis/#Schoelkopf2021][^/time-series/timeseries-data.analysis/#Dawid2022]. The I.I.D. requirement in time series is stationarity.
A stationary time series is clean and pure. However, real-world data is not necessarily stationary, e.g., macroeconomic series data are non-stationary[^/time-series/timeseries-data.analysis/#Das2019].
## Serial Dependence
Autocorrelation measures the serial dependency of a time series[^/time-series/timeseries-data.analysis/#wiki-autocorrelation]. By definition, the autocorrelation is the autocovariance normalized by the variance,
\\\[ \\rho = \\frac{\\mathbb{Cov}\[x\_t, x\_{t+\\delta}\]}{\\mathbb{Var}\[x\_t\]}. \\\]
One naive expectation is that the autocorrelation diminishes if \\(\\delta \\to \\infty\\)[^/time-series/timeseries-data.analysis/#Shalizi2012].
## Terminology
Terminologies for time series data may be different in different fields[^/time-series/timeseries-data.analysis/#Hyndman2020]. For example, we may encounter the term "panel data" in econometrics, which is the same as "multivariate time series" in "data science".
> [!NOTE]
>
> **Panel Data**
>
> Panel data is multivariate time series data,
>
> \\\[ \\mathbf y\_t \\to y\_{it}. \\\]
>
> | time | variable \\(y\_1\\) | variable \\(y\_2\\) | variable \\(y\_3\\) |
> | --- | --- | --- | --- |
> | \\(t\_1\\) | \\(y\_{11}\\) | \\(y\_{21}\\) | \\(y\_{31}\\) |
> | \\(t\_2\\) | \\(y\_{12}\\) | \\(y\_{22}\\) | \\(y\_{32}\\) |
> | \\(t\_3\\) | \\(y\_{13}\\) | \\(y\_{23}\\) | \\(y\_{33}\\) |
> | \\(t\_4\\) | \\(y\_{14}\\) | \\(y\_{24}\\) | \\(y\_{34}\\) |
> | \\(t\_5\\) | \\(y\_{15}\\) | \\(y\_{25}\\) | \\(y\_{35}\\) |
1. [doi:10.1162/99608f92.dec7d780]()
---
**Related:** [Box-Cox Transformation]() · [AR]()
[^/time-series/timeseries-data.analysis/#wiki-stationary-process]: Contributors to Wikimedia projects. Stationary process. In: Wikipedia \[Internet\]. 18 Sep 2022 \[cited 13 Nov 2022\]. Available: [https://en.wikipedia.org/wiki/Stationary\_process]()
[^/time-series/timeseries-data.analysis/#nist-stationarity]: 6.4.4.2. Stationarity. In: Engineering Statistics Handbook \[Internet\]. NIST; \[cited 13 Nov 2022\]. Available: [https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc442.htm\#:\~:text=Stationarity%20can%20be%20defined%20in,no%20periodic%20fluctuations%20(seasonality).]()
[^/time-series/timeseries-data.analysis/#Shalizi2012]: Shalizi C. 36-402, Undergraduate Advanced Data Analysis (2012). In: Undergraduate Advanced Data Analysis \[Internet\]. 2012 \[cited 13 Nov 2022\]. Available: [https://www.stat.cmu.edu/\~cshalizi/uADA/12/]()
[^/time-series/timeseries-data.analysis/#Schoelkopf2021]: Schölkopf B, Locatello F, Bauer S, Ke NR, Kalchbrenner N, Goyal A, et al. Toward Causal Representation Learning. Proc IEEE. 2021;109: 612–634. doi:10.1109/JPROC.2021.3058954
[^/time-series/timeseries-data.analysis/#wiki-autocorrelation]: Contributors to Wikimedia projects. Autocorrelation. In: Wikipedia \[Internet\]. 10 Nov 2022 \[cited 13 Nov 2022\]. Available: [https://en.wikipedia.org/wiki/Autocorrelation]()
[^/time-series/timeseries-data.analysis/#Das2019]: Das P. Econometrics in Theory and Practice. Springer Nature Singapore; [doi:10.1007/978-981-32-9019-8]()
[^/time-series/timeseries-data.analysis/#Dawid2022]: Dawid P, Tewari A. On learnability under general stochastic processes. Harvard Data Science Review. 2022;
[^/time-series/timeseries-data.analysis/#Hyndman2020]: Hyndman R. Rob J Hyndman - Terminology matters. In: Rob J Hyndman \[Internet\]. 26 Jun 2020 \[cited 9 Nov 2023\]. Available: [https://robjhyndman.com/hyndsight/terminology-matters/\#same-concept-different-terminology]()
# Box-Cox Transformation
> [!NOTE]
>
> **In one minute**
>
> Real series are often non-stationary, with a variance that changes with the level. The Box-Cox transformation, a family of transforms indexed by λ (λ = 0 is the log), reduces this; the air passenger data shows it in action. It doesn't always produce perfectly stationary data.
>
> **Read first:** [Time Series Analysis]()
Many time series models require [stationary data](). However, real-world time series data may be non-stationary and [heteroscedastic]()[^/time-series/timeseries-data.box-cox/#scedasticity]. Box-cox transformation is useful when reducing the non-stationarity and heteroscedasticity.
> [!NOTE]
>
> Rob J Hyndman and George Athanasopoulos's famous textbook FPP2 provides some [nice examples of box-cox transformations]().
To see Box-Cox transformation in action, we show an example using the [air passenger dataset]().
The air passenger dataset is a monthly dataset. We can observe the trend and varying variance simply by eyes.
![Air Passenger Data]()
Applying Box-Cox transformations with different lambdas leads to different results shown below. Drag the \\(\\lambda\\) slider to transform the series yourself: \\(\\lambda = 1\\) only shifts the data, \\(\\lambda = 0\\) is the log transform. The lower panel shows the rolling 12-month standard deviation of the transformed series divided by its average, so a flat line at 1 means the variance no longer grows with the level.
![Box-Cox transformed Air Passenger data]()
To check the variance, we plot out the variance rolling on a 12-month window.
![Air Passenger Var]()
Box-Cox transformation with \\(\\lambda =0.1\\) reduces the variability in variance.
![Box-Cox Air Passenger Var]()
> [!WARNING]
>
> **Box-Cox May not Always Reach Perfect Stationary Data**
>
> Box-Cox transformation is a simple transformation that helps us reduce the non-stationarity and heteroscedasticy. However, we may not always be able to convert the dataset to stationary and homoscedastic data. This can be observed by performing checks using tools such as [`stationarity_tests` in Darts]().
[^/time-series/timeseries-data.box-cox/#scedasticity]: Homoscedasticity and heteroscedasticity. (2023, June 2). In Wikipedia. [https://en.wikipedia.org/wiki/Homoscedasticity\_and\_heteroscedasticity]()
# Two-Way Fixed Effects
> [!NOTE]
>
> **In one minute**
>
> A two-way fixed effects model is a linear model for multivariate time series (panel data) with one effect per series and one per time step. A small constructed example with the prices and demand of three articles shows how it recovers their shared linear relation.
>
> **Read first:** [Time Series Analysis]()
Two-way fixed effects on [panel data]() is a handy method for establishing linear models from time series data. To keep our notations consistent, we will use the term multivariate time series to refer to panel data in the following content.
## Two-way Fixed Effects Model
A two-way fixed effects model is a linear model that allows the parameters to vary across both time and the variables[^/time-series/timeseries-data.analysis.twfe/#bib-Imai2021-kk],
\\\[ y\_{it} = \\beta X\_{it} + \\alpha\_i + \\gamma\_t + \\epsilon\_{it}, \\\]
where \\(\\alpha\_i\\) and \\(\\gamma\_t\\) represent the effect coming from the variable and time, respectively.
## Example
To help readers outside of econometrics or causal inference get started with this model, we will use a simple example to illustrate the idea. We will construct a naive dataset with three groups and two variables linearly related to each other.
We construct a naive dataset that contains three articles (column `name`), each having a different distribution of prices and demand, while all of them are generated with the same linear relation between the variable `log_demand` and `log_price`. The data points also fluctuate in time (column `step`).
Using a simple linear model with both time (`step`) and variable (`name`) fixed effects, we obtain the following results.
```
Estimation: OLS
Dep. var.: log_demand, Fixed effects: name+step
Inference: CRV1
Observations: 1450
| Coefficient | Estimate | Std. Error | t value | Pr(>|t|) | 2.5 % | 97.5 % |
|:--------------|-----------:|-------------:|----------:|-----------:|--------:|---------:|
| log_price | -2.972 | 0.004 | -680.195 | 0.000 | -2.991 | -2.953 |
---
RMSE: 0.003 Adj. R2: 1.0 Adj. R2 Within: 1.0
```
```
pyfixest==0.10.10.0
seaborn==0.13.0
eerily==0.2.1
```
[![Open In Colab]()]()
```
import numpy as np
import pandas as pd
import random
from pyfixest.estimation import feols
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
from eerily.generators.elasticity import ElasticityStepper, LinearElasticityParams
from eerily.generators.naive import (
ConstantStepper,
ConstStepperParams,
SequenceStepper,
SequenceStepperParams,
)
from eerily.generators.utils.choices import Choices
# %% [markdown]
# ## Generate Data
# %%
def create_one_article(
elasticity_value, length, article_id, initial_condition,
log_prices, first_step=0
):
es = ElasticityStepper(
model_params=LinearElasticityParams(
initial_state=initial_condition,
log_prices=iter(log_prices),
elasticity=iter([elasticity_value + (random.random() - 0.5)/10] * length),
variable_names=["log_demand", "log_price", "elasticity"],
),
length=length
)
ss = SequenceStepper(
model_params=SequenceStepperParams(
initial_state=[first_step], variable_names=["step"], step_sizes=[1]
),
length=length
)
cs = ConstantStepper(
model_params=ConstStepperParams(initial_state=[article_id], variable_names=["name"]),
length=length
)
return (es & ss & cs)
initial_condition = {"log_demand": 3, "log_price": 1, "elasticity": None}
length_1 = 200
length_2 = 400
length_3 = 850
log_price_choices_1 = Choices(elements=[1,1.1, 1.2, 1.3, 1.4, 1.5])
log_price_choices_2 = Choices(elements=[1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9])
log_price_choices_3 = Choices(elements=[2, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8])
log_prices_1 = [next(log_price_choices_1) for i in range(length_1)]
log_prices_2 = [next(log_price_choices_2) for i in range(length_2)]
log_prices_3 = [next(log_price_choices_3) for i in range(length_3)]
data_gen = (
create_one_article(elasticity_value=-3, length=length_1, article_id="article_1", initial_condition=initial_condition, log_prices=log_prices_1)
+ create_one_article(elasticity_value=-3, length=length_2, article_id="article_2", initial_condition=initial_condition, log_prices=log_prices_2)
+ create_one_article(elasticity_value=-3, length=length_3, article_id="article_3", initial_condition=initial_condition, log_prices=log_prices_3)
)
# %%
df = pd.DataFrame(list(data_gen))
# %% [markdown]
# ## Visualizations
# %%
fig, ax = plt.subplots(figsize=(10, 6.18))
sns.scatterplot(
df,
x="log_price",
y="log_demand",
hue="step",
style="name"
)
# %% [markdown]
# ## Estimation
# %%
fit_feols = feols(
fml="log_demand ~ log_price | name + step",
data=df
)
# %%
fit_feols.summary()
```
> [!NOTE]
>
> **Tools and Further Reading**
>
> In the R world, [`fixest`]() is a popular package for estimating two-way fixed effects models. In the Python world, we have something similar called [pyfixest]().
[^/time-series/timeseries-data.analysis.twfe/#bib-Imai2021-kk]: Imai K., Kim I.S.. On the use of two-way fixed effects regression models for causal inference with panel data. *Political analysis: an annual publication of the Methodology Section of the American Political Science Association*. 2021. [https://web.mit.edu/insong/www/pdf/FEmatch-twoway.pdf]()
# The Time Delay Embedding Representation
> [!NOTE]
>
> **In one minute**
>
> Time delay embedding, also called rolling, rewrites a series as a table of fixed-length windows: each row holds p consecutive past values and the value to predict next. Neural networks need such fixed-length inputs, and Takens' theorem explains why the representation preserves the dynamics of the original series; the pendulum data illustrates it.
The time delay embedding representation of time series data is widely used in deep learning forecasting models[^/time-series/timeseries-data.time-delayed-embedding/#bib-Hewamalage2022-sc]. This is also called rolling in many time series analyses [^/time-series/timeseries-data.time-delayed-embedding/#bib-Zivot2006-es].
For simplicity, we only write down the representation for a problem with time series \\(y\_{1}, \\cdots, y\_{t}\\), and forecasting \\(y\_{t+1}\\). We rewrite the series into a matrix, in an autoregressive way,
\\\[ \\begin{align} \\mathbf Y = \\begin{bmatrix} y\_1 & y\_2 & \\cdots & y\_p &\\Big| & {\\color{red}y\_{p+1}} \\\\ y\_{1+1} & y\_{1+2} & \\cdots & y\_{1+p} &\\Big| & {\\color{red}y\_{1+p+1}} \\\\ \\vdots & \\vdots & \\ddots & \\vdots &\\Big| & {\\color{red}\\vdots} \\\\ y\_{i-p+1} & y\_{i-p+2} & \\cdots & y\_{i} &\\Big| & {\\color{red}y\_{i+1}} \\\\ \\vdots & \\vdots & \\ddots & \\vdots &\\Big| & {\\color{red}\\vdots} \\\\ y\_{t-p+1} & y\_{t-p+2} & \\cdots & y\_{t} &\\Big| & {\\color{red}y\_{t+1}} \\\\ \\end{bmatrix} \\end{align} \\\]
which indicates that we will use everything on the left, a matrix of shape \\((t-p+1,p)\\), to predict the vector on the right (in red). This is a useful representation when building deep learning models as many of the neural networks require fixed-length inputs.
## Try It: Rolling a Window over a Series
Choose the history length \\(p\\) and the forecast horizon \\(H\\), then step through the rows of the table. Each row is one training example: the blue values are the inputs and the orange values are the targets.
An interactive chart that slides an input window and a target window along a series and shows the resulting rows of the table. It needs JavaScript; the matrix above shows the same construction.
## Taken's Theorem
The reason that time delayed embedding representation is useful is that it is a representation of the original time series that preserves the dynamics of the original time series, if any. The math behind it is the Taken's theorem [^/time-series/timeseries-data.time-delayed-embedding/#bib-Takens1981-kh].
To illustrate the idea, we take our [pendulum dataset]() as an example. The pendulum dataset describes a damped pendulum, for the math and visualizations please refer to [the corresponding page](). Here we apply the time delay embedding representation to the pendulum dataset by setting both the history length and the target length to 1, so that we can better visualize it.
We plot out the delayed embedding representation of the pendulum dataset. The x-axis is the value of the pendulum angle at time \\(t\\), and the y-axis is the value of the pendulum angle at time \\(t+1\\). The animation shows how the delayed embedding representation evolves over time and shows attractor behavior. If a model can capture this dynamics, it can make good predictions.
![Delayed Embedding]()
The notebook for more about the dataset itself is [here]().
````
from functools import cached_property
from typing import List, Tuple
import matplotlib as mpl
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import pandas as pd
from ts_dl_utils.datasets.dataset import DataFrameDataset
from ts_dl_utils.datasets.pendulum import Pendulum
ds_de = DataFrameDataset(dataframe=df["theta"][:200], history_length=1, horizon=1)
class DelayedEmbeddingAnimation:
"""Builds an animation for univariate time series
using delayed embedding.
```python
fig, ax = plt.subplots(figsize=(10, 10))
dea = DelayedEmbeddingAnimation(dataset=ds_de, fig=fig, ax=ax)
ani = dea.build(interval=10, save_count=dea.time_steps)
ani.save("results/pendulum_dataset/delayed_embedding_animation.mp4")
```
:param dataset: a PyTorch dataset, input and target should have only length 1
:param fig: figure object from matplotlib
:param ax: axis object from matplotlib
"""
def __init__(
self, dataset: DataFrameDataset, fig: mpl.figure.Figure, ax: mpl.axes.Axes
):
self.dataset = dataset
self.ax = ax
self.fig = fig
@cached_property
def data(self) -> List[Tuple[float, float]]:
return [(i[0][0], i[1][0]) for i in self.dataset]
@cached_property
def x(self):
return [i[0] for i in self.data]
@cached_property
def y(self):
return [i[1] for i in self.data]
def data_gen(self):
for i in self.data:
yield i
def animation_init(self) -> mpl.axes.Axes:
ax.plot(
self.x,
self.y,
)
ax.set_xlim([-1.1, 1.1])
ax.set_ylim([-1.1, 1.1])
ax.set_xlabel("t")
ax.set_ylabel("t+1")
return self.ax
def animation_run(self, data: Tuple[float, float]) -> mpl.axes.Axes:
x, y = data
self.ax.scatter(x, y)
return self.ax
@cached_property
def time_steps(self):
return len(self.data)
def build(self, interval: int = 10, save_count: int = 10):
return animation.FuncAnimation(
self.fig,
self.animation_run,
self.data_gen,
interval=interval,
init_func=self.animation_init,
save_count=save_count,
)
fig, ax = plt.subplots(figsize=(10, 10))
dea = DelayedEmbeddingAnimation(dataset=ds_de, fig=fig, ax=ax)
ani = dea.build(interval=10, save_count=dea.time_steps)
gif_writer = animation.PillowWriter(fps=5, metadata=dict(artist="Lei Ma"), bitrate=100)
ani.save("results/pendulum_dataset/delayed_embedding_animation.gif", writer=gif_writer)
# ani.save("results/pendulum_dataset/delayed_embedding_animation.mp4")
````
In some advanced deep learning models, delayed embedding plays a crucial role. For example, Large Language Models (LLM) can perform good forecasts by taking in delayed embedding of time series[^/time-series/timeseries-data.time-delayed-embedding/#bib-Rasul2023-ep].
---
**Related:** [Time Series Forecasting Tasks]() · [Time Series Forecasting Evaluation]()
[^/time-series/timeseries-data.time-delayed-embedding/#bib-Hewamalage2022-sc]: Hewamalage H., Ackermann K., Bergmeir C.. Forecast Evaluation for Data Scientists: Common Pitfalls and Best Practices. 2022. [http://arxiv.org/abs/2203.10716]()
[^/time-series/timeseries-data.time-delayed-embedding/#bib-Zivot2006-es]: Zivot E., Wang J.. Modeling Financial Time Series with S-PLUS. *Springer New York*. 2006. [https://link.springer.com/book/10.1007/978-0-387-32348-0]()
[^/time-series/timeseries-data.time-delayed-embedding/#bib-Takens1981-kh]: Takens F.. Detecting strange attractors in turbulence. *Lecture Notes in Mathematics*. 1981. [http://dx.doi.org/10.1007/bfb0091924]()
[^/time-series/timeseries-data.time-delayed-embedding/#bib-Rasul2023-ep]: Rasul K., Ashok A., Williams A.R. et al.. Lag-Llama: Towards foundation models for time series forecasting. *arXiv \[cs.LG\]*. 2023. [http://arxiv.org/abs/2310.08278]()
# Generating Processes for Time Series
> [!NOTE]
>
> **In one minute**
>
> Time series come from many kinds of data generating processes: simple deterministic ones such as exponential growth and circular motion, pure noise, linear processes such as AR, and processes where several series interact. Simulating them builds intuition for modeling real data.
The data generating processes (DGP) for time series are diverse. For example, in physics, we have all sort of dynamical systems that generates time series data and many dynamics models are formulated based on the time series data. In industries, time series data are often coming from stochastic processes.
We present some data generating processes to help us build up intuition when modeling real-world data.
## Simple Examples of DGP
> [!NOTE]
>
> **Exponential Growth**
>
> Exponential growth is a frequently observed natural and economical phenomenon.
>
> \\\[ y = e^{c \\cdot t} \\\]
>
> ![circular motion series]() ![circular motion series]()
> [!NOTE]
>
> **Circular Motion**
>
> The circular motion shows some cyclic patterns.
>
> \\\[ y = \\sin(w \\cdot t) \\\]
>
> ![circular motion series]()
>
> ![circular motion series autocorrelation]()
> [!NOTE]
>
> **Random Gaussian**
>
> Time series can also be noisy Gaussian samples.
>
> ![random gaussian series]() ![random gaussian series]()
## General Linear Processes
A popular model for modeling as well as generating time series is the [autoregressive (AR)]() model. An AR is formulated as
\\\[ x\_t = \\phi\_0 + \\phi\_1 x\_{t-1} + \\epsilon\_t. \\\]
> [!NOTE]
>
> **AR(p) and the Lag Operator**
>
> A general autoregressive model of p-th order is
>
> \\\[ x\_t = \\sum\_l \\phi \_i x\_{t-i} + \\epsilon\_t, \\\]
>
> where \\(l\\) is the lag.
>
> Define a lag operator \\(\\hat L\\) with \\(\\hat L x\_t = x\_{t-1}\\). The definition can also be rewritten using the lag operator
>
> \\\[ x\_t = \\sum\_l \\phi \_i {\\hat L}^i x\_{t} + \\epsilon\_t. \\\]
We write down each time step in the following table.
| \\(t\\) | \\(x\_t\\) |
| :---: | :---: |
| 0 | \\(y\_0\\) |
| 1 | \\(\\phi\_0 + \\phi\_1 y\_0 + \\epsilon\_1\\) |
| 2 | \\(\\phi\_0 + \\phi\_1 (\\phi\_0 + \\phi\_1 y\_0 + \\epsilon\_1) + \\epsilon\_2 = \\phi\_0 (1 + \\phi\_1) + \\phi\_1^2 y\_0 + \\phi\_1\\epsilon\_1 + \\epsilon\_2\\) |
| 3 | \\(\\phi\_0 + \\phi\_1 (\\phi\_0 + \\phi\_1\\phi\_0 + \\phi\_1^2 y\_0 + \\phi\_1\\epsilon\_1 + \\epsilon\_2) + \\epsilon\_3 = \\phi\_0(1 + \\phi\_1 + \\phi\_1^2) + \\phi\_1^3 y\_0 + \\phi\_1^2\\epsilon\_1 + \\phi\_1\\epsilon\_2 + \\epsilon\_3\\) |
| ... | ... |
| \\(t\\) | \\(\\phi\_0 \\sum\_{i=0}^{t-1} \\phi\_1^i + \\phi\_1^t y\_0 + \\sum\_{i=1}^{t-1} \\phi\_1^{t-i} \\epsilon\_{i}\\) |
We have found a new formula for AR(1), i.e.
\\\[ x\_t = \\phi\_0 \\sum\_{i=0}^{t-1} \\phi\_1^i + \\phi\_1^t y\_0 + \\sum\_{i=1}^{t-1} \\phi\_1^{t-i} \\epsilon\_{i}, \\\]
which is very similar to a general linear process[^/time-series/timeseries-datasets.dgp/#Das2019]
\\\[ x\_t - \\mu = \\sum\_{i=0}^\\tau \\alpha\_i \\epsilon\_{t-i}. \\\]
The general linear process is the Taylor expansion of an arbitrary DGP \\(x\_t = \\operatorname{DGP}(\\epsilon\_t, ...)\\)[^/time-series/timeseries-datasets.dgp/#Das2019].
## Interactions between Series
The interactions between the series can be modeled as explicit interactions, e.g., many spiking neurons, or through hidden variables, e.g., hidden state model[^/time-series/timeseries-datasets.dgp/#hmm]. Among these models, [Vector Autoregressive model, aka VAR,]() is a simple but popular model.
---
**Related:** [AR]() · [VAR]() · [Time Series Data Generating Process: Langevin Equation]()
[^/time-series/timeseries-datasets.dgp/#Das2019]: Das P. Econometrics in Theory and Practice. Springer Nature Singapore; [doi:10.1007/978-981-32-9019-8]()
[^/time-series/timeseries-datasets.dgp/#hmm]: Contributors to Wikimedia projects. Hidden Markov model. In: Wikipedia \[Internet\]. 22 Oct 2022 \[cited 22 Nov 2022\]. Available: [https://en.wikipedia.org/wiki/Hidden\_Markov\_model]()
# Time Series Data Generating Process: Langevin Equation
> [!NOTE]
>
> **In one minute**
>
> The Langevin equation describes Brownian motion: a velocity that decays exponentially while a random force keeps kicking it. Discretizing the equation gives a simple recipe for simulating a stochastic time series.
>
> **Read first:** [Generating Processes for Time Series]()
Among the many data generating processes (DGP), the Langevin equation is one of the most interesting DGP.
## Brownian Motion
Brownian motion as a very simple stochastic process can be described by the Langevin equation[^/time-series/timeseries-datasets.dgp.langevin/#ma-sp]. In this section, we simulate a time series dataset from Brownian motion.
Macroscopically, Brownian Motion can be described by the notion of random forces on the particles,
\\\[ \\frac{d}{dt} v(t) + \\gamma v(t) = R(t), \\\]
where \\(v(t)\\) is the velocity at time \\(t\\) and \\(R(t)\\) is the stochastic force density from the reservoir particles. Solving the equation, we get
\\\[ v(t) = v(0)e^{-\\gamma t} + \\int\_0^t dt' e^{-\\gamma (t-t')} R(t') . \\\]
To generate a dataset numerically, we discretize it by replacing the integral with a sum,
\\\[ v(t) = v(0) e^{-\\gamma t} + \\sum\_{n=0}^N \\Delta t e^{-\\gamma (t - t\_n)} R(t\_n) \\\]
where \\(t\_i = i \* \\Delta t\\) and \\(t = t\_n\\), thus the equation is further simplified,
\\\[ v(N\\Delta t) = v(0) e^{-\\gamma N\\Delta t} + \\sum\_{n=0}^N e^{-\\gamma (N - n)\\Delta t} R(n\\Delta t) \\Delta t. \\\]
The first term in the solution is responsible for the exponential decay and the second term calculates the effect of the stochastic force.
To simulate a Brownian motion, we can either use the formal solution or the differential equation itself. Here we choose to use the differential equation itself. To simulate the process numerically, we rewrite
\\\[ \\frac{d}{dt} v(t) + \\gamma v(t) = R(t), \\\]
as
\\\[ \\Delta v (t+1) = R(t) \\Delta t - \\gamma v(t) \\Delta t. \\\]
The following is a simulated 1D Brownian motion.
![Brownian Motion example]()
We create a stepper to calculate the next steps.
```
import numpy as np
import copy
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
## Define Brownian Motion
class GaussianForce:
"""A Gaussian stochastic force iterator.
Each iteration returns a single sample from the corresponding
Gaussian distribution.
:param mu: mean of the Gaussian distribution
:param std: standard deviation of the Gaussian distribution
:param seed: seed for the random generator
"""
def __init__(self, mu: float, std: float, seed: Optional[float] = None):
self.mu = mu
self.std = std
self.rng = np.random.default_rng(seed=seed)
def __next__(self) -> float:
return self.rng.normal(self.mu, self.std)
class BrownianMotionStepper:
"""Calculates the next step in a brownian motion.
:param gamma: the damping factor $\gamma$ of the Brownian motion.
:param delta_t: the minimum time step $\Delta t$.
:param force_densities: the stochastic force densities, e.g. [`GaussianForce`][eerily.data.generators.brownian.GaussianForce].
:param initial_state: the initial velocity $v(0)$.
"""
def __init__(
self,
gamma: float,
delta_t: float,
force_densities: Iterator,
initial_state: Dict[str, float],
):
self.gamma = gamma
self.delta_t = delta_t
self.forece_densities = copy.deepcopy(force_densities)
self.current_state = copy.deepcopy(initial_state)
def __iter__(self):
return self
def __next__(self) -> Dict[str, float]:
force_density = next(self.forece_densities)
v_current = self.current_state["v"]
v_next = v_current + force_density * self.delta_t - self.gamma * v_current * self.delta_t
self.current_state["force_density"] = force_density
self.current_state["v"] = v_next
return copy.deepcopy(self.current_state)
## Generating time series
delta_t = 0.1
stepper = BrownianMotionStepper(
gamma=0,
delta_t=delta_t,
force_densities=GaussianForece(mu=0, std=1),
initial_state={"v": 0},
)
length = 200
history = []
for _ in range(length):
history.append(next(stepper))
df = pd.DataFrame(history)
fig, ax = plt.subplots(figsize=(10, 6.18))
sns.lineplot(
x=np.linspace(0, length-1, length) * delta_t,
y=df.v,
ax=ax,
marker="o",
)
ax.set_title("Brownian Motion")
ax.set_xlabel("Time")
ax.set_ylabel("Velocity")
```
[^/time-series/timeseries-datasets.dgp.langevin/#ma-sp]: Ma L. Brownian Motion — Statistical Physics Notes. In: Statistical Physics \[Internet\]. \[cited 17 Nov 2022\]. Available: [https://statisticalphysics.leima.is/nonequilibrium/brownian-motion.html]()
# Statistical Models of Time Series
> [!NOTE]
>
> **In one minute**
>
> A short tour of classical statistical forecasting models: ARIMA and how its components relate, simple exponential smoothing, which averages the latest observation with the previous forecast so that older history fades exponentially, and state space models.
Though statistical models are not our focus, it is always beneficial to understand how those famous statistical models work. To best understand how the models work, we will build some data generating process using these models and explore their behavior.
In the following paragraphs, we list some of the most applied statistical models. For a comprehensive review of statistical models, please refer to Petropoulos et al., 2022 and Hyndman et al., 2021[^/time-series/timeseries-basics.statistical-models/#Petropoulos2022][^/time-series/timeseries-basics.statistical-models/#Hyndman2021].
## ARIMA
ARIMA is one of the most famous forecasting models[^/time-series/timeseries-basics.statistical-models/#Cerqueira2019]. We will not discuss the details of the model. However, for reference, we sketch the relations between the different components of the ARIMA model in the following chart.
```
flowchart TD
AR --"interdependencies"--> VAR
MA --"add autoregressive"--> ARMA
AR --"add moving average"--> ARMA
ARMA --"difference between values"--> ARIMA
ARMA --"interdependencies"--> VARMA
VAR --"moving average"--> VARMA
ARIMA --"interdependencies"--> VARIMA
VAR --"difference and moving average"--> VARIMA
VARMA --"difference"--> VARIMA
```
## Exponential Smoothing
> [!NOTE]
>
> **A Naive Forecast**
>
> In time series forecasting, one of the naive forecasts we can use it the previous observation, i.e.,
>
> \\\[ \\hat s(t+1) = s(t), \\\]
>
> where we use \\(\\hat s\\) to denote the forecasts and \\(s\\) for the observations.
A naive version of the exponential smoothing model is the Simple Exponential Smoothing (SES)[^/time-series/timeseries-basics.statistical-models/#Petropoulos2022][^/time-series/timeseries-basics.statistical-models/#Hyndman2021]. The SES is an average of the most recent observation and the previous forecasts.
\\\[ \\hat s(t+1) = \\alpha s(t) + (1-\\alpha) \\hat s(t), \\\]
where \\(\\hat s\\) is the forecast and \\(s\\) is the observation. Expanding this form, we observe the exponential decaying effect of history in the long past[^/time-series/timeseries-basics.statistical-models/#Hyndman2021].
## State Space Models
State space models (SSM) are amazing models due to their simplicity. SSM applies Markov chains but is not limited to the Markovian assumptions[^/time-series/timeseries-basics.statistical-models/#Bishop2006].
---
**Related:** [AR]() · [VAR]() · [Naive Forecasts]()
[^/time-series/timeseries-basics.statistical-models/#Cerqueira2019]: Cerqueira V, Torgo L, Soares C. Machine Learning vs Statistical Methods for Time Series Forecasting: Size Matters. arXiv \[stat.ML\]. 2019. Available: [http://arxiv.org/abs/1909.13316]()
[^/time-series/timeseries-basics.statistical-models/#wu2020]: Wu Z, Pan S, Long G, Jiang J, Chang X, Zhang C. Connecting the Dots: Multivariate Time Series Forecasting with Graph Neural Networks. arXiv \[cs.LG\]. 2020. Available: [http://arxiv.org/abs/2005.11650]()
[^/time-series/timeseries-basics.statistical-models/#Petropoulos2022]: Petropoulos F, Apiletti D, Assimakopoulos V, Babai MZ, Barrow DK, Ben Taieb S, et al. Forecasting: theory and practice. Int J Forecast. 2022;38: 705–871. doi:10.1016/j.ijforecast.2021.11.001
[^/time-series/timeseries-basics.statistical-models/#Hyndman2021]: Hyndman, R.J., & Athanasopoulos, G. (2021) Forecasting: principles and practice, 3rd edition, OTexts: Melbourne, Australia. OTexts.com/fpp3. Accessed on 2022-11-27.
[^/time-series/timeseries-basics.statistical-models/#Bishop2006]: Bishop CM. Pattern Recognition and Machine Learning. Springer; 2006. Available: [https://play.google.com/store/books/details?id=qWPwnQEACAAJ]()
# AR
> [!NOTE]
>
> **In one minute**
>
> An autoregressive model predicts the next value from a weighted sum of previous values plus noise. Depending on its coefficients, an AR(1) process hovers around a constant, decays or grows exponentially; the AR(2) playground shows when a process stays stationary.
>
> **Read first:** [Time Series Analysis]()
Autoregressive (AR) models are simple models to model time series. A general AR(p) model is described by the following process:
\\\[ s(t) = \\phi\_0 + \\sum\_{i=1}^p \\phi\_i s(t-i) + \\epsilon. \\\]
## AR(1)
A first order AR model, aka AR(1), is as simple as
\\\[ s(t) = \\phi\_0 + \\phi\_1 s(t-1) + \\epsilon. \\\]
By staring at this equation, we can build up our intuitions.
| \\(\\phi\_0\\) | \\(\\phi\_1\\) | \\(\\epsilon\\) | Behavior |
| :---: | :---: | :---: | :---: |
| \- | \\(0\\) | \- | constant + noise |
| \\(0\\) | \\(1\\) | \- | constant + noise |
| \\(0\\) | \\(\\phi\_1\>1\\) or \\(0\\le\\phi\_1 \\lt 1\\) | \- | exponential + noise |
> [!NOTE]
>
> **Exponential Behavior doesn't Always Approach Positive Infinity**
>
> For example, the combination \\(\\phi\_0=0\\) and \\(\\phi\_1\>1\\) without noise leads to exponential growth if the initial series value is positive. However, it approaches negative infinity if the initial series is negative.
![]()
![Decay]()
![]()
![]()
```
import copy
from dataclasses import dataclass
from typing import Dict, Iterator
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns; sns.set()
class GaussianEpsilon:
"""Gaussian noise
:param mu: mean value of the noise
:param std: standard deviation of the noise
"""
def __init__(self, mu, std, seed=None):
self.mu = mu
self.std = std
self.rng = np.random.default_rng(seed=seed)
def __next__(self):
return self.rng.normal(self.mu, self.std)
class ZeroEpsilon:
"""Constant noise
:param epsilon: the constant value to be returned
"""
def __init__(self, epsilon=0):
self.epsilon = epsilon
def __next__(self):
return self.epsilon
@dataclass(frozen=True)
class ARModelParams:
"""Parameters of our AR model,
$$s(t+1) = \phi_0 + \phi_1 s(t) + \epsilon.$$
:param delta_t: step size of time in each iteration
:param phi0: pho_0 in the AR model
:param phi1: pho_1 in the AR model
:param epsilon: noise iterator, e.g., Gaussian noise
:param initial_state: a dictionary of the initial state, e.g., `{"s": 1}`
"""
delta_t: float
phi0: float
phi1: float
epsilon: Iterator
initial_state: Dict[str, float]
class AR1Stepper:
"""Stepper that calculates the next step in time in an AR model
:param model_params: parameters for the AR model
"""
def __init__(self, model_params):
self.model_params = model_params
self.current_state = copy.deepcopy(self.model_params.initial_state)
def __iter__(self):
return self
def __next__(self):
phi0 = self.model_params.phi0
phi1 = self.model_params.phi1
epsilon = next(self.model_params.epsilon)
next_s = (
self.model_params.phi0
+ self.model_params.phi1 * self.current_state["s"]
+ epsilon
)
self.current_state = {"s": next_s}
return copy.deepcopy(self.current_state)
def visualize_vr1(delta_t, phi0, phi1, length=200, savefig=False):
mu = 0
std = 0.1
geps = GaussianEpsilon(mu=mu, std=std)
zeps = ZeroEpsilon()
initial_state = {"s": -1}
ar1_params = ARModelParams(
delta_t=delta_t, phi0=phi0, phi1=phi1, epsilon=geps, initial_state=initial_state
)
ar1_params_zero_noise = ARModelParams(
delta_t=delta_t, phi0=phi0, phi1=phi1, epsilon=zeps, initial_state=initial_state
)
ar1_stepper = AR1Stepper(model_params=ar1_params)
ar1_stepper_no_noise = AR1Stepper(model_params=ar1_params_zero_noise)
history = []
history_zero_noise = []
for l in range(length):
history.append(next(ar1_stepper))
history_zero_noise.append(next(ar1_stepper_no_noise))
df = pd.DataFrame(history)
df_zero_noise = pd.DataFrame(history_zero_noise)
fig, ax = plt.subplots(figsize=(10, 6.18))
sns.lineplot(
x=np.linspace(0, length - 1, length) * delta_t,
y=df.s,
ax=ax,
marker=".",
label="AR1",
color="r",
alpha=0.9,
)
sns.lineplot(
x=np.linspace(0, length - 1, length) * delta_t,
y=df_zero_noise.s,
ax=ax,
marker=".",
label="AR1 (wihout Noise)",
color="g",
alpha=0.5,
)
ax.set_title(
f"AR(1) Example ($\phi_0={phi0}$, $\phi_1={phi1}$; $\epsilon$: $\mu={mu}$, $\sigma={std}$; $s(0)={initial_state['s']}$)"
)
ax.set_xlabel("Time")
ax.set_ylabel("Values")
if savefig:
plt.savefig(
f"/work/timeseries-dgp-ar-var/exports/ar1-phi0-{phi0}-phi1-{phi1}-std-{std}-init-{initial_state['s']}.png"
)
```
Call the function `visualize_vr1` to make some plots.
```
visualize_vr1(delta_t = 0.01, phi0 = 0, phi1 = 1.1, length = 200, savefig=True)
```
## Play with it
The playground below adds one more lag, \\(s(t) = \\phi\_0 + \\phi\_1 s(t-1) + \\phi\_2 s(t-2) + \\epsilon\\), and plots the series, its sample ACF, and where \\((\\phi\_1, \\phi\_2)\\) sits relative to the stationarity triangle. Start from the *Damped* preset and push \\(\\phi\_1\\) up until the dot leaves the triangle: at which value does the series stop returning to its mean, and what happens to the ACF? Then try *Oscillating* and find the edge where the cycles stop dying out.
The playground is a [marimo notebook](). From a clone of the repository, run it with `uvx marimo run --sandbox playgrounds/ar.py`.
---
**Related:** [VAR]() · [Generating Processes for Time Series]()
[^/time-series/timeseries-basics.ar/#Kumar2022]: Kumar A. Autoregressive (AR) models with Python examples. In: Data Analytics \[Internet\]. 25 Apr 2022 \[cited 11 Aug 2022\]. Available: [https://vitalflux.com/autoregressive-ar-models-with-python-examples/]()
# VAR
> [!NOTE]
>
> **In one minute**
>
> A vector autoregressive model extends AR to several series that influence each other: the next value of each series depends on the previous values of all of them. A VAR(1) blows up when the largest eigenvalue of its coefficient matrix exceeds 1 and stays stable otherwise.
>
> **Read first:** [AR]()
## VAR(1)
VAR(1) is similar to [AR(1)]() but models time series with interactions between the series. For example, a two-dimensional VAR(1) model is
\\\[ \\begin{pmatrix}s^{(1)}(t+1) \\\\ s^{(2)}(t+1) \\end{pmatrix} = \\begin{pmatrix} \\phi^{(1)}\_0 \\\\ \\phi^{(2)}\_0 \\end{pmatrix} + \\begin{pmatrix}\\phi\_{1, 11} & \\phi\_{1, 12}\\\\ \\phi\_{1, 21} & \\phi\_{1, 22} \\end{pmatrix} \\begin{pmatrix}s^{(1)}(t) \\\\ s^{(2)}(t) \\end{pmatrix} + \\begin{pmatrix}\\epsilon^{(1)} \\\\ \\epsilon^{(2)} \\end{pmatrix}. \\\]
A more compact form is
\\\[ \\mathbf s (t+1) = \\boldsymbol \\phi\_0 + \\boldsymbol \\phi\_1 \\mathbf s(t) + \\boldsymbol \\epsilon. \\\]
> [!NOTE]
>
> **Stability of VAR**
>
> For VAR(1), our series blows up when the max eigenvalue of the matrix \\(\\boldsymbol \\phi\_1\\) is large than 1[^/time-series/timeseries-basics.var/#Zvot2006]. Otherwise, we get stable series.
>
> In the following examples, we denote the largest eigenvalue of \\(\\boldsymbol \\phi\_1\\) as \\(\\lambda\_0\\).
![VAR(1) stable]()
The figure is created using the code from the "Python Code" tab, and the following parameters.
```
var_params_stable = VAR1ModelParams(
delta_t = 0.01,
phi0 = np.array([0.1, 0.1]),
phi1 = np.array([
[0.5, -0.25],
[-0.35, 0.45+0.2]
]),
epsilon = ConstantEpsilon(epsilon=np.array([0,0])),
initial_state = np.array([1, 0])
)
var1_visualize(var_params=var_params_stable)
```
![VAR(1) example]()
The figure is created using the code from the "Python Code" tab, and the following parameters.
```
var_params_unstable = VAR1ModelParams(
delta_t = 0.01,
phi0 = np.array([0.1, 0.1]),
phi1 = np.array([
[0.5, -0.25],
[-0.35, 0.45+0.5]
]),
epsilon = ConstantEpsilon(epsilon=np.array([0,0])),
initial_state = np.array([1, 0])
)
var1_visualize(var_params=var_params_unstable)
```
![VAR(1) example]()
The figure is created using the code from the "Python Code" tab, and the following parameters.
```
var_params_no_noise = VAR1ModelParams(
delta_t = 0.01,
phi0 = np.array([-1, 1]),
phi1 = np.array([
[0.7, 0.2],
[0.2, 0.7]
]),
epsilon = ConstantEpsilon(epsilon=np.array([0,0])),
initial_state = np.array([1, 0])
)
var1_visualize(var_params=var_params_no_noise)
```
![VAR(1) example]()
The figure is created using the code from the "Python Code" tab, and the following parameters.
```
var_params_zero_mean_noise = VAR1ModelParams(
delta_t = 0.01,
phi0 = np.array([-1, 1]),
phi1 = np.array([
[0.7, 0.2],
[0.2, 0.7]
]),
epsilon = MultiGaussianNoise(mu=np.array([0, 0]), cov=np.array([[1, 0.5],[0.5, 1]])),
initial_state = np.array([1, 0])
)
var1_visualize(var_params=var_params_zero_mean_noise)
```
![VAR(1) example]()
The figure is created using the code from the "Python Code" tab, and the following parameters.
```
var_params_nonzero_mean_noise = VAR1ModelParams(
delta_t = 0.01,
phi0 = np.array([-1, 1]),
phi1 = np.array([
[0.7, 0.2],
[0.2, 0.7]
]),
epsilon = MultiGaussianNoise(mu=np.array([1, 2]), cov=np.array([[1, 0.5],[0.5, 1]])),
initial_state = np.array([1, 0])
)
var1_visualize(var_params=var_params_nonzero_mean_noise)
```
```
import copy
from dataclasses import dataclass
from typing import Iterator
import numpy as np
class MultiGaussianNoise:
"""A multivariate Gaussian noise
:param mu: means of the variables
:param cov: covariance of the variables
:param seed: seed of the random number generator for reproducibility
"""
def __init__(self, mu: np.ndarray, cov: np.ndarray, seed: Optional[float] = None):
self.mu = mu
self.cov = cov
self.rng = np.random.default_rng(seed=seed)
def __next__(self) -> np.ndarray:
return self.rng.multivariate_normal(self.mu, self.cov)
class ConstantEpsilon:
"""Constant noise
:param epsilon: the constant value to be returned
"""
def __init__(self, epsilon=0):
self.epsilon = epsilon
def __next__(self):
return self.epsilon
@dataclass(frozen=True)
class VAR1ModelParams:
"""Parameters of our VAR model,
:param delta_t: step size of time in each iteration
:param phi0: pho_0 in the AR model
:param phi1: pho_1 in the AR model
:param epsilon: noise iterator, e.g., Gaussian noise
:param initial_state: a dictionary of the initial state, e.g., `{"s": 1}`
"""
delta_t: float
phi0: np.ndarray
phi1: np.ndarray
epsilon: Iterator
initial_state: np.ndarray
class VAR1Stepper:
"""Calculate the next values using VAR(1) model.
:param model_params: the parameters of the VAR(1) model, e.g.,
[`VAR1ModelParams`][eerily.data.generators.var.VAR1ModelParams]
"""
def __init__(self, model_params):
self.model_params = model_params
self.current_state = copy.deepcopy(self.model_params.initial_state)
def __iter__(self):
return self
def __next__(self):
epsilon = next(self.model_params.epsilon)
phi0 = self.model_params.phi0
phi1 = self.model_params.phi1
self.current_state = phi0 + np.matmul(phi1, self.current_state) + epsilon
return copy.deepcopy(self.current_state)
class Factory:
"""A generator that creates the data points based on the stepper."""
def __init__(self):
pass
def __call__(self, stepper, length):
i = 0
while i < length:
yield next(stepper)
i += 1
```
We create a function to visualize the series.
```
def var1_visualize(var_params):
phi1_eig_max = max(np.linalg.eig(var_params.phi1)[0])
var1_stepper = VAR1Stepper(model_params=var_params)
length = 200
fact = Factory()
history = list(fact(var1_stepper, length=length))
df = pd.DataFrame(history, columns=["s1", "s2"])
print(df.head())
fig, ax = plt.subplots(figsize=(10, 6.18))
sns.lineplot(
x=np.linspace(0, length-1, length) * var_params.delta_t,
y=df.s1,
ax=ax,
marker="o",
)
sns.lineplot(
x=np.linspace(0, length-1, length) * var_params.delta_t,
y=df.s2,
ax=ax,
marker="o",
)
ax.set_title(f"VAR(1) Example ($\lambda_0={phi1_eig_max:0.2f}$)")
ax.set_xlabel("Time")
ax.set_ylabel("Values")
```
[^/time-series/timeseries-basics.var/#Zvot2006]: Zivot E, Wang J. Modeling Financial Time Series with S-PLUS®. Springer New York; 2006. [doi:10.1007/978-0-387-32348-0]()
# Synthetic Time Series
> [!NOTE]
>
> **In one minute**
>
> Synthetic time series serve three purposes: benchmarking models on data whose dynamics are known, improving models through augmentation or transfer learning, and sharing data without exposing private or business information. Generating realistic series is hard, though generic generators such as GANs exist.
Synthetic time series data is useful in time series modeling, such as forecasting.
Real world time series data often comes with complex dynamics in the [data generating process](). Benchmarking models using real world data often doesn't reflect the special designs in forecasting models. Synthetic time series data provides a good playground for benchmarking models as it can provide useful insights.
Another application of synthetic data is to improve model performance. Synthetic data can be used to [augment the training data]()[^/time-series/timeseries-synthetic/#Bandara2020] as well as in transfer learning[^/time-series/timeseries-synthetic/#Rotem2022].
A third application of synthetic data is data sharing without compromising privacy and business secrets[^/time-series/timeseries-synthetic/#Lin2019].
Though useful, synthesizing proper artificial time series data can be very complicated as there are an enormous amount of diverse theories associated with time series data. On the other hand, many time series generators are quite universal. For example, GAN can be used to generate realistic time series[^/time-series/timeseries-synthetic/#Leznik2021].
In this chapter, we will explain the basic ideas and demonstrate our generic programming framework for synthetic time series. With the basics explored, we will focus on a special case of synthetic time series: time series with interactions.
---
**Related:** [Generating Processes for Time Series]() · [Data Augmentation for Time Series]() · [Synthetic Time Series]()
[^/time-series/timeseries-synthetic/#Rotem2022]: Rotem Y, Shimoni N, Rokach L, Shapira B. Transfer learning for time series classification using synthetic data generation. arXiv \[cs.LG\]. 2022. Available: [http://arxiv.org/abs/2207.07897]()
[^/time-series/timeseries-synthetic/#Bandara2020]: Bandara K, Hewamalage H, Liu Y-H, Kang Y, Bergmeir C. Improving the Accuracy of Global Forecasting Models using Time Series Data Augmentation. arXiv \[cs.LG\]. 2020. Available: [http://arxiv.org/abs/2008.02663]()
[^/time-series/timeseries-synthetic/#Lin2019]: Lin Z, Jain A, Wang C, Fanti G, Sekar V. Using GANs for Sharing Networked Time Series Data: Challenges, Initial Promise, and Open Questions. arXiv \[cs.LG\]. 2019. Available: [http://arxiv.org/abs/1909.13403]()
[^/time-series/timeseries-synthetic/#Leznik2021]: Leznik M, Michalsky P, Willis P, Schanzel B, Östberg P-O, Domaschka J. Multivariate Time Series Synthesis Using Generative Adversarial Networks. Proceedings of the ACM/SPEC International Conference on Performance Engineering. New York, NY, USA: Association for Computing Machinery; 2021. pp. 43–50. doi:10.1145/3427921.3450257
# Synthetic Time Series
> [!NOTE]
>
> **In one minute**
>
> How to generate synthetic series in code with the recipe-based generator in GluonTS, from random Gaussian noise to multivariate recipes.
>
> **Read first:** [Generating Processes for Time Series]()
With a proper understanding of the [DGP](), we can build data generators around the DGP we choose.
## GluonTS
[GluonTS]() is a python package for probabilistic time series modeling. It comes with a simple yet easy-to-use synthetic data generator. For example, to generate a time series of random Gaussian, we only need the following code[^/time-series/timeseries-datasets.synthetic/#gluonts-synth].
```
from gluonts.dataset.artificial import recipe as rcp
g_rg = rcp.RandomGaussian(stddev=2)
g_rp_series = rcp.evaluate(g_rg, 100)
```
For more complicated multivariate time series, we create recipes for our variables. We steal the example in the [GluonTS]() tutorial.
```
from gluonts.dataset.artificial import recipe as rcp
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
daily_smooth_seasonality = rcp.SmoothSeasonality(period=288, phase=-72)
noise = rcp.RandomGaussian(stddev=0.1)
signal = daily_smooth_seasonality + noise
recipe = dict(
daily_smooth_seasonality=daily_smooth_seasonality, noise=noise, signal=signal
)
rec_eval = rcp.evaluate(recipe, 500)
fig, ax = plt.subplots(figsize=(10, 6.18))
sns.lineplot(rec_eval)
```
![gluonts example]()
[^/time-series/timeseries-datasets.synthetic/#gluonts-synth]: Synthetic data generation. In: GluonTS documentation \[Internet\]. \[cited 13 Nov 2022\]. Available: [https://ts.gluon.ai/stable/tutorials/data\_manipulation/synthetic\_data\_generation.html]()
# Data Augmentation for Time Series
> [!NOTE]
>
> **In one minute**
>
> Real datasets are often too small or too imbalanced to train deep models well. Augmentation creates extra training series by random transformations such as jittering, by mixing patterns from several series (for example DBA), or with generative models from AR to GANs. The page then covers how to use the synthetic data in training.
In deep learning, our dataset should help the optimization mechanism locate a good spot in the parameter space. However, real-world data is not necessarily diverse enough that covers the required situations with enough records. For example, some datasets may be extremely imbalanced class labels which leads to poor performance in classification tasks [^/time-series/timeseries-data.data-augmentation/#bib-Hasibi2019-in]. Another problem with a limited dataset is that the trained model may not generalize well [^/time-series/timeseries-data.data-augmentation/#bib-Iwana2020-oc][^/time-series/timeseries-data.data-augmentation/#bib-Shorten2019-ty].
We will cover two topics in this section: Augmenting the dataset and application of the augmented data to model training.
## Augmenting the Dataset
There are many different ways of augmenting time series data [^/time-series/timeseries-data.data-augmentation/#bib-Iwana2020-oc][^/time-series/timeseries-data.data-augmentation/#bib-Wen2020-ez]. We categorize the methods into the following groups:
- Random transformations, e.g., jittering;
- Pattern mixing, e.g., DBA;[^/time-series/timeseries-data.data-augmentation/#bib-Petitjean2011-sj]
- Generative models, e.g.,
- phenomenological generative models such as AR [^/time-series/timeseries-data.data-augmentation/#bib-Kang2019-cl],
- first principle models such as economical models [^/time-series/timeseries-data.data-augmentation/#bib-Stock2016-mh],
- deep generative models such as TimeGAN or TS GAN [^/time-series/timeseries-data.data-augmentation/#bib-Yoon_undated-gs][^/time-series/timeseries-data.data-augmentation/#bib-Brophy2021-vn].
We also treat the first two methods, random transformations and pattern mixing as basic methods.
### Basic Methods
In the following table, we group some of the data augmentation methods by two dimensions, the category of the method, and the domain of where the method is applied.
| | Projected Domain | Time Scale | Magnitude |
| --- | --- | --- | --- |
| Random Transformation | Frequency Masking, Frequency Warping, Fourier Transform, STFT | Permutation, Slicing, Time Warping, Time Masking, Cropping | Jittering, Flipping, Scaling, Magnitude Warping |
| Pattern Mixing | EMDA[^/time-series/timeseries-data.data-augmentation/#bib-Takahashi2017-yz], SFM[^/time-series/timeseries-data.data-augmentation/#bib-Cui2014-de] | Guided Warping[^/time-series/timeseries-data.data-augmentation/#bib-Iwana2020-fe] | DFM[^/time-series/timeseries-data.data-augmentation/#bib-Stock2016-mh], Interpolation, DBA[^/time-series/timeseries-data.data-augmentation/#bib-Petitjean2011-sj] |
For completeness, we will explain some of the methods in more detail in the following.
#### Perturbation in Fourier Domain
In the Fourier domain, for each the amplitude \\(A\_f\\) and phase \\(\\phi\_f\\) at a specific frequency, we can perform[^/time-series/timeseries-data.data-augmentation/#bib-Gao2020-qr]
- magnitude replacement using a Gaussian distribution, and
- phase shift by adding Gaussian noise.
We perform such perturbations at some chosen frequency.
#### Slicing, Permutation, and Bootstrapping
We can slice a series into small segments. With the slices, we can perform different operations to create new series.
- Window Slicing (**WS**): In a classification task, we can take the slices from the original series and assign the same class label to the slice [^/time-series/timeseries-data.data-augmentation/#bib-Le_Guennec2016-zi]. The slices can also be interpolated to match the length of the original series [^/time-series/timeseries-data.data-augmentation/#bib-Iwana2020-oc].
- Permutation: We take the slices and permute them to form a new series [^/time-series/timeseries-data.data-augmentation/#bib-Um2017-oq].
- Moving Block Bootstrapping (**MBB**): First, we remove the trend and seasonability. Then we draw blocks of fixed length from the residual of the series until the desired length of the series is met. Finally, we combine the newly formed residual with trend and seasonality to form a new series [^/time-series/timeseries-data.data-augmentation/#bib-Bergmeir2016-eh].
#### Warping
Both the time scale and magnitude can be warped. For example,
- Time Warping: We distort time intervals by taking a range of data points and upsample or downsample it [^/time-series/timeseries-data.data-augmentation/#bib-Wen2020-ez].
- Magnitude Warping: the magnitude of the time series is rescaled.
> [!NOTE]
>
> **Dynamic Time Warping (**DTW**)**
>
> Given two sequences, \\(S^{(1)}\\) and \\(S^{(2)}\\), the Dynamic Time Warping (**DTW**) algorithm finds the best way to align two sequences. During this alignment process, we quantify the misalignment using a distance similar to the Levenshtein distance, where the distance between two series \\(S^{(1)}\_{1:i}\\) (with \\(i\\) elements) and \\(S^{(2)}\_{1:j}\\) (with \\(j\\) elements) is[^/time-series/timeseries-data.data-augmentation/#bib-Petitjean2011-sj]
>
> \\\[ \\begin{align} D(S^{(1)}\_{1:i}, S^{(2)}\_{1:j}) =& d(S^{(1)}\_i, S^{(2)}\_j)\\\\ & + \\operatorname{min}\\left\[ D(S^{(1)}\_{1:i-1}, S^{(2)}\_{1:j-1}), D(S^{(1)}\_{1:i}, S^{(2)}\_{1:j-1}), D(S^{(1)}\_{1:i-1}, S^{(2)}\_{1:j}) \\right\], \\end{align} \\\]
>
> where \\(S^{(1)}\_i\\) is the \\(i\\)the element of the series \\(S^{(1)}\\), \\(d(x,y)\\) is a predetermined distance, e.g., Euclidean distance. This definition reveals the recursive nature of the DTW distance.
>
> > **Notations in the Definition: \\(S\_{1:i}\\) and \\(S\_{i}\\)**
> >
> > The notation \\(S\_{1:i}\\) stands for a series that contains the elements starting from the first to the \\(i\\)th in series \\(S\\). For example, we have a series
> >
> > \\\[ S^1 = \[s^1\_1, s^1\_2, s^1\_3, s^1\_4, s^1\_5, s^1\_6\]. \\\]
> >
> > The notation \\(S^1\_{1:4}\\) represents
> >
> > \\\[ S^1\_{1:4} = \[s^1\_1, s^1\_2, s^1\_3, s^1\_4\]. \\\]
> >
> > The notation \\(S\_i\\) indicates the \\(i\\)th element in \\(S\\). For example,
> >
> > \\\[ S^1\_4 = s^1\_4. \\\]
> >
> > If we map these two notations to Python,
> >
> > - \\(S\_{1:i}\\) is equivalent to `S[0:i]`, and
> > - \\(S\_i\\) is equivalent to `S[i-1]`.
> >
> > Note that the indices in Python look strange. This is also the reason we choose to use subscripts not square brackets in our definition.
>
> > **Levenshtein Distance**
> >
> > Given two words, e.g., \\(w^{a} = \\mathrm{cats}\\) and \\(w^{b} = \\mathrm{katz}\\). Suppose we can only use three operations: insertions, deletions and substitutions. The Levenshtein distance calculates the number of such operations needed to change from the first word \\(w^a\\) to the second one \\(w^b\\) by applying single-character edits. In this example, we need two replacements, i.e., `"c" -> "k"` and `"s" -> "z"`.
> >
> > The Levenshtein distance can be solved using recursive algorithms [^/time-series/timeseries-data.data-augmentation/#trekhleb].
>
> DTW is very useful when comparing series with different lengths. For example, most error metrics require the actual time series and predicted series to have the same length. In the case of different lengths, we can perform DTW when calculating these metrics[^/time-series/timeseries-data.data-augmentation/#darts-dtw-metric].
>
> The forecasting package darts provides a [demo of DTW]().
> [!NOTE]
>
> **DTW Barycenter Averaging**
>
> [DTW]() Barycenter Averaging (**DBA**) constructs a series \\(\\bar{\\mathcal S}\\) out of a set of series \\(\\{\\mathcal S^{(\\alpha)}\\}\\) so that \\(\\bar{\\mathcal S}\\) is the barycenter of \\(\\{\\mathcal S^{(\\alpha)}\\}\\) measured by Dynamic Time Warping (**DTW**) distance [^/time-series/timeseries-data.data-augmentation/#bib-Petitjean2011-sj].
>
> ## Barycenter Averaging Based on DTW Distance
>
> Petitjean et al proposed a time series averaging algorithm based on DTW distance which is dubbed DTW Barycenter Averaging (**DBA**).
>
> > **DBA Implementation**
> >
> > [https://github.com/fpetitjean/DBA]()
### Series Mixing
Another class of data augmentation methods is mixing the series. For example, we take two randomly drawn series and average them using DTW Barycenter Averaging (**DBA**) [^/time-series/timeseries-data.data-augmentation/#bib-Petitjean2011-sj]. (DTW, dynamic time warping, is an algorithm to calculate the distance between sequential datasets by matching the data points on each of the series [^/time-series/timeseries-data.data-augmentation/#bib-Petitjean2011-sj][^/time-series/timeseries-data.data-augmentation/#bib-Hewamalage2019-tv].) To augment a dataset, we can choose from a list of strategies [^/time-series/timeseries-data.data-augmentation/#bib-Bandara2020-yp][^/time-series/timeseries-data.data-augmentation/#bib-Forestier2017-uk]:
- Average All series using different sets of weights to create new synthetic series.
- Average Selected series based on some strategies. For example, Forestier et al proposed choosing an initial series and combining it with its nearest neighbors [^/time-series/timeseries-data.data-augmentation/#bib-Forestier2017-uk].
- Average Selected with Distance is Average Selected but neighbors that are far from the initial series are down-weighted [^/time-series/timeseries-data.data-augmentation/#bib-Forestier2017-uk].
Some other similar methods are
- Equalized Mixture Data Augmentation (**EMDA**) calculates the weighted average of spectrograms of the same class label[^/time-series/timeseries-data.data-augmentation/#bib-Takahashi2017-yz].
- Stochastic Feature Mapping (**SFM**) is a data augmentation method in audio data[^/time-series/timeseries-data.data-augmentation/#bib-Cui2014-de].
### Data Generating Process
Time series data can also be augmented using some assumed data generating process (**DGP**). Some methods, such as GRATIS [^/time-series/timeseries-data.data-augmentation/#bib-Kang2019-cl], utilize simple generic methods such as AR/MAR. Some other methods, such as Gaussian Trees [^/time-series/timeseries-data.data-augmentation/#bib-Cao2014-mt], utilize more complicated hidden structures using graphs, which can approximate more complicated data generating processes. These methods do not necessarily reflect the actual data generating process but the data is generated using some parsimonious phenomenological models. Some other methods are more tuned toward detailed mechanisms. There are also methods using generative deep neural networks such as [GAN]().
#### Dynamic Factor Model (**DFM**)
For example, we have a series \\(X(t)\\) which depends on a latent variable \\(f(t)\\)[^/time-series/timeseries-data.data-augmentation/#bib-Stock2016-mh],
\\\[ X(t) = \\mathbf A f(t) + \\eta(t), \\\]
where \\(f(t)\\) is determined by a differential equation
\\\[ \\frac{f(t)}{dt} = \\mathbf B f(t) + \\xi(t). \\\]
In the above equations, \\(\\eta(t)\\) and \\(\\xi(t)\\) are the irreducible noise.
The above two equations can be combined into one first-order differential equation.
Once the model is fit, it can be used to generate new data points. However, we will have to understand whether the data is generated in such processes.
## Applying the Synthetic Data to Model Training
Once we prepared the synthetic dataset, there are two strategies to include them in our model training [^/time-series/timeseries-data.data-augmentation/#bib-Bandara2020-yp].
| Strategy | Description |
| --- | --- |
| Pooled Strategy | Synthetic data + original data -\> model |
| Transfer Strategy | Synthetic data -\> pre-trained model; pre-trained model + original data -\> model |
The pooled strategy takes the synthetic data and original data then feeds them together into the training pipeline. The transfer strategy uses the synthetic data to pre-train the model, then uses transfer learning methods (e.g., freeze weights of some layers) to train the model on the original data.
---
**Related:** [Synthetic Time Series]() · [Generating Processes for Time Series]()
[^/time-series/timeseries-data.data-augmentation/#trekhleb]: trekhleb. javascript-algorithms/src/algorithms/string/levenshtein-distance at master · trekhleb/javascript-algorithms. In: GitHub \[Internet\]. \[cited 27 Jul 2022\]. Available: [https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/string/levenshtein-distance]()
[^/time-series/timeseries-data.data-augmentation/#darts-dtw-metric]: Unit8. Metrics — darts documentation. In: Darts \[Internet\]. \[cited 7 Mar 2023\]. Available: [https://unit8co.github.io/darts/generated\_api/darts.metrics.metrics.html?highlight=dtw\#darts.metrics.metrics.dtw\_metric]()
[^/time-series/timeseries-data.data-augmentation/#bib-Hasibi2019-in]: Hasibi R., Shokri M., Dehghan M.. Augmentation Scheme for Dealing with Imbalanced Network Traffic Classification Using Deep Learning. 2019. [http://arxiv.org/abs/1901.00204]()
[^/time-series/timeseries-data.data-augmentation/#bib-Iwana2020-oc]: Iwana B.K., Uchida S.. An Empirical Survey of Data Augmentation for Time Series Classification with Neural Networks. 2020. [http://arxiv.org/abs/2007.15951]()
[^/time-series/timeseries-data.data-augmentation/#bib-Shorten2019-ty]: Shorten C., Khoshgoftaar T.M.. A survey on Image Data Augmentation for Deep Learning. *Journal of Big Data*. 2019. [https://journalofbigdata.springeropen.com/articles/10.1186/s40537-019-0197-0]()
[^/time-series/timeseries-data.data-augmentation/#bib-Wen2020-ez]: Wen Q., Sun L., Yang F. et al.. Time Series Data Augmentation for Deep Learning: A Survey. 2020. [http://arxiv.org/abs/2002.12478]()
[^/time-series/timeseries-data.data-augmentation/#bib-Petitjean2011-sj]: Petitjean F., Ketterlin A., Gan\\c carski P.. A global averaging method for dynamic time warping, with applications to clustering. *Pattern recognition*. 2011. [https://www.sciencedirect.com/science/article/pii/S003132031000453X]()
[^/time-series/timeseries-data.data-augmentation/#bib-Kang2019-cl]: Kang Y., Hyndman R.J., Li F.. GRATIS: GeneRAting TIme Series with diverse and controllable characteristics. 2019. [http://arxiv.org/abs/1903.02787]()
[^/time-series/timeseries-data.data-augmentation/#bib-Stock2016-mh]: Stock J.H., Watson M.W.. Chapter 8 - Dynamic Factor Models, Factor-Augmented Vector Autoregressions, and Structural Vector Autoregressions in Macroeconomics. *Handbook of Macroeconomics*. 2016. [https://www.sciencedirect.com/science/article/pii/S1574004816300027]()
[^/time-series/timeseries-data.data-augmentation/#bib-Yoon_undated-gs]: Yoon J., Jarrett D., Schaar M.. Time-series generative adversarial networks. *Advances in Neural Information Processing Systems*. 2019. [https://papers.nips.cc/paper/2019/hash/c9efe5f26cd17ba6216bbe2a7d26d490-Abstract.html]()
[^/time-series/timeseries-data.data-augmentation/#bib-Brophy2021-vn]: Brophy E., Wang Z., She Q. et al.. Generative adversarial networks in time series: A survey and taxonomy. 2021. [http://arxiv.org/abs/2107.11098]()
[^/time-series/timeseries-data.data-augmentation/#bib-Takahashi2017-yz]: Takahashi N., Gygli M., Van Gool L.. AENet: Learning Deep Audio Features for Video Analysis. 2017. [http://arxiv.org/abs/1701.00599]()
[^/time-series/timeseries-data.data-augmentation/#bib-Cui2014-de]: Cui X., Goel V., Kingsbury B.. Data Augmentation for deep neural network acoustic modeling. *2014 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)*. 2014. [http://dx.doi.org/10.1109/ICASSP.2014.6854671]()
[^/time-series/timeseries-data.data-augmentation/#bib-Iwana2020-fe]: Iwana B.K., Uchida S.. Time Series Data Augmentation for Neural Networks by Time Warping with a Discriminative Teacher. 2020. [http://arxiv.org/abs/2004.08780]()
[^/time-series/timeseries-data.data-augmentation/#bib-Gao2020-qr]: Gao J., Song X., Wen Q. et al.. RobustTAD: Robust Time Series Anomaly Detection via Decomposition and Convolutional Neural Networks. 2020. [http://arxiv.org/abs/2002.09545]()
[^/time-series/timeseries-data.data-augmentation/#bib-Le_Guennec2016-zi]: Le Guennec A., Malinowski S., Tavenard R.. Data augmentation for time series classification using convolutional neural networks. *ECML/PKDD workshop on advanced analytics and learning on temporal data*. 2016. [https://halshs.archives-ouvertes.fr/halshs-01357973/document]()
[^/time-series/timeseries-data.data-augmentation/#bib-Um2017-oq]: Um T.T., Pfister F.M.J., Pichler D. et al.. Data Augmentation of Wearable Sensor Data for Parkinson's Disease Monitoring using Convolutional Neural Networks. 2017. [http://arxiv.org/abs/1706.00527]()
[^/time-series/timeseries-data.data-augmentation/#bib-Bergmeir2016-eh]: Bergmeir C., Hyndman R.J., Ben\\'\\itez J.M.. Bagging exponential smoothing methods using STL decomposition and Box–Cox transformation. *International journal of forecasting*. 2016. [https://www.sciencedirect.com/science/article/pii/S0169207015001120]()
[^/time-series/timeseries-data.data-augmentation/#bib-Hewamalage2019-tv]: Hewamalage H., Bergmeir C., Bandara K.. Recurrent Neural Networks for Time Series Forecasting: Current Status and Future Directions. 2019. [http://arxiv.org/abs/1909.00590]()
[^/time-series/timeseries-data.data-augmentation/#bib-Bandara2020-yp]: Bandara K., Hewamalage H., Liu Y. et al.. Improving the Accuracy of Global Forecasting Models using Time Series Data Augmentation. 2020. [http://arxiv.org/abs/2008.02663]()
[^/time-series/timeseries-data.data-augmentation/#bib-Forestier2017-uk]: Forestier G., Petitjean F., Dau H.A. et al.. Generating Synthetic Time Series to Augment Sparse Datasets. *2017 IEEE International Conference on Data Mining (ICDM)*. 2017. [http://dx.doi.org/10.1109/ICDM.2017.106]()
[^/time-series/timeseries-data.data-augmentation/#bib-Cao2014-mt]: Cao H., Tan V.Y.F., Pang J.Z.F.. A parsimonious mixture of Gaussian trees model for oversampling in imbalanced and multimodal time-series classification. *IEEE transactions on neural networks and learning systems*. 2014. [http://dx.doi.org/10.1109/TNNLS.2014.2308321]()
# Time Series Forecasting Tasks
> [!NOTE]
>
> **In one minute**
>
> Forecasting tasks differ by how many series are involved. Univariate forecasting predicts the next H steps of one series from its last K steps; multivariate forecasting handles several series and their covariates, which may not be aligned at every time step.
>
> **Read first:** [Time Series Data and Statistical Forecasting Methods]()
There are many different types of time series forecasting tasks. Forecasting tasks can be categorized by different criteria. For example, we can categorize them by the number of variables in the series and their relations to each other.
In the [introduction of this chapter](), we already discussed some terminologies of time series forecasting. In this section, we dive deep into the details of univariate time series forecasting and multivariate time series forecasting.
## Forecasting Univariate Time Series
In a univariate time series forecasting task, we are given a single time series and asked to forecast future steps of the series.
![Univariate Time Series Data]()
Given a time series \\(\\{y\_{t}\\}\\), we train a model to forecast \\(\\color{red}y\_{t+1:t+H}\\) using input \\(\\color{blue}y\_{t-K:t}\\), i.e., we build a model \\(f\\) such that
\\\[ f({\\color{blue}y\_{t-K:t}}) \\to {\\color{red}y\_{t+1:t+H}}. \\\]
![Univaraite TS Task]()
## Forecasting Multivariate Time Series
In a multivariate time series forecasting task, we will deal with multiple time series. Naively, we expect multivariate time series forecasting to be nothing special but adding more series. However, the complication comes from the fact that different series may not be aligned well at all time steps.
In the [introduction of this chapter](), we have shown the basic ideas of targets \\(\\mathbf y\\) and covariates \\(\\mathbf x\\) and \\(\\mathbf u\\). In the following illustration, we expand the idea to the multivariate case.
![Multivariate Time Series Data]()
---
**Related:** [The Time Delay Embedding Representation]() · [Naive Forecasts]()
# Naive Forecasts
> [!NOTE]
>
> **In one minute**
>
> Simple baselines that every model should beat: repeat the last observation, forecast the mean of the past, or use simple exponential smoothing, which weights recent values more. Truncating the smoothing sum biases the forecast.
In some sense, time series forecasting is easy, if we have low expectations. From a dynamical system point of view, our future is usually not too different from our current state.
## Last Observation
Assuming our time series is not changing dramatically, we can take our last observation as our forecast.
> [!NOTE]
>
> **Example: Last Observation as Forecast**
>
> Assuming we have the simplest dynamical system,
>
> \\\[ \\frac{\\mathrm d y(t)}{\\mathrm dt} = f(y, t, \\theta), \\\]
>
> where \\(y(t)\\) is the time series generator function, \\(t\\) is time, \\(\\theta\\) is some parameters defining the function \\(f\\).
>
> For example,
>
> \\\[ \\frac{\\mathrm d y(t)}{\\mathrm dt} = t \\\]
>
> is a linear growing time series.
>
> We would imagine, it won't be too crazy if we just take the last observed value as our forecast.
>
> ![Naive Last Value Forecasts]()
>
> ```
> import matplotlib.pyplot as plt
>
> from darts.utils.timeseries_generation import linear_timeseries
>
> ts = linear_timeseries(length=30)
> ts.plot(marker=".")
>
> ts_train, ts_test = ts.split_before(0.9)
> ts_train.plot(marker=".", label="Train")
> ts_test.plot(marker="+", label="Test")
>
> ts_last_value_naive_forecast = ts_train.shift(1)[-1]
>
> fig, ax = plt.subplots(figsize=(10, 6.18))
> ts_train.plot(marker=".", label="Train", ax=ax)
> ts_test.plot(marker="+", label="Test", ax=ax)
> ts_last_value_naive_forecast.plot(marker=".", label="Last Value Naive Forecast")
> ```
There are also slightly more complicated naive forecasting methods.
## Mean Forecast
In some bounded time series, the mean of the past values is also a good naive candidate[^/time-series/timeseries-forecast.naive/#Hyndman2021].
> [!NOTE]
>
> **Example: Naive Mean Forecast**
>
> ![]()
>
> ```
> import matplotlib.pyplot as plt
>
> from darts.utils.timeseries_generation import sine_timeseries
> from darts.models.forecasting.baselines import NaiveMean
>
> ts_sin = sine_timeseries(length=30, value_frequency=0.05)
>
> ts_sin.plot(marker=".")
>
>
> ts_sin_train, ts_sin_test = ts_sin.split_before(0.9)
>
> ts_sin_train.plot(marker=".", label="Train")
> ts_sin_test.plot(marker="+", label="Test")
>
>
> naive_mean_model = NaiveMean()
> naive_mean_model.fit(ts_sin_train)
> ts_mean_naive_forecast = naive_mean_model.predict(1)
>
> fig, ax = plt.subplots(figsize=(10, 6.18))
> ts_sin_train.plot(marker=".", label="Train", ax=ax)
> ts_sin_test.plot(marker="+", label="Test", ax=ax)
> ts_mean_naive_forecast.plot(marker=".", label="Naive Mean Forecast")
> ```
## Simple Exponential Smoothing
Simple Exponential Smoothing (SES) is a naive smoothing method to account for the historical values of a time series when forecasting. The expanded form of SES is[^/time-series/timeseries-forecast.naive/#Hyndman2021]
\\\[ y(t) = \\alpha ( y(t-1) + (1-\\alpha) y(t-2) + (1-\\alpha)^2 y(t-3) + \\cdots ) \\\]
> [!WARNING]
>
> **Truncated SES is Biased**
>
> Naively speaking, if history is constant, we have to forecast the same constant. For example, if we have \\(y(t) = y(t\_0)\\), the smoothing
>
> \\\[ y(t) = \\alpha (1 + (1-\\alpha) + \\cdots) y(t\_0) \\\]
>
> should equal to \\(y(t\_0)\\), i.e.,
>
> \\\[ \\alpha (1 + (1-\\alpha) + \\cdots) = 1. \\\]
>
> The series indeed sums up to \\(1/\\alpha\\) when \\(n\\to\\infty\\) since
>
> \\\[ \\sum\_{n=0}^\\infty (1-\\alpha) = \\frac{1}{\\alpha}. \\\]
>
> However, if we truncate the series to finite values, we will have
>
> \\\[ \\sum\_{n=0}^N (1-\\alpha) \\leq \\frac{1}{\\alpha}. \\\]
>
> Then our naive forecast for constant series is
>
> \\\[ y(t) = \\alpha \\sum\_{n=0}^N (1-\\alpha) y(t\_0) \\leq y(t\_0), \\\]
>
> when \\(y(t\_0)\\) is positive.
>
> As an intuition, we plot out the sum of the coefficients for different orders and \\(\\alpha\\)s.
>
> ![]()
>
> ```
> from itertools import product
> import pandas as pd
> import seaborn as sns; sns.set()
> from matplotlib.colors import LogNorm
>
> def ses_coefficients(alpha, order):
> return (
> np.power(
> np.ones(int(order)) * (1-alpha), np.arange((order))
> ) * alpha
> )
>
> alphas = np.linspace(0.05, 0.95, 19)
> orders = list(range(1, 16))
>
> # Create dataframes for visualizations
> df_ses_coefficients = pd.DataFrame(
> [[alpha, order] for alpha, order in product(alphas, orders)],
> columns=["alpha", "order"]
> )
> df_ses_coefficients["ses_coefficients_sum"] = df_ses_coefficients.apply(
> lambda x: ses_coefficients(x["alpha"], x["order"]).sum(), axis=1
> )
>
> # Visualization
> g = sns.heatmap(
> data=df_ses_coefficients.pivot(
> "alpha", "order", "ses_coefficients_sum"
> ),
> square=True, norm=LogNorm(),
> fmt="0.2g",
> yticklabels=[f"{i:0.2f}" for i in alphas],
> )
>
> g.set_title("SES Sum of Coefficients");
> ```
> [!NOTE]
>
> **Holt-Winters' Exponential Smoothing**
>
> In applications, the Holt-Winters' exponential smoothing is more practical[^/time-series/timeseries-forecast.naive/#Hyndman2021][^/time-series/timeseries-forecast.naive/#nist][^/time-series/timeseries-forecast.naive/#HWES-numpyro].
>
> We created some demo time series and apply the Holt-Winters' exponential smoothing. To build see where exponential smoothing works, we forecast at different dates.
>
> ![]()
>
> ![]()
>
> ![]()
>
> ![]()
>
> ![]()
>
> ```
> import matplotlib.pyplot as plt
>
> from darts.utils.timeseries_generation import sine_timeseries
> from darts.models.forecasting.baselines import NaiveMean
>
> ts_sin = sine_timeseries(length=30, value_frequency=0.05)
>
> ts_sin.plot(marker=".")
>
> ts_sin_train, ts_sin_test = ts_sin.split_before(0.7)
>
> es_model = ExponentialSmoothing()
>
> es_model.fit(ts_sin_train)
> es_model_sin_forecast = es_model.predict(4)
>
> fig, ax = plt.subplots(figsize=(10, 6.18))
> ts_sin_train.plot(marker=".", label="Train", ax=ax)
> ts_sin_test.plot(marker="+", label="Test", ax=ax)
> es_model_sin_forecast.plot(marker=".", label="Exponential Smoothing Forecast")
> ```
## Other
Other naive forecasts, such as naive drift, are introduced in Hyndman, et al., (2021)[^/time-series/timeseries-forecast.naive/#Hyndman2021].
---
**Related:** [Time Series Forecasting Metrics]() · [Statistical Models of Time Series]()
[^/time-series/timeseries-forecast.naive/#Hyndman2021]: Hyndman, R.J., & Athanasopoulos, G. (2021) Forecasting: principles and practice, 3rd edition, OTexts: Melbourne, Australia. OTexts.com/fpp3. Accessed on 2023-02-13.
[^/time-series/timeseries-forecast.naive/#nist]: 6.4.3.5. Triple Exponential Smoothing. In: NIST Engineering Statistics Handbook \[Internet\]. \[cited 16 Feb 2023\]. Available: [https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc435.htm]()
[^/time-series/timeseries-forecast.naive/#HWES-numpyro]: Example: Holt-Winters Exponential Smoothing — NumPyro documentation. In: NumPyro \[Internet\]. \[cited 16 Feb 2023\]. Available: [https://num.pyro.ai/en/stable/examples/holt\_winters.html]()
# Time Series Forecasting Evaluation
> [!NOTE]
>
> **In one minute**
>
> Time series can't be split at random: the test data has to come after the training data, or information leaks from the future. Backtesting moves the split point forward in time, sliding or growing the training window, and evaluates on the block that follows, which gives several scores instead of one; a gap between train and test adds a safety margin. Shuffled cross-validation is rarely appropriate.
>
> **Read first:** [The Time Delay Embedding Representation]()
Evaluating time series forecasting models is very important yet sometimes difficult. For example, it is very easy to bring in information leakage when evaluating time series forecasting models. In this section, we will discuss some of the common pitfalls and best practices when evaluating time series forecasting models.
## Train Test Split for Time Series Data
Evaluating time series models is usually different from most other machine learning tasks as we usually don't have strictly i.i.d. data. On the other hand, the time dimension in our time series data is a natural dimension to split the data into train and test sets. In this section, we will discuss the different ways to split the data into train and test sets.
### Backtesting
We choose the specific time step to split the data, assuming the series used to train the model is \\(Y\_t\\) with length \\(T\_t\\), and the series used to evaluate the model is \\(Y\_e\\) with length \\(T\_e\\).
> [!NOTE]
>
> **Slicing the Training Data \\(Y\_t\\) for Training**
>
> In many deep learning models, the input length and output length are fixed. To train the model using time series data, we usually apply the [time delayed embedding]() method to prepare the train data \\(Y\_t\\). Refer to [our deep learning forecasting examples]() for more details.
Keeping the length of the train and test unchanged, we can move forward in time, where we require the split time point to fall inside the window[^/time-series/timeseries-evaluation.forecasting/#bib-Cerqueira2019-vt]. In this way, we create multiple train test splits and perform multiple evaluations, or backtesting, on the model. The following illustration shows an example of this technique. The uppermost panel shows the original series, with each block indicating a time step.
![Sliding Blocks]()
In the interactive version above, switch between a sliding and an expanding train window, add a gap between train and test, and click on any fold to inspect it.
> [!NOTE]
>
> **Expanding the Length of the Training Set**
>
> Keeping the train set length equal when sliding through time is to simulate the use case where we always take a fixed length of historical data to train the model. For example, some dataset has gradual data shift, and using fixed length historical data can help relieviate data shift problems.
>
> In some other use cases, we would take in as much data as possible. In this case, we could also expand the train set when silidng the window.
>
> ![with Growing Train]()
In some use cases, we do not get to know the most recent data when we are performing inference. For example, if we are forecasting the demand for the next week, we might not know the demand for the last week as the data might be ready. In this case, we can also use a gap between the train and test sets to simulate this situation.
![with Gap]()
#### Using Multiple Time Windows
When we move the split time point forward in time, we could constrain the split to fall inside a specific time window. In the following, we have assumed the sliding window size to be 4, where we move forward one time step for each test set.
![Out-of-Sample with Sliding Window]()
For some large time series forecasting datasets, we might be interested in the performance of some specific types of periods. For example, if Amazon is evaluating its demand forecasting model, it may be more interested in the performance of the model during some normal days as well as the holiday seasons. In this case, we can use multiple sliding windows to evaluate the model.
### Cross-validation
> [!WARNING]
>
> **Not a Common Practice**
>
> This is not a common practice in time series forecasting problems but it is still worth mentioning here.
If our dataset is i.i.d. through time and we do not have information leakage if we randomly take a subsequence of the data, we could also use the cross-validation technique to evaluate the model. The following illustration shows an example of this technique. The uppermost panel shows the original series, with each block indicating a time step.
![Cross-validation]()
Similar to the gap technique in backtesting, we can also use a gap between the train and test sets.
![Cross-validation with Neighbor removed]()
---
**Related:** [Time Series Forecasting Metrics]()
[^/time-series/timeseries-evaluation.forecasting/#bib-Cerqueira2019-vt]: Cerqueira V., Torgo L., Mozetic I.. Evaluating time series forecasting models: An empirical study on performance estimation methods. 2019. [http://arxiv.org/abs/1905.11744]()
# Time Series Forecasting Metrics
> [!NOTE]
>
> **In one minute**
>
> A metric turns forecast errors into one number, and the choice decides which model looks best. Scale-dependent errors (MAE, MSE, RMSE) are in the data's units, and the squared ones punish large misses most; percentage errors (MAPE, sMAPE) compare across series but blow up when the truth is near zero; scaled errors such as MASE compare against a naive forecast; probabilistic forecasts need scores such as the quantile loss or CRPS.
>
> **Read first:** [Time Series Forecasting Evaluation]()
Measuring the goodness of a forecaster is nontrivial. Tons of metrics are devised to measure forecasting results, applying the wrong metric may lead to "consequences" in decisions.
In the following discussion, we assume the forecast at time \\(t\\) to be \\(\\hat y(t)\\) and the actual value is \\(y(t)\\). The forecast horizon is defined as \\(H\\). In general, we look for a function
\\\[ L\\left(\\{y(t\_1), \\cdots, y(t\_H)\\}, \\{\\hat y(t\_1), \\cdots, \\hat y(t\_H)\\}; \\{C(t)\\}, \\{y(t)\\} \\right), \\\]
where \\(\\{C(t)\\}\\) are the covariates and \\(\\{y(t)\\}\\) represents the past target variables.
> [!NOTE]
>
> **Distance between Truths and Forecasts**
>
> Naive choices of such metrics are distances between the truth vector \\(\\{y(t\_1), \\cdots, y(t\_H)\\}\\) and the forecast vector \\(\\{\\hat y(t\_1), \\cdots, \\hat y(t\_H)\\}\\).
>
> For example, we can use norms of the deviation vector \\(\\{y(t\_1) - \\hat y(t\_1), \\cdots, y(t\_H) - \\hat y(t\_H)\\}\\).
>
> In Hyndman & Koehler (2006), \\(y(t\_i) - \\hat y(t\_i)\\) is defined as the **forecast error** \\(e\_i\\equiv y(t\_i) - \\hat y(t\_i)\\)[^/time-series/timeseries-metrics.forecasting/#bib-Hyndman2006-ld]. While it is a bit confusing, the term **forecast error** is used in many kinds of literature.
>
> The authors also defined the **relative error** \\(r\_i = e\_i/e^\*\_i\\) with \\(e^\*\_i\\) being the reference forecast error from the baseline.
In this section, we explore some frequently used metrics. Hyndman & Koehler (2006) discussed four different types of metrics[^/time-series/timeseries-metrics.forecasting/#bib-Hyndman2006-ld]
1. scaled-dependent measures, e.g., errors based on \\(\\{y(t\_1) - \\hat y(t\_1), \\cdots, y(t\_H) - \\hat y(t\_H)\\}\\),
2. percentage errors, e.g., errors based on \\(\\{\\frac{y(t\_1) - \\hat y(t\_1)}{y(t\_1)}, \\cdots, \\frac{y(t\_H) - \\hat y(t\_H)}{y(t\_H)}\\}\\),
3. relative errors, e.g., errors based on \\(\\{\\frac{y(t\_1) - \\hat y(t\_1)}{y(t\_1) - \\hat y^\*(t\_1)}, \\cdots, \\frac{y(t\_H) - \\hat y(t\_H)}{y(t\_H) - \\hat y^\*(t\_H)}\\}\\), where \\(\\hat y^\*(t\_i)\\) is a baseline forecast at time \\(t\_i\\),
4. relative metrics, e.g., the ratio of the MAE for the experiment and the baseline, \\(\\operatorname{MAE}/\\operatorname{MAE}\_{\\text{baseline}}\\),
5. in-sample scaled errors, e.g., MASE.
Apart from the above categories, there are some other properties of metrics. Some metrics are bounded while others are not. Also, some metrics specifically require probabilistic forecasts. In the following table, we list some of the useful metrics.
| Metric | Probabilistic | Theoretical Range | Notes |
| --- | --- | --- | --- |
| MAE | | \\(\[0,\\infty)\\) | |
| MSE | | \\(\[0,\\infty)\\) | |
| RMSE | | \\(\[0,\\infty)\\) | |
| MASE | | \\(\[0,\\infty)\\) | Scaled in practice; requires insample data |
| RMSLE | | \\(\[0,\\infty)\\) | |
| MAPE | | \\(\[0,\\infty\]\\) | |
| sMAPE | | \\(\[0, 2\]\\) | For values of the same sign |
| wMAPE | | \- | Depends on what weights are used |
| Quantile Score | ✅ | \\(\[0,\\infty)\\) | |
| [CRPS]() | ✅ | \\(\[0,\\infty)\\) | |
> [!NOTE]
>
> **Recommended Reading**
>
> [Hyndman & Athanasopoulos (2021)]() is a good reference for forecast errors [^/time-series/timeseries-metrics.forecasting/#Hyndman2021].
>
> To find implementations of metrics, [Darts]() and [GluonTS]() both have a handful of metrics implemented.
## Try It: How Metrics React
Pick a scenario and move its slider, or drag the orange forecast points, and watch how each metric responds. The small chart under each value shows that metric over the whole range of the slider, and the small print compares the value with the scenario as loaded.
An interactive chart with five scenarios (error size, one big miss, bias, a true value near zero, scale). Each has a slider, and MAE, MSE, RMSE, MAPE and sMAPE are shown together with their curves over the slider's range. It needs JavaScript; the sections below cover the same ground.
## Try It: Shift the Level of the Values
Add the same constant \\(c\\) to every true value and every forecast. The errors \\(y(t) - \\hat y(t)\\) do not change, so a metric built only from the errors stays the same at every level, while a metric that divides by the values or takes their logarithm does not.
An interactive chart where a slider shifts the truth and the forecast by the same amount, and MAE, MSE, RMSE, MAPE, sMAPE and RMSLE update. It needs JavaScript. In short: MAE, MSE and RMSE are the same at every shift; MAPE, sMAPE and RMSLE get smaller as the level grows, and MAPE blows up when the true values come close to zero.
## List of Metrics
> [!NOTE]
>
> **Code to Reproduce the Results**
>
> ```
> # %%
> from loguru import logger
> import datetime
> import numpy as np
> from itertools import product
>
> from matplotlib.ticker import FormatStrFormatter
> import pandas as pd
>
> import matplotlib.pyplot as plt
> import seaborn as sns
>
> sns.set()
>
> from darts.utils.timeseries_generation import (
> sine_timeseries,
> linear_timeseries,
> constant_timeseries,
> )
>
> from darts.metrics.metrics import (
> mae,
> mape,
> marre,
> mse,
> ope,
> rho_risk,
> rmse,
> rmsle,
> smape,
> mase
> )
>
> # %%
> length = 600
> start = 0
> ts_sin = sine_timeseries(length=length, value_frequency=0.01, start=0)
> ts_lin = linear_timeseries(
> length=length, start_value=0, end_value=1.5, start=0
> )
>
> ts = (ts_sin + ts_lin).with_columns_renamed("sine", "sin+linear")
>
> split_at = 500
> ts_train, ts_test = ts.split_before(split_at)
> ts_train = ts_train.with_columns_renamed("sin+linear", "train")
> ts_test = ts_test.with_columns_renamed("sin+linear", "actual")
>
>
> _, ts_pred_lin = ts_lin.split_before(split_at)
> ts_pred_lin = ts_pred_lin.with_columns_renamed("linear", "linear_prediction")
>
>
> _, ts_pred_sin = ts_sin.split_before(split_at)
> ts_pred_sin = ts_pred_sin.with_columns_renamed("sine", "sin_prediction")
>
> ts_pred_const = constant_timeseries(
> value=ts_train.last_value(),
> start=ts_test.start_time(),
> end=ts_test.end_time()
> )
> ts_pred_const = ts_pred_const.with_columns_renamed("constant", "constant_prediction")
>
>
> # %%
> ts.plot(marker=".")
> # ts_lin.plot(linestyle="dashed")
> # ts_sin.plot(linestyle="dashed")
>
> ts_train.plot()
> ts_test.plot(color="r")
>
> ts_pred_lin.plot(color="orange")
> ts_pred_sin.plot(color="green")
> ts_pred_const.plot(color="black")
>
> # %%
> class MetricBench:
> def __init__(self, metric_fn, metric_name=None):
> self.metric_fn = metric_fn
> if metric_name is None:
> metric_name = self.metric_fn.__name__
> self.metric_name = metric_name
>
> def _heatmap_data(self, actual_range=None, pred_range=None):
> if actual_range is None:
> actual_range = np.linspace(-1,1, 21)
> if pred_range is None:
> pred_range = np.linspace(-1,1, 21)
> hm_data = []
> for y, y_hat in product(actual_range, pred_range):
> ts_y = constant_timeseries(value=y, length=1)
> ts_y_hat = constant_timeseries(value=y_hat, length=1)
> try:
> hm_data.append(
> {
> "y": y,
> "y_hat": y_hat,
> "metric": f"{self.metric_name}",
> "value": self.metric_fn(ts_y, ts_y_hat)
> }
> )
> except Exception as e:
> logger.warning(f"Skipping due to {e}")
>
> df_hm_data = pd.DataFrame(hm_data)
>
> return df_hm_data
>
> def heatmap(self, ax=None, cmap="viridis_r", actual_range=None, pred_range=None):
> if ax is None:
> fig, ax = plt.subplots(figsize=(12, 10))
>
> df_hm_data = self._heatmap_data(actual_range=actual_range, pred_range=pred_range)
>
> sns.heatmap(
> df_hm_data.pivot("y_hat", "y", "value"),
> fmt=".2g",
> cmap=cmap,
> ax=ax,
> )
>
> ax.set_xticklabels(
> [self._heatmap_fmt(label.get_text())
> for label in ax.get_xticklabels()]
> )
> ax.set_yticklabels(
> [self._heatmap_fmt(label.get_text())
> for label in ax.get_yticklabels()]
> )
> ax.set_title(f"Metric: {self.metric_name}")
>
> return ax
>
> @staticmethod
> def _heatmap_fmt(s):
> try:
> n = "{:.2f}".format(float(s))
> except:
> n = ""
> return n
>
> def _ratio_data(self, pred_range=None):
> if pred_range is None:
> pred_range = np.linspace(-1, 3, 41)
> ratio_data = []
> y = 1
> for y_hat in pred_range:
> ts_y = constant_timeseries(value=y, length=1)
> ts_y_hat = constant_timeseries(value=y_hat, length=1)
> try:
> ratio_data.append(
> {
> "y": y,
> "y_hat": y_hat,
> "metric": f"{self.metric_name}",
> "value": self.metric_fn(ts_y, ts_y_hat)
> }
> )
> except Exception as e:
> logger.warning(f"Skipping due to {e}")
>
> df_ratio_data = pd.DataFrame(ratio_data)
>
> return df_ratio_data
>
> def ratio_plot(self, ax=None, color="k", pred_range=None):
>
> if ax is None:
> fig, ax = plt.subplots(figsize=(12, 10))
>
> df_ratio_data = self._ratio_data(pred_range=pred_range)
>
> sns.lineplot(df_ratio_data, x="y_hat", y="value", ax=ax)
>
> ax.set_title(f"Metric {self.metric_name} (y=1)")
>
> return ax
>
>
> # %% [markdown]
> # ## Norms (MAE, MSE)
>
> # %%
> mse_bench = MetricBench(metric_fn=mse)
> mse_bench.heatmap()
>
> # %%
> mse_bench.ratio_plot()
>
> # %%
> mae_bench = MetricBench(metric_fn=mae)
> mae_bench.heatmap()
>
>
> # %%
> mae_bench.ratio_plot()
>
> # %%
> rmsle_bench = MetricBench(metric_fn=rmsle)
> rmsle_bench.heatmap()
>
> # %%
> rmsle_bench.ratio_plot()
>
> # %%
> rmse_bench = MetricBench(metric_fn=rmse)
> rmse_bench.heatmap()
>
> # %%
> rmse_bench.ratio_plot()
>
> # %%
> y_pos = np.linspace(0.1, 1, 20)
>
> mape_bench = MetricBench(metric_fn=mape)
> mape_bench.heatmap(actual_range=y_pos)
>
> # %%
> mape_bench.ratio_plot()
>
> # %%
> smape_bench = MetricBench(metric_fn=smape)
> smape_bench.heatmap(actual_range=y_pos, pred_range=y_pos)
>
> # %%
> smape_bench.ratio_plot(pred_range=y_pos)
>
> # %% [markdown]
> # ## Naive MultiHorizon Forecasts
>
> # %%
> two_args_metrics = [
> mse, mae, rmse, rmsle, mape, smape
> ]
>
> insample_metrics = [mase]
>
>
> metrics_tests = []
>
> for m in two_args_metrics:
> metrics_tests.append(
> {
> "metric": m.__name__,
> "value_lin_pred": m(ts_test, ts_pred_lin),
> "value_sin_pred": m(ts_test, ts_pred_sin),
> "value_const_pred": m(ts_test, ts_pred_const)
> }
> )
>
> for m in insample_metrics:
> metrics_tests.append(
> {
> "metric": m.__name__,
> "value_lin_pred": m(ts_test, ts_pred_lin, insample=ts_train),
> "value_sin_pred": m(ts_test, ts_pred_sin, insample=ts_train),
> "value_const_pred": m(ts_test, ts_pred_const, insample=ts_train)
> }
> )
>
> df_metrics_tests = (
> pd.DataFrame(metrics_tests)
> .round(3)
> .set_index("metric")
> .sort_values(by="value_const_pred")
> .sort_values(by="mape", axis=1)
> )
>
> df_metrics_tests.rename(
> columns={
> "value_lin_pred": "Linear Prediction",
> "value_sin_pred": "Sine Prediction",
> "value_const_pred": "Last Observed"
> },
> inplace=True
> )
>
> df_metrics_tests
>
> # %%
> from matplotlib.colors import LogNorm
>
> # %%
> metrics_tests_min_value = df_metrics_tests.min().values.min()
> metrics_tests_max_value = np.ma.masked_invalid(df_metrics_tests.max()).max()
> metrics_tests_min_value, metrics_tests_max_value
>
> # %%
> fig, ax = plt.subplots(figsize=(10, 6.18))
>
> sns.heatmap(
> df_metrics_tests,
> norm=LogNorm(
> vmin=0.1,
> vmax=100
> ),
> cbar_kws={"ticks":[0,1,10,1e2]},
> vmin = 0.1, vmax=100,
> annot=True,
> fmt="0.3f",
> ax=ax,
> )
> ```
### 1-Norm: MAE
The Mean Absolute Error (MAE) is
\\\[ \\operatorname{MAE}(y, \\hat y) = \\frac{1}{H}\\sum\_{t=1}^{t=H}\\lvert y(t) - \\hat y(t)\\rvert. \\\]
We can check some special and extreme cases:
- All forecasts are zeros: \\(\\hat y(t)=0\\), the value of \\(\\operatorname{MAE}(y, \\hat y)\\) is determined by the true value \\(y\\).
> **The Interpretation of MAE is Scale Dependent**
>
> This also tells us that MAE depends on the scale of the true values: MAE value of \\(100\\) for larger true values such as true value \\(y=1000\\) with forecast \\(\\hat y=900\\) doesn't seem to be bad, but MAE value for smaller true values such as true value \\(y=100\\) with forecast \\(\\hat y=0\\) seems to be quite off. Of course, the actual perception depends on the problem we are solving.
>
> This brings in a lot of trouble when we are dealing with forecasts on different scales, such as sales forecasts for all kinds of items on an e-commerce platform. Different types of items, e.g., expensive watches vs cheat T-shirts, have very different sales. In fact, in a paper from Amazon, the sales on Amazon are even scale-free[^/time-series/timeseries-metrics.forecasting/#bib-Salinas2017-hg].
- All forecasts are infinite: \\(\\hat y=\\infty\\), the MAE value will also be \\(\\infty\\). This means MAE is not bounded.
![]()
![]()
### 2-Norm: MSE
The Mean Square Error (MSE) is
\\\[ \\operatorname{MSE}(y, \\hat y) = \\frac{1}{H}\\sum\_{t=1}^{t=H}(y(t) - \\hat y(t))^2. \\\]
Similar to MAE, the interpretation of MSE is also scale dependent and the value is unbounded. However, due to the \\({}^2\\), MSE can be really large or small. Obtaining insights from MSE is even harder than MAE in most situations unless MSE matches a meaningful quantity in the dynamical system we are forecasting. Nevertheless, we can know that large deviations (\\(\\lvert y(t) - \\hat y(t)\\rvert \\gg 1\\)) dominates the metric even more than MAE.
![]()
![]()
> [!NOTE]
>
> **Other Norms**
>
> Other norms are not usually seen in literature but might provide insights into forecasts.
>
> The Max Norm error of a forecast can be defined as[^/time-series/timeseries-metrics.forecasting/#max-norm-wiki]
>
> \\\[\\operatorname{MAE}(y, \\hat y) = \\operatorname{max}\\left( \\{y(t) - \\hat y(t)\\}\\right).\\\]
### RMSE
The Root Mean Square Error (RMSE) is
\\\[ \\operatorname{RMSE}(y, \\hat y) = \\sqrt{\\operatorname{MSE}(y, \\hat y)} = \\sqrt{\\frac{1}{H}\\sum\_{t=1}^{t=H}(y(t) - \\hat y(t))^2}. \\\]
RMSE essentially brings the scale of the metric from the MSE scale back to something similar to MAE. However, we have to be mindful that large deviations dominate the metric more than that in MAE.
> [!NOTE]
>
> **Domination by Large Deviations**
>
> For example, in a horizon 2 forecasting problem, suppose we have the true values \\(\[100, 1\]\\) and we forecast \\(\[0, 0\]\\)
>
> \\\[ \\operatorname{RMSE} = \\sqrt{ \\frac{1}{2}\\left((100-0)^2 + (1-0)^2 \\right)} \\sim 70.71 \\\]
>
> If we assume the second step is forecasted perfectly, i.e., forecasts \\(\[0, 1\]\\), we have almost the same RMSE
>
> \\\[ \\sqrt{ \\frac{1}{2}(100-0)^2 + (1-1)^2} \\sim 70.71 \\\]
>
> For MAE, assuming forecasts \\(\[0,0\]\\), we get
>
> \\\[ \\operatorname{MAE} = \\frac{1}{2} \\left( \\lvert 1 - 0 \\rvert + \\lvert 100 - 0 \\rvert \\right) = 50.5. \\\]
>
> If we assume the forecast \\(\[0,1\]\\), we get something slightly different
>
> \\\[ \\frac{1}{2} \\lvert 100 - 0 \\rvert = 50. \\\]
>
> To see the difference between RMSE and MAE visually, we compute the following quantities
>
> \\\[ MAE(y=\[x, 1\], \\hat y=\[0, 1\]) / MAE(y=\[x, 1\], \\hat y=\[0, 0\]) \\\]
>
> as well as
>
> \\\[ RMSE(y=\[x, 1\], \\hat y=\[0, 1\]) / RMSE(y=\[x, 1\], \\hat y=\[0, 0\]). \\\]
>
> Using these ratios, we investigate the contributions from the large deviations for MAE and RMSE.
>
> ![Contribute Investigation MAE vs RMSE]()
>
> ```
> import numpy as np
> from darts.metrics.metrics import mae, rmse
> from darts import TimeSeries
>
> metric_contrib_x = np.linspace(0, 50, 101)
>
> mae_contrib_ratio = []
> for i in metric_contrib_x:
> mae_contrib_ratio.append(
> mae(
> TimeSeries.from_values(np.array([i,1,])),
> TimeSeries.from_values(np.array([0,1,])),
> )/mae(
> TimeSeries.from_values(np.array([i,1,])),
> TimeSeries.from_values(np.array([0,0,])),
> )
> )
>
> rmse_contrib_ratio = []
> for i in metric_contrib_x:
> rmse_contrib_ratio.append(
> rmse(
> TimeSeries.from_values(np.array([ i, 1,])),
> TimeSeries.from_values(np.array([0, 1,])),
> )/rmse(
> TimeSeries.from_values(np.array([i, 1,])),
> TimeSeries.from_values(np.array([0,0])),
> )
> )
> ```
>
> The above chart shows that RMSE is more dominated by large deviations.
### MASE
The Mean Absolute Scaled Error (MASE) is the MAE scaled by the one-step ahead naive forecast error on the training data (\\(\\{y(t\_i)\\}\\), with \\(i\\in {1, \\cdots, T}\\))[^/time-series/timeseries-metrics.forecasting/#mase-wiki]
\\\[ \\operatorname{MASE}(y(t), \\hat y(t)) = \\frac{\\operatorname{MAE}(y(t), \\hat y(t))}{ \\frac{1}{H-1} \\sum\_{i=1}^H \\lvert y(t\_i) - y(t\_{i-1})\\rvert }. \\\]
Due to the scaling by the one-step ahead naive forecast, MASE is easier to interpret. If MASE is large, the deviation in our forecasts is comparable to the rough scale of the time series. Naively, we expect a good MASE to be smaller than 1.
### RMSLE
The Root Mean Squared Log Error (RMSLE) is
\\\[ \\begin{align} &\\operatorname{RMSLE(y(t), \\hat y(t))} \\\\ = &\\operatorname{MSE\\left( \\ln(y(t) + 1), \\ln(\\hat y(t) + 1) \\right)} \\\\ = &\\sqrt{ \\frac{1}{H} \\sum\_{i=1}^T \\left( \\ln (y(t) + 1) - \\ln (\\hat y(t) +1 ) \\right)^2 }. \\end{align} \\\]
![]()
![]()
### MAPE
The Mean Absolute Percent Error (MAPE) is a bounded metric defined as
\\\[ \\operatorname{MAPE(y(t), \\hat y(t))} = \\frac{1}{H} \\sum\_{i=1}^H \\left\\lvert \\frac{y(t\_i) - \\hat y(t\_i)}{y(t\_i)} \\right\\rvert. \\\]
![]()
![]()
### sMAPE
The [symmetric Mean Absolute Percent Error (sMAPE)]() is a symmetrized version of MAPE
\\\[ \\operatorname{sMAPE}(y(t), \\hat y(t)) = \\frac{1}{H} \\sum\_{i=1}^H \\frac{\\lvert y(t\_i) - \\hat y(t\_i) \\rvert}{ \\lvert y(t\_i) + \\hat y(t\_i) \\rvert/2 }. \\\]
![]()
![]()
> [!NOTE]
>
> **sMAPE is Bounded but Hard to Get a Feeling**
>
> Even though sMAPE is bounded and it solves the blow-up problem in MAPE, it is dangerous to use sMAPE alone. For example, given true values \\(\[1\]\\), forecasting \\(\[10\]\\) gives us sMAPE value \\(1.636\\); Forecasting \\(\[100\]\\) gives us sMAPE value \\(1.960\\); Forecasting \\(\[1000\]\\) gives us sMAPE value \\(1.996\\). The later are not too different judging by the sMAPE values.
>
> That being said, as the sMAPE value gets a bit larger, it is hard to get stable intuitions on how bad the forecast is.
### wMAPE
The [weighted Mean Absolute Percent Error (wMAPE)]() is
\\\[ \\operatorname{wMAPE}(y(t), \\hat y(t)) = \\frac{\\sum\_{i=1}^H w\_i \\lvert y(t\_i) - \\hat y(t\_i) \\rvert }{\\sum\_{i=1}^H w\_i}. \\\]
### Quantile Loss
The Quantile loss is defined as [^/time-series/timeseries-metrics.forecasting/#bib-Gneiting2011-rr][^/time-series/timeseries-metrics.forecasting/#bib-Koenker1978-lf][^/time-series/timeseries-metrics.forecasting/#bib-De_Vargas_Staudacher2022-en]
\\\[ \\operatorname{QL}(y(t), \\hat y(t)) = \\sum\_{t=1}^H \\sum\_{q}\\left( q (y(t) - \\hat y(t))\_+ + (1-q) (\\hat y(t) - y(t))\_+ \\right), \\\]
where \\({}\_{+}\\) indicates that we only take positive values.
> [!NOTE]
>
> **Quantile Loss has many names**
>
> The quantile loss is also called quantile score, pinball loss, quantile risk or \\(\\rho\\)-risk.
### Other Metrics
We do not have a full collection of all metrics available. But we also explain some more complicated metrics, e.g., [CRPS](), as individual sections.
## Metrics Applied on a Toy Problem
To feel the difference between each metric, we assume a simple forecasting problem with some artificial time series data.
We construct the artificial data by summing a sine series and a linear series.
![artificial data]()
We have prepared three naive forecasts,
1. forecasting constant values using the last observation,
2. forecasting the sin component of the actual data,
3. forecasting the linear component of the actual data.
We calculated the metrics for the three different scenarios.
![Metrics Demo]()
---
**Related:** [Continuous Ranked Probability Score (CRPS)]() · [Naive Forecasts]()
[^/time-series/timeseries-metrics.forecasting/#Hyndman2021]: Hyndman, R.J., & Athanasopoulos, G. (2021) Forecasting: principles and practice, 3rd edition, OTexts: Melbourne, Australia. OTexts.com/fpp3. Accessed on 2022-11-27.
[^/time-series/timeseries-metrics.forecasting/#max-norm-wiki]: Contributors to Wikimedia projects. Uniform norm. In: Wikipedia \[Internet\]. 23 Oct 2022 \[cited 5 Mar 2023\]. Available: [https://en.wikipedia.org/wiki/Uniform\_norm]()
[^/time-series/timeseries-metrics.forecasting/#mase-wiki]: Contributors to Wikimedia projects. Mean absolute scaled error. In: Wikipedia \[Internet\]. 11 Jan 2023 \[cited 5 Mar 2023\]. Available: [https://en.wikipedia.org/wiki/Mean\_absolute\_scaled\_error]()
[^/time-series/timeseries-metrics.forecasting/#bib-Hyndman2006-ld]: Hyndman R.J., Koehler A.B.. Another look at measures of forecast accuracy. *International journal of forecasting*. 2006. [https://www.sciencedirect.com/science/article/pii/S0169207006000239]()
[^/time-series/timeseries-metrics.forecasting/#bib-Salinas2017-hg]: Salinas D., Flunkert V., Gasthaus J.. DeepAR: Probabilistic Forecasting with Autoregressive Recurrent Networks. 2017. [http://arxiv.org/abs/1704.04110]()
[^/time-series/timeseries-metrics.forecasting/#bib-Gneiting2011-rr]: Gneiting T.. Quantiles as optimal point forecasts. *International journal of forecasting*. 2011. [https://www.sciencedirect.com/science/article/pii/S0169207010000063]()
[^/time-series/timeseries-metrics.forecasting/#bib-Koenker1978-lf]: Koenker R., Bassett G.. Regression Quantiles. *Econometrica: journal of the Econometric Society*. 1978. [http://www.jstor.org/stable/1913643]()
[^/time-series/timeseries-metrics.forecasting/#bib-De_Vargas_Staudacher2022-en]: Vargas Staudacher J.M.R., Wu B., Struss C. et al.. Uncertainty Quantification and Probabilistic forecasting of big data time series at Amazon Supply Chain. 2022. [https://www.mdsi.tum.de/fileadmin/w00cet/di-lab/pdf/Amazon\_SS2022\_Final\_Report.pdf]()
# Continuous Ranked Probability Score (CRPS)
> [!NOTE]
>
> **In one minute**
>
> CRPS scores a probabilistic forecast against the one value that actually happened. It compares the forecast's cumulative distribution with a step at the observed value: the closer and sharper the distribution around the truth, the lower the score. For a point forecast it reduces to the absolute error.
>
> **Read first:** [Time Series Forecasting Metrics]()
The Continuous Ranked Probability Score, aka CRPS, is a score to measure how a proposed distribution approximates the data, without knowledge about the true distributions of the data.
## Definition
CRPS is defined as[^/time-series/timeseries-metrics.forecasting.crps/#Hersbach2000]
\\\[ \\operatorname{CRPS}(P, x\_a) = \\int\_{-\\infty}^\\infty \\lVert P(x) - H(x - x\_a) \\rVert\_2^2 dx, \\\]
where
- \\(x\_a\\) is the true value of \\(x\\),
- P(x) is our proposed cumulative distribution for \\(x\\),
- \\(H(x)\\) is the Heaviside step function,
- \\(\\lVert \\cdot \\rVert\_2\\) is the L2 norm.
> [!NOTE]
>
> **Heaviside Step Function**
>
> \\\[ H(x - x\_a) = \\begin{cases} 1, &\\qquad x\\geq x\_a\\\\ 0, &\\qquad x\< x\_a\\\\ \\end{cases} \\\]
## Explain it
The formula looks abstract on first sight, but it becomes crystal clear once we understand it.
Note that the distribution that corresponds to a Heaviside CDF is the delta function \\(\\delta(x-x\_a)\\). What this score is calculating is the difference between our distribution and a delta function. If we have a model that minimizes CRPS, then we are looking for a distribution that is close to the delta function \\(\\delta(x-x\_a)\\). In other words, we want our distribution to be large around \\(x\_a\\).
Try it: move the forecast distribution and watch the shaded gap between its CDF and the step at the observed value. The score below is the exact CRPS of a normal forecast, \\(\\int (F(x) - H(x - x\_a))^2 dx\\).
An interactive chart of a normal forecast's CDF against the step at the observed value, with the CRPS computed live. It needs JavaScript; the scenarios below show the same idea in figures.
To illustrate what the integrand \\(\\lVert P(x) - H(x - x\_a) \\rVert\_2^2\\) means, we apply some shades to the integrand of the integral in CRPS. We visualize four different scenarios.
> [!NOTE]
>
> **Scenario 1: The predicted CDF \\(P(x)\\) is reaching 1 very fast.**
>
> ![When the proposed CDF \\(P(x)\\) is reaching 1 faster]()
> [!NOTE]
>
> **Scenario 2: The predicted CDF \\(P(x)\\) is reaching 1 quite late.**
>
> ![When the proposed CDF \\(P(x)\\) is reaching 1 slower]()
> [!NOTE]
>
> **Scenario 3: The predicted CDF \\(P(x)\\) is reaching 1 around the Heaviside function jump.**
>
> ![When the proposed CDF \\(P(x)\\) is close to the Heaviside function]()
> [!NOTE]
>
> **Scenario 4: The predicted CDF \\(P(x)\\) is steadily increasing but very dispersed.**
>
> ![When the proposed CDF \\(P(x)\\) is dispersed around \\(x\_a\\)]()
With the four different scenarios visualized, intuitively, the only way to get a small CRPS score is to choose a distribution that is focused around \\(x\_a\\). Echoing a previous note on the delta function being the density function of the Heaviside function, we expect a small CRPS reflects a scenario of the following: the predicted distribution \\(\\rho(x)\\) is very focused around the observation \\(x\_a\\).
![densities of \\(P(x)\\) and \\(H(x-x\_a)\\)]()
## Discussions
Gebetsberger et al found that CRPS is more robust compared to Likelihood while producing similar results if we use a good assumption for the data distribution[^/time-series/timeseries-metrics.forecasting.crps/#Gebetsberger2018].
CRPS is also very useful in time series forecasting. For example, the integrand of CRPS can be used as the loss function in model training [^/time-series/timeseries-metrics.forecasting.crps/#Gouttes2021].
[^/time-series/timeseries-metrics.forecasting.crps/#Hersbach2000]: [Hersbach H. Decomposition of the Continuous Ranked Probability Score for Ensemble Prediction Systems. Weather Forecast. 2000;15: 559–570. doi:10.1175/1520-0434(2000)015\<0559:DOTCRP\>2.0.CO;2]()
[^/time-series/timeseries-metrics.forecasting.crps/#Gouttes2021]: [Gouttes A, Rasul K, Koren M, Stephan J, Naghibi T. Probabilistic Time Series Forecasting with Implicit Quantile Networks. arXiv \[cs.LG\]. 2021. doi:10.48550/arXiv.2107.03743]()
[^/time-series/timeseries-metrics.forecasting.crps/#Gebetsberger2018]: [Gebetsberger M, Messner JW, Mayr GJ, Zeileis A. Estimation Methods for Nonhomogeneous Regression Models: Minimum Continuous Ranked Probability Score versus Maximum Likelihood. Mon Weather Rev. 2018;146: 4323–4338. doi:10.1175/MWR-D-17-0364.1]()
# Hierarchical Time Series Data
> [!NOTE]
>
> **In one minute**
>
> Many datasets have structure: store sales add up to state sales, which add up to the total. A summing matrix S encodes these relations by mapping the bottom-level series to every level, and forecasts that respect it are called coherent. The M5 store sales serve as the example.
Many real-world time series data assert some internal structure among the series. For example, the dataset used in the [M5 competition]() is the sales data of different items but with the store and category information provided[^/time-series/timeseries-hierarchical.data/#Makridakis2022]. For simplicity, we simplified the dataset to only include the hierarchy of stores.
The simplified dataset can be found [here](). The original data can [be found on the website of IIF](). In this simplified version of the M5 dataset, we have the following hierarchy.
```
flowchart LR
top["Total Sales"]
ca["Sales in California"]
tx["Sales in Texas"]
wi["Sales in Wisconsin"]
top --- ca
top --- tx
top --- wi
subgraph California
ca1["Sales in Store #1 in CA"]
ca2["Sales in Store #2 in CA"]
ca3["Sales in Store #3 in CA"]
ca4["Sales in Store #4 in CA"]
ca --- ca1
ca --- ca2
ca --- ca3
ca --- ca4
end
subgraph Texas
tx1["Sales in Store #1 in TX"]
tx2["Sales in Store #2 in TX"]
tx3["Sales in Store #3 in TX"]
tx --- tx1
tx --- tx2
tx --- tx3
end
subgraph Wisconsin
wi1["Sales in Store #1 in WI"]
wi2["Sales in Store #2 in WI"]
wi3["Sales in Store #3 in WI"]
wi --- wi1
wi --- wi2
wi --- wi3
end
```
The above tree is useful when thinking about the hierarchies. For example, it explicitly tells us that the sales in stores \#1, \#2, \#3 in TX should sum up to the sales in TX.
We plotted the sales in CA as well as the individual stores in CA. We can already observe some synchronized anomalies.
![M5 Data of each store Full]()
![M5 Data of each store 2015]()
## Summing Matrix
The relations between the series is represented using a **summing matrix** \\(\\mathbf S\\), which connects the bottom level series \\(\\mathbf b\\) and all the possible levels \\(\\mathbf s\\)[^/time-series/timeseries-hierarchical.data/#Hyndman2021]
\\\[ \\mathbf y(t) = \\mathbf S \\mathbf b(t). \\\]
If our forecasts satisfy this relation, we claim our forecasts to be **coherent**[^/time-series/timeseries-hierarchical.data/#Hyndman2021].
> [!NOTE]
>
> **Summing Matrix Example**
>
> We take part of the above dataset and only consider the hierarchy of states,
>
> \\\[ s(t) = s\_\\mathrm{CA}(t) + s\_\\mathrm{TX}(t) + s\_\\mathrm{WI}(t). \\\]
>
> The hierarchy is also revealed in the following tree.
>
> ```
> flowchart TD
>
> top["Total Sales"]
>
> ca["Sales in California"]
> tx["Sales in Texas"]
> wi["Sales in Wisconsin"]
>
> top --- ca
> top --- tx
> top --- wi
> ```
>
> In this example, the bottom level series are denoted as
>
> \\\[ \\mathbf b(t) = \\begin{pmatrix} s\_\\mathrm{CA}(t) \\\\ s\_\\mathrm{TX}(t) \\\\ s\_\\mathrm{WI}(t) \\end{pmatrix}, \\\]
>
> and all the possible levels are denoted as
>
> \\\[ \\mathbf y(t) = \\begin{pmatrix} s(t) \\\\ s\_\\mathrm{CA}(t) \\\\ s\_\\mathrm{TX}(t) \\\\ s\_\\mathrm{WI}(t) \\end{pmatrix}. \\\]
>
> The summing matrix is
>
> \\\[ \\mathbf S = \\begin{pmatrix} 1 & 1 & 1 \\\\ 1 & 0 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 0 & 1 \\end{pmatrix}. \\\]
---
**Related:** [Hierarchical Time Series Reconciliation]()
[^/time-series/timeseries-hierarchical.data/#Makridakis2022]: Makridakis S, Spiliotis E, Assimakopoulos V. The M5 competition: Background, organization, and implementation. Int J Forecast. 2022;38: 1325–1336. doi:10.1016/j.ijforecast.2021.07.007
[^/time-series/timeseries-hierarchical.data/#Hyndman2021]: Hyndman, R.J., & Athanasopoulos, G. (2021) Forecasting: principles and practice, 3rd edition, OTexts: Melbourne, Australia. OTexts.com/fpp3. Accessed on 2022-11-27.
# Hierarchical Time Series Reconciliation
> [!NOTE]
>
> **In one minute**
>
> Forecasting each level of a hierarchy separately gives numbers that don't add up. Reconciliation is a post-processing step: a matrix P maps the base forecasts to bottom-level forecasts, and the summing matrix S maps those back to all levels, which makes them coherent. MinT, one way to choose P, is worked through with examples, theory and real data.
>
> **Read first:** [Hierarchical Time Series Data](