# 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]() Reconciliation is a post-processing method to adjust the forecasts to be coherent. Given **base forecasts** \\(\\hat{\\mathbf y}(t)\\) (forecasts for all levels but each level forecasted independently), we use \\(\\mathbf P\\) to map them to the bottom-level forecasts \\\[ \\begin{equation} \\tilde{\\mathbf b}(t) = \\mathbf P \\hat{\\mathbf y}(t). \\end{equation} \\\] > [!NOTE] > > **\\(P\\) and \\(S\\)** > > In the [previous section](), we discussed the summing matrix \\(\\color{blue}S\\). The summing matrix maps the bottom-level forecasts \\(\\color{red}{\\mathbf b}(t)\\) to all forecasts on all levels \\(\\color{green}\\mathbf y(t)\\). The example we provided was > > \\\[{\\color{green}\\begin{pmatrix} s(t) \\\\ s\_\\mathrm{CA}(t) \\\\ s\_\\mathrm{TX}(t) \\\\ s\_\\mathrm{WI}(t) \\end{pmatrix}} = {\\color{blue}\\begin{pmatrix} 1 & 1 & 1 \\\\ 1 & 0 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 0 & 1 \\end{pmatrix}} {\\color{red}\\begin{pmatrix} s\_\\mathrm{CA}(t) \\\\ s\_\\mathrm{TX}(t) \\\\ s\_\\mathrm{WI}(t) \\end{pmatrix}}. \\\] > > If we forecast different levels independently, the forecasts we get > > \\\[ \\hat{\\mathbf y}(t) = \\begin{pmatrix} \\hat s(t) \\\\ \\hat s\_\\mathrm{CA}(t) \\\\ \\hat s\_\\mathrm{TX}(t) \\\\ \\hat s\_\\mathrm{WI}(t) \\end{pmatrix}, \\\] > > are not necessarily coherent. However, if we can choose a proper \\(\\mathbf P\\), we can convert the base forecasts into some bottom-level forecasts > > \\\[ \\begin{pmatrix} \\tilde s\_\\mathrm{CA}(t) \\\\ \\tilde s\_\\mathrm{TX}(t) \\\\ \\tilde s\_\\mathrm{WI}(t) \\end{pmatrix} = \\mathbf P \\begin{pmatrix} \\hat s(t) \\\\ \\hat s\_\\mathrm{CA}(t) \\\\ \\hat s\_\\mathrm{TX}(t) \\\\ \\hat s\_\\mathrm{WI}(t) \\end{pmatrix}. \\\] > > From the usage, \\(\\mathbf S\\) and \\(\\mathbf P\\) are like conjugates. We have the following relation > > \\\[ \\begin{pmatrix} \\tilde s\_\\mathrm{CA}(t) \\\\ \\tilde s\_\\mathrm{TX}(t) \\\\ \\tilde s\_\\mathrm{WI}(t) \\end{pmatrix} = \\mathbf P \\mathbf S {\\color{red}\\begin{pmatrix} s\_\\mathrm{CA}(t) \\\\ s\_\\mathrm{TX}(t) \\\\ s\_\\mathrm{WI}(t) \\end{pmatrix}}. \\\] > > It is clear that \\(\\mathbf P \\mathbf S\\) is identity if we set > > \\\[ \\begin{pmatrix} \\tilde s\_\\mathrm{CA}(t) \\\\ \\tilde s\_\\mathrm{TX}(t) \\\\ \\tilde s\_\\mathrm{WI}(t) \\end{pmatrix} = {\\color{red}\\begin{pmatrix} s\_\\mathrm{CA}(t) \\\\ s\_\\mathrm{TX}(t) \\\\ s\_\\mathrm{WI}(t) \\end{pmatrix}}. \\\] > > However, this is not the only \\(\\mathbf P\\) we can choose. To generate the coherent forecasts \\(\\tilde{\\mathbf y}(t)\\), we use [the summing matrix]() to map the bottom level forecasts to base forecasts of all levels[^/time-series/timeseries-hierarchical.reconciliation/#Hyndman2021][^/time-series/timeseries-hierarchical.reconciliation/#bib-Rangapuram2021-xi] \\\[ \\begin{equation} \\tilde{\\mathbf y}(t) = \\mathbf S\\tilde{\\mathbf b}(t) = \\mathbf S \\mathbf P \\hat{\\mathbf y}(t). \\label{eq:reconciliation-compact-form} \\end{equation} \\\] > [!NOTE] > > **Walmart Sales in Stores** > > We reuse the example of the [Walmart sales data](). The base forecasts for all levels are > > \\\[ \\hat{\\mathbf y}(t) = \\begin{pmatrix} \\hat s(t) \\\\ \\hat s\_\\mathrm{CA}(t) \\\\ \\hat s\_\\mathrm{TX}(t) \\\\ \\hat s\_\\mathrm{WI}(t) \\end{pmatrix}. \\\] > > The simplest mapping to the bottom-level forecasts is > > \\\[ \\tilde{\\mathbf b}(t) = \\begin{pmatrix} 0 & 1 & 0 & 0 \\\\ 0 & 0 & 1 & 0 \\\\ 0 & 0 & 0 & 1 \\end{pmatrix}\\begin{pmatrix} \\hat s(t) \\\\ \\hat s\_\\mathrm{CA}(t) \\\\ \\hat s\_\\mathrm{TX}(t) \\\\ \\hat s\_\\mathrm{WI}(t) \\end{pmatrix}. \\\] > > where > > \\\[ \\tilde{\\mathbf b}(t) = \\begin{pmatrix} \\tilde s\_\\mathrm{CA}(t) \\\\ \\tilde s\_\\mathrm{TX}(t) \\\\ \\tilde s\_\\mathrm{WI}(t) \\end{pmatrix} \\\] > > are the bottom-level forecasts to be transformed into coherent forecasts. > > In this simple method, our mapping matrix \\(\\mathbf P\\) can be > > \\\[ \\mathbf P = \\begin{pmatrix} 0 & 1 & 0 & 0 \\\\ 0 & 0 & 1 & 0 \\\\ 0 & 0 & 0 & 1 \\end{pmatrix}. \\\] > > Using this \\(\\mathbf P\\), we get > > \\\[ \\tilde{\\mathbf b}(t) = \\hat{\\mathbf b}(t) = \\begin{pmatrix} \\hat s\_\\mathrm{CA}(t) \\\\ \\hat s\_\\mathrm{TX}(t) \\\\ \\hat s\_\\mathrm{WI}(t) \\end{pmatrix}. \\\] > > The last step is to apply the summing matrix > > \\\[ \\mathbf S = \\begin{pmatrix} 1 & 1 & 1 \\\\ 1 & 0 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 0 & 1 \\end{pmatrix}, \\\] > > so that > > \\\[ \\tilde{\\mathbf y}(t) = \\mathbf S \\tilde{\\mathbf b}(t) = \\begin{pmatrix} \\hat s\_\\mathrm{CA}(t) + \\hat s\_\\mathrm{TX}(t) + \\hat s\_\\mathrm{WI}(t) \\\\ \\hat s\_\\mathrm{CA}(t) \\\\ \\hat s\_\\mathrm{TX}(t) \\\\ \\hat s\_\\mathrm{WI}(t) \\end{pmatrix}. \\\] > > In summary, our coherent forecasts for each level are > > \\\[ \\begin{align} \\tilde s (t) &= \\hat s\_\\mathrm{CA}(t) + \\hat s\_\\mathrm{TX}(t) + \\hat s\_\\mathrm{WI}(t) \\\\ \\tilde s\_\\mathrm{CA}(t) &= \\hat s\_\\mathrm{CA}(t) \\\\ \\tilde s\_\\mathrm{TX}(t) &= \\hat s\_\\mathrm{TX}(t) \\\\ \\tilde s\_\\mathrm{WI}(t) &= \\hat s\_\\mathrm{WI}(t). \\end{align} \\\] > > The \\(\\mathbf P\\) we used in this example represents the **bottom-up method**. > > Results like \\(\\tilde s\_\\mathrm{CA}(t) = \\hat s\_\\mathrm{CA}(t)\\) look comfortable but they are not necessary. In other reconciliation methods, these relations might be broken, i.e., \\(\\tilde s\_\\mathrm{CA}(t) = \\hat s\_\\mathrm{CA}(t)\\) may not be true. > [!NOTE] > > **Component Form** > > We rewrite > > \\\[ \\tilde{\\mathbf y}(t) = \\mathbf S \\mathbf P \\hat{\\mathbf y}(t) \\\] > > using the component form > > \\\[ \\tilde y\_i = S\_{ij} G\_{jk} \\hat y\_k. \\\] There is more than one \\(\\mathbf P\\) that can map the forecasts to the bottom-level forecasts. Three of the so-called single-level approaches[^/time-series/timeseries-hierarchical.reconciliation/#Hyndman2021] are bottom-up, top-down, and middle-out[^/time-series/timeseries-hierarchical.reconciliation/#bib-Rangapuram2021-xi]. Apart from these intuitive methods, Wickramasuriya et al. (2017) proposed the MinT method to find the optimal \\(\\mathbf P\\) matrix that gives us the minimal trace of the covariance of the **reconciled forecast error**[^/time-series/timeseries-hierarchical.reconciliation/#bib-Wickramasuriya2019-cv], \\\[ \\tilde{\\boldsymbol \\epsilon} = \\mathbf y(t) - \\tilde{\\mathbf y}(t), \\\] with \\(\\mathbf y\\) being the ground truth and \\(\\tilde{\\mathbf y}\\) being the coherent forecasts. Wickramasuriya et al. (2017) showed that the optimal \\(\\mathbf P\\) is \\\[ \\begin{equation} \\hat{\\mathbf P} = (\\mathbf S^T \\mathbf W(t)^{-1} \\mathbf S)^{-1} (\\mathbf S^{T}\\mathbf W(t)^{-1}), \\label{eq-mint-p} \\end{equation} \\\] where \\(W\_{h} = \\mathbb E\\left\[ \\tilde{\\boldsymbol \\epsilon} \\tilde{\\boldsymbol \\epsilon}^T \\right\] = \\mathbb E \\left\[ (\\mathbf y(t) - \\tilde{\\mathbf y}(t))(\\mathbf y(t) - \\tilde{\\mathbf y}(t))^T \\right\]\\) is the covariance matrix of the reconciled forecast error. > [!NOTE] > > **\\(\\hat{\\mathbf P} \\neq \\mathbf I\\)** > > Note that \\(\\mathbf S\\) is not a square matrix and we can't simply apply the inverse on each element, > > \\\[ (\\mathbf S^T \\mathbf W(t)^{-1} \\mathbf S)^{-1} \\neq \\mathbf S^{-1} \\mathbf W(t) {\\mathbf S^T}^{-1}. \\\] MinT is easy to calculate but it assumes that the forecasts are unbiased. To relieve this constraint, Van Erven & Cugliari (2013) proposed a game-theoretic method called GTOP[^/time-series/timeseries-hierarchical.reconciliation/#bib-Van_Erven2015-ht]. In deep learning, Rangapuram et al. (2021) developed an end-to-end model for coherent probabilistic hierarchical forecasts[^/time-series/timeseries-hierarchical.reconciliation/#bib-Rangapuram2021-xi]. For these advanced topics, we redirect the readers to the original papers. ## MinT Examples ### Theories To see how the MinT method works, we calculate a few examples based on equation \\(\\eqref{eq-mint-p}\\). For simplicity, we assume that the variance \\(\\mathbf W\\) is diagonal[^/time-series/timeseries-hierarchical.reconciliation/#bib-Wickramasuriya2019-cv]. Note that the matrix \\(\\mathbf S \\mathbf P\\) decides how each original forecast is combined, \\(\\tilde{\\mathbf y} = \\mathbf S \\mathbf P \\hat{\\mathbf y}\\). It will be the key for us to understand how MinT works. In the following examples, we observe that the lower variance of the reconciled forecast error \\(W\_{ii}\\), the less change in the reconciled result. Since lower values of \\(W\_{ii}\\) indicate lower reconciled forecast error, reconciliation should not adjust it by a lot. For a 2-level hierarchical forecasting problem, the shape of the \\(\\mathbf S\\) matrix is (3,2) and we have three values to pre-compute or assume, i.e., the diagonal elements of \\(\\mathbf W\\). | \\(\\mathbf S\\) | \\(\\mathbf P\\) | \\(\\mathbf S \\mathbf P\\) | | --- | --- | --- | | \\(\\left\[\\begin{matrix}1 & 1\\\\1 & 0\\\\0 & 1\\end{matrix}\\right\]\\) | \\(\\left\[\\begin{matrix}\\frac{- \\frac{W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}} + \\frac{W\_{1} W\_{2} + W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}}}{W\_{1}} & \\frac{W\_{1} W\_{2} + W\_{2} W\_{3}}{W\_{2} \\left(W\_{1} + W\_{2} + W\_{3}\\right)} & - \\frac{W\_{2}}{W\_{1} + W\_{2} + W\_{3}}\\\\\\frac{- \\frac{W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}} + \\frac{W\_{1} W\_{3} + W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}}}{W\_{1}} & - \\frac{W\_{3}}{W\_{1} + W\_{2} + W\_{3}} & \\frac{W\_{1} W\_{3} + W\_{2} W\_{3}}{W\_{3} \\left(W\_{1} + W\_{2} + W\_{3}\\right)}\\end{matrix}\\right\]\\) | \\(\\left\[\\begin{matrix}\\frac{- \\frac{2 W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}} + \\frac{W\_{1} W\_{2} + W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}} + \\frac{W\_{1} W\_{3} + W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}}}{W\_{1}} & \\frac{- \\frac{W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}} + \\frac{W\_{1} W\_{2} + W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}}}{W\_{2}} & \\frac{- \\frac{W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}} + \\frac{W\_{1} W\_{3} + W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}}}{W\_{3}}\\\\\\frac{- \\frac{W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}} + \\frac{W\_{1} W\_{2} + W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}}}{W\_{1}} & \\frac{W\_{1} W\_{2} + W\_{2} W\_{3}}{W\_{2} \\left(W\_{1} + W\_{2} + W\_{3}\\right)} & - \\frac{W\_{2}}{W\_{1} + W\_{2} + W\_{3}}\\\\\\frac{- \\frac{W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}} + \\frac{W\_{1} W\_{3} + W\_{2} W\_{3}}{W\_{1} + W\_{2} + W\_{3}}}{W\_{1}} & - \\frac{W\_{3}}{W\_{1} + W\_{2} + W\_{3}} & \\frac{W\_{1} W\_{3} + W\_{2} W\_{3}}{W\_{3} \\left(W\_{1} + W\_{2} + W\_{3}\\right)}\\end{matrix}\\right\]\\) | We visualize the matrix \\(\\mathbf S\\mathbf P\\). It is straightforward to verify that it always leads to coherent results. ![S \* P]() ``` import sympy as sp import numpy as np import seaborn as sns class MinTMatrices: def __init__(self, levels: int): self.levels = levels @property def s(self): s_ident_diag = np.diag([1] * (self.levels - 1)).tolist() return sp.Matrix( [ [1] * (self.levels - 1), ] + s_ident_diag ) @property def w_diag_elements(self): return tuple( sp.Symbol(f"W_{i}") for i in range(1, self.levels + 1) ) @property def w(self): return sp.Matrix(np.diag(self.w_diag_elements).tolist()) @property def p_left(self): return sp.Inverse( sp.MatMul(sp.Transpose(self.s), sp.Inverse(self.w), self.s) ) @property def p_right(self): return ( sp.MatMul(sp.Transpose(self.s), sp.Inverse(self.w)) ) @property def p(self): return sp.MatMul(self.p_left, self.p_right) @property def s_p(self): return sp.MatMul(self.s, self.p) @property def s_p_numerical(self): return sp.lambdify( self.w_diag_elements, self.s_p ) def visualize_s_p(self, w_elements, ax): sns.heatmap(self.s_p_numerical(*w_elements), annot=True, cbar=False, ax=ax) ax.grid(False) ax.set(xticklabels=[], yticklabels=[]) ax.tick_params(bottom=False, left=False) ax.set_title(f"$W_{{diag}} = {w_elements}$") return ax mtm_3 = MinTMatrices(levels=3) print( f"s: {sp.latex(mtm_3.s)}\n" f"p: {sp.latex(mtm_3.p.as_explicit())}\n" f"s_p: {sp.latex(mtm_3.s_p.as_explicit())}\n" ) # 2 bottom series, in total three series mtm_3.s mtm_3.p mtm_3.s_p.as_explicit() w_elements = [ (1,1,1), (2,1,1) ] fig, axes = plt.subplots(nrows = 1, ncols=2, figsize=(4 * 2, 4)) for idx, w in enumerate(w_elements): mtm_3.visualize_s_p(w, axes[idx]) fig.show() ``` > [!NOTE] > > **Implementations** > > There are different methods to get the covariance matrix \\(\\mathbf W\\). We discuss a few examples and their implications. > > | method | \\(\\mathbf W\\) | Note | > | --- | --- | --- | > | OLS | \\(\\mathbf I\\) | More weight on the higher levels in the hierarchy | > | Structual Scaling | \\(\\operatorname{diag}(\\mathbf S \\mathbf I)\\) | Less weight on higher levels compared to OLS | ### Real-world Data > [!NOTE] > > **Code** > > The code for this subsection can be found in [this notebook]() (also available on [Google Colab]()). We use a [small subset of the M5 competition data]() to show that MinT works by shifting the values on different hierarchies. | date | CA | TX | WI | CA\_1 | CA\_2 | CA\_3 | CA\_4 | TX\_1 | TX\_2 | TX\_3 | WI\_1 | WI\_2 | WI\_3 | Total | | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | | 2011-01-29 00:00:00 | 14195 | 9438 | 8998 | 4337 | 3494 | 4739 | 1625 | 2556 | 3852 | 3030 | 2704 | 2256 | 4038 | 32631 | | 2011-01-30 00:00:00 | 13805 | 9630 | 8314 | 4155 | 3046 | 4827 | 1777 | 2687 | 3937 | 3006 | 2194 | 1922 | 4198 | 31749 | | 2011-01-31 00:00:00 | 10108 | 6778 | 6897 | 2816 | 2121 | 3785 | 1386 | 1822 | 2731 | 2225 | 1562 | 2018 | 3317 | 23783 | | 2011-02-01 00:00:00 | 11047 | 7381 | 6984 | 3051 | 2324 | 4232 | 1440 | 2258 | 2954 | 2169 | 1251 | 2522 | 3211 | 25412 | | 2011-02-02 00:00:00 | 9925 | 5912 | 3309 | 2630 | 1942 | 3817 | 1536 | 1694 | 2492 | 1726 | 2 | 1175 | 2132 | 19146 | We apply a simple LightGBM model using Darts. The forecasts are not coherent. ![forecasts not coherent]() Applying [MinT method](), we reached coherent forecasts for all levels. The following charts shows the example for the top two levels. ![MinT -\> coherent]() Each step was adjusted differently since the forecasted values are different. To see how exactly the forecasted are adjusted to reach coherency, we plot out the difference between the reconciled results and the original forecasts, \\(\\tilde{\\mathbf y} - \\hat{\\mathbf y}\\). ![adjustments from MinT]() ## Tools and Packages [Darts]() and [hierarchicalforecast from Nixtla]() provide good support for reconciliations. [^/time-series/timeseries-hierarchical.reconciliation/#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-hierarchical.reconciliation/#bib-Rangapuram2021-xi]: Rangapuram S.S., Werner L.D., Benidis K. et al.. End-to-End Learning of Coherent Probabilistic Forecasts for Hierarchical Time Series. *Proceedings of the 38th International Conference on Machine Learning*. 2021. [https://proceedings.mlr.press/v139/rangapuram21a.html]() [^/time-series/timeseries-hierarchical.reconciliation/#bib-Wickramasuriya2019-cv]: Wickramasuriya S.L., Athanasopoulos G., Hyndman R.J.. Optimal Forecast Reconciliation for Hierarchical and Grouped Time Series Through Trace Minimization. *Journal of the American Statistical Association*. 2019. [https://doi.org/10.1080/01621459.2018.1448825]() [^/time-series/timeseries-hierarchical.reconciliation/#bib-Van_Erven2015-ht]: Erven T., Cugliari J.. Game-Theoretically Optimal Reconciliation of Contemporaneous Hierarchical Time Series Forecasts. *Modeling and Stochastic Learning for Forecasting in High Dimensions*. 2015. [http://dx.doi.org/10.1007/978-3-319-18732-7\_15]() # Time Series Datasets > [!NOTE] > > **In one minute** > > A list of real-world datasets used for forecasting (ECB exchange rates, NREL solar power, UCI electricity load, PeMS traffic) and of synthetic sources such as chaotic systems. We list a few useful real-world time series datasets here. | name | link | descriptions | | --- | --- | --- | | ECB Exchange Rate | [Website]() | [ECB Exchange Rate Details]() | | NREL Solar Power | [Website]() | | | Electricity | [UCI ElectricityLoadDiagrams20112014 Data Set]() | | | PEMS | [Caltrans PeMS]() | | Apart from real-world data, we also use synthetic data to demonstrate time series analysis and forecasting. The following are some synthetic time series datasets. | name | link | descriptions | | --- | --- | --- | | Chaotic Systems | [williamgilpin/dysts]() | [williamgilpin/dysts]() | # Time Series Dataset: ECB Exchange Rate > [!NOTE] > > **In one minute** > > Euro foreign exchange reference rates from the ECB: 41 currencies starting on 1999-01-04, with example plots and a look at missing values. We download the time series data in zip format using [this link](). We [find]() 41 currencies in this dataset. The earliest date is 1999-01-04. ![]() ![]() --- **Related:** [Time Series Datasets]() # Time Series Dataset: Solar Energy > [!NOTE] > > **In one minute** > > Synthetic solar power data from NREL for the United States in 2006, one file per plant in 5-minute steps. Nearly half of the records in the example file are zero, since there is no power at night. We download the time series data from [this link](). > NREL's Solar Power Data for Integration Studies are synthetic solar photovoltaic (PV) power plant data points for the United States representing the year 2006. When we downloaded Alabama on 2022-11-05, and loaded `Actual_30.45_-88.25_2006_UPV_70MW_5_Min.csv` as an example. We [found]() a lot of `0` entries (which is expected as the will be no power during dark nights). | Power is Zero | Number of Records | | :---: | :---: | | False | 57868 | | True | 47252 | The dataset contains multiple files with each file containing a time series with a time step of 5 minutes ([naming convention explained here]()). ![]() ![]() ![]() --- **Related:** [Time Series Datasets]() # Time Series Dataset: Electricity > [!NOTE] > > **In one minute** > > Electricity consumption of 370 clients from the UCI repository, in 15-minute steps from 2011 to the start of 2015 with no missing values, plus code to load and clean it. This dataset is provided [as the "ElectricityLoadDiagrams20112014 Data Set" on the UCI website](). It is the time series of electricity consumption of 370 points/clients. We download the time series data in zip format using [this link](). We [find]() that - in total 140256 rows and 370 series, - the earliest time is 2011-01-01 00:15:00, - the latest time is 2015-01-01 00:00:00, - a fixed time interval of 15 minutes. We only plot out three series. We only plot every 100 time steps. ![]() We fine no missing values. ![]() ## Loading and Basic Cleaning We provide some code to load the data from the UCI website. ``` import requests, zipfile, io import pandas as pd # Download from remote URL data_uri = "https://archive.ics.uci.edu/ml/machine-learning-databases/00321/LD2011_2014.txt.zip" r = requests.get(data_uri) z = zipfile.ZipFile(io.BytesIO(r.content)) z.extractall("data/uci_electricity/") # Load as pandas dataframe df = pd.read_csv( "data/uci_electricity/LD2011_2014.txt", delimiter=";", decimal=',' ).rename(columns={"Unnamed: 0": "date"}).set_index("date") df.index = pd.to_datetime(df.index) ``` --- **Related:** [Time Series Datasets]() # Time Series Dataset: PEMS > [!NOTE] > > **In one minute** > > Traffic data from the California PeMS system and how to download it (registration required). No examples are shown yet. California Department of Transportation (Caltrans) Performance Measurement System (PeMS) provides traffic data on [their website](). To download the data[^/time-series/timeseries-datasets.pems/#how-to-download], - Register on the website and wait for approval, then login. - Go to [this page]() and choose the data we need using the filter on the top. - For example, we choose Type = `Station 5-Minute` and District = `District 3`. We do not show examples of this dataset here. --- **Related:** [Time Series Datasets]() [^/time-series/timeseries-datasets.pems/#how-to-download]: VeritasYin. How to download the dataset from PeMS website? · Issue \#6 · VeritasYin/STGCN\_IJCAI-18. In: GitHub \[Internet\]. \[cited 5 Nov 2022\]. Available: [https://github.com/VeritasYin/STGCN\_IJCAI-18/issues/6]() # Trees # Tree-Based Models > [!NOTE] > > **In one minute** > > A decision tree predicts by asking a sequence of questions about the features. A toy example, deciding whether to work from home given health, weather and holidays, shows how a tree is described, how it is built from data and how easily it overfits. Trees are still powerful machine-learning models for time series forecasting. We explain the basic ideas of trees in the following sections. ## Should I Work from Home? > [!NOTE] > > We prepared a notebook for this section . To illustrate the idea of trees, we use a simple classification task: Deciding whether a person will go to the office or work from home based on an artificial dataset. ### Definition of the problem We will decide whether one should go to work today. In this demo project, we consider the following features. | feature | possible values | | :---: | :---: | | health | 0: feeling bad, 1: feeling good | | weather | 0: bad weather, 1: good weather | | holiday | 1: holiday, 0: not holiday | Our prediction will be a binary result, 0 or 1, with 0 indicates staying at home and 1 indicates going to work. > [!NOTE] > > **Notations** > > For more compactness, we can use the abstract notation \\(\\{0,1\\}^3\\) to describe a set of three features each with 0 and 1 as possible values. In general, the notation \\(\\{0,1\\}^d\\) indicates \\(d\\) binary features. > > Meanwhile, the prediction can be denoted as \\(\\{0,1\\}^1\\). ### How to Describe a Decision Tree In theory, we would expect a decision tree of the following. ``` graph TD A[health] --> |feeling bad| E[stay home] A[health] --> |feeling good| B[weather] B --> |bad weather| E B --> |good weather| C[holiday] C --> |holiday| E C --> |not holiday| G[go to the office] ``` > [!NOTE] > > It is straightforward to prove that the max required depths and max required leaves of a model that maps \\(\\{0,1\\}^d\\) to \\(\\{0,1\\}^1\\) are \\(d+1\\) and \\(2^d\\). In our simple example, some of the branches are truncated based on our understanding of the problem. In principle, the branch "feeling bad" could also go on to the next level. ### Data However, we are not always lucky enough to be able to forge trees using experience and common sense. It is more common to build the tree using data. > [!NOTE] > > **Artificial Dataset** > > To fit a model, we generated some artificial data using [this notebook](). > > When generating the data, we follow the rule that one only goes to the office, if and only if > > - the person is healthy, > - the weather is good, and > - today is not a holiday. The following table shows a small sample of the dataset. | | health | weather | holiday | go\_to\_office | | ---: | ---: | ---: | ---: | ---: | | 0 | 0 | 0 | 1 | 0 | | 1 | 1 | 1 | 1 | 0 | | 2 | 1 | 0 | 1 | 0 | | 3 | 0 | 0 | 0 | 0 | | 4 | 1 | 0 | 1 | 0 | ### Build a Tree We use sklearn to build a decision tree, see . We observed that the decision tree we get from the data is exactly what we expected. ![A decision tree trained with the dataset]() > [!NOTE] > > **Reading the Decision Tree Chart** > > On each node of the tree, we read useful information. > > In the **root**, aka the first node on the top, the feature name and value range are denoted on the first row, i.e., **weather\<= 0.5**, which means that we are making decisions based on whether the value of the weather feature is less or equal to 0.5. If the value is less or equal to 0.5, we go to the left branch, otherwise, we go to the right branch. The following rows in the node are assuming the condition is satisfied. > > On the second row, we read the [**Gini** impurity value](). Gini impurity is a measure of the impurity of the data under the condition. > > On the third row, the number of samples of the given condition (weather \<= 0.5) is also given. > > Finally, we read the values of the samples. In this example, value = \[93, 7\], i.e., 93 of the samples have a target value 0, and 7 of the samples have a target value 1. This is a perfect result as it is the same as our theoretical expectations. This is because we have built our dataset using the rules. Surely we will get a perfect tree. In reality, our dataset is probabilistic or comes with noise. To see how the noise affects our decision tree, we can build a tree using a perturbed dataset. Here is an example. ![Decision tree on data with noise]() A decision tree trained with a fake "impure dataset" with noise that doesn't always fit into our theoretical model. For example, on the **leaves**, aka, **the bottom level**, we see some with both going to the office and not going to the office, which corresponds to nonzero [Gini impurity value](). Though we take the majority target value when doing the predictions, we can already imagine that some of the data points will be misclassified. ### How was the Model Built? Many different algorithms can build a decision tree from a given dataset. The Iterative Dichotomizer 3 algorithm, aka ID3 algorithm, is one of the famous implementations of the decision tree[^/trees/tree.basics/#bib-shalev-shwartz_ben-david_2014]. The following is the "flowchart" of the algorithm[^/trees/tree.basics/#bib-shalev-shwartz_ben-david_2014]. ``` graph TD Leaf("Prepare samples in node") MajorityVote["Calculate majority vote"] Assign[Assign label to node] Leaf --> MajorityVote --> Assign Assign --> Split1[Split on feature 1] Assign --> Splitdots["..."] Assign --> Splitd[Split on feature d] subgraph "split on a subset of features" Split1 --> |"Split on feature 1"|B1["Calculate gain of split"] Splitdots --> |"..."| Bdots["..."] Splitd --> |"Split on feature d"| Bd["Calculate gain of split"] end B1 --> C["Use the split with the largest gain"] Bdots --> C Bd --> C C --> Left["Prepare samples in left node"] C --> Right["Prepare samples in right node"] subgraph "left node" MajorityVoteL["Calculate majority vote"] AssignL(Assign label to left node) Left --> MajorityVoteL --> AssignL end subgraph "right node" MajorityVoteR["Calculate majority vote"] Right --> MajorityVoteR AssignR(Assign label to right node) MajorityVoteR --> AssignR end ``` To "calculate the gain of the split", here we use [Gini impurity](). There are other "gains" such as [information gain](). For regression tasks, we can also have gains such as a MSE loss. ## Overfitting Fully grown trees will most likely to overfit the data since they always try to grow pure leaves. Besides, fully grown trees grow exponentially as the number of features grows which requires a lot of computation resources. > [!WARNING] > > Applying Occam's razor, we prefer smaller trees as long as the trees can explain the data well. To achieve this, we will either have to limit how the trees grow during training or prune the trees after the trees are built. Pruning of a tree is achieved by replacing subtrees at a node with a leaf if certain conditions are based on cost estimations. --- **Related:** [Random Forest]() [^/trees/tree.basics/#bib-shalev-shwartz_ben-david_2014]: Shalev-Shwartz S., Ben-David S.. Understanding Machine Learning: From Theory to Algorithms. *Cambridge University Press*. 2014. [https://doi.org/10.1017/CBO9781107298019]() # Random Forest > [!NOTE] > > **In one minute** > > A random forest is an ensemble of decision trees, each built on a random subset of the features, whose predictions are combined. Its predicting power is explained through the margin, the strength of the individual trees and the correlation between them; the page ends with the random forest regressor. > > **Read first:** [Tree-Based Models]() > [!NOTE] > > **From Ho TK. Random decision forests** > > "The essence of the method is to build multiple trees in randomly selected subspaces of the feature space."[^/trees/tree.random-forest/#bib-Ho1995-gk] Random forest is an ensemble method based on decision trees which are dubbed as base-learners. Instead of using one single decision tree and model on all the features, we utilize a bunch of decision trees and each tree can model on a subset of features (feature subspace). To make predictions, the results from each tree are combined using some democratization. Translating to math language, given a proper dataset \\(\\mathscr D(\\mathbf X, \\mathbf y)\\), random forest or the ensemble of trees, denoted as \\(\\{f\_i\\}\\), will predict an ensemble of results \\(\\{f\_i(\\mathbf X\_i)\\}\\), with \\(\\mathbf X\_i \\subseteq \\mathbf X\\). > [!NOTE] > > **A Good Reference for Random Forest** > > Hastie T, Tibshirani R, Friedman J. The Elements of Statistical Learning: Data Mining, Inference, and Prediction. Springer Science & Business Media; 2013. pp. 567–567. However, random forest is not "just" ensembling. There are many different ensembling methods, e.g., bootstrapping, but suffer from correlations in the trees. Random forest has two levels of randomization: - Bootstrapping the dataset by randomly selecting a subset of the training data; - Random selection of the features to train a tree. We can already use the bootstrapping step to create many models to ensemble with, however, the randomization of features is also key to a random forest model as it helps reduce the correlations between the trees[^/trees/tree.random-forest/#bib-Hastie2013-tt]. In this section, we ask ourselves the following questions. 1. How to democratize the ensemble of results from each tree? 2. What determines the quality of the predictions? 3. Why does it even work? ## Margin, Strength, and Correlations The margin of the model, the strength of the trees, and the correlation between the trees can help us understand how random forest work. ### Margin The **margin** of the tree is defined as[^/trees/tree.random-forest/#bib-Breiman2001-oj][^/trees/tree.random-forest/#bib-Bernard2010-tz] \\\[ M(\\mathbf X, \\mathbf y) = {\\color{green}P (\\{f\_i(\\mathbf X)=\\mathbf y \\})} - \\operatorname{max}\_{\\mathbf j\\neq \\mathbf y} {\\color{red}P (\\{ f\_i(\\mathbf X) = \\mathbf j \\})}. \\\] > [!NOTE] > > **Terms in the Margin Definition** > > The first term, \\({\\color{green}P (\\{f\_i(\\mathbf X)=\\mathbf y \\})}\\) is the probability of predicting the exact value in the dataset. In a random forest model, it can be calculated using > > \\\[ {\\color{green}P (\\{f\_i(\\mathbf X)=\\mathbf y \\})} = \\frac{\\sum\_{i=1}^N I(f\_i(\\mathbf X) = \\mathbf y)}{N}, \\\] > > where \\(I\\) is the indicator function that maps the correct predictions to 1 and the incorrect predictions to 0. The summation is over all the trees. > > The term \\({\\color{red}P (\\{f\_i(\\mathbf X) = \\mathbf j \\})}\\) is the probability of predicting values \\(\\mathbf j\\). The second term \\(\\operatorname{max}\_{\\mathbf j\\neq \\mathbf y} {\\color{red}P ( \\{f\_i(\\mathbf X) = \\mathbf j\\})}\\) finds the highest misclassification probabilities, i.e., the max probabilities of predicting values \\(\\mathbf j\\) other than \\(\\mathbf y\\). > [!NOTE] > > **Raw Margin** > > We can also think of the indicator function itself is also a measure of how well the predictions are. Instead of looking into the whole forest and probabilities, the **raw margin** of a single tree is defined as[^/trees/tree.random-forest/#bib-Breiman2001-oj] > > \\\[ M\_{R,i}(\\mathbf X, \\mathbf y) = I (f\_i(\\mathbf X)=\\mathbf y ) - \\operatorname{max}\_{\\mathbf j\\neq \\mathbf y} I ( f\_i(\\mathbf X) = \\mathbf j ). \\\] > > The margin is the expected value of this raw margin over each classifier. To make it easier to interpret this quantity, we only consider two possible predictions: - \\(M(\\mathbf X, \\mathbf y) \\to 1\\): We will always predict the true value, for all the trees. - \\(M(\\mathbf X, \\mathbf y) \\to -1\\): We will always predict the wrong value, for all the trees. - \\(M(\\mathbf X, \\mathbf y) \\to 0\\), we have an equal probability of predicting the correct value and the wrong value. In general, we prefer a model with higher \\(M(\\mathbf X, \\mathbf y)\\). ### Strength However, the margin of the same model is different in different problems. The same model for one problem may give us margin 1 but it might not work that well for a different problem. This can be seen in [our decision tree examples](). To bring the idea of margin to a specific problem, Breiman defined the **strength** \\(s\\) as the expected value of the margin over the dataset fed into the trees[^/trees/tree.random-forest/#bib-Breiman2001-oj][^/trees/tree.random-forest/#bib-Bernard2010-tz], \\\[ s = E\_{\\mathscr D}\[M(\\mathbf X, \\mathbf y)\]. \\\] > [!NOTE] > > **Dataset Fed into the Trees** > > This may be different in different models since there are different randomization and data selection methods. For example, in bagging, the dataset fed into the trees would be random selections of the training data. ### Correlation Naively speaking, we expect each tree takes care of different factors and spit out a different result, for ensembling to provide benefits. To quantify this idea, we define the **correlation** of raw margin between the trees[^/trees/tree.random-forest/#bib-Breiman2001-oj] \\\[ \\rho\_{ij} = \\operatorname{corr}(M\_{R,i}, M\_{R,j}) = \\frac{\\operatorname{cov}(M\_{R,i}, M\_{R,j})}{\\sigma\_{M\_{R,i}} \\sigma\_{M\_{R,j}}} = \\frac{E\[(M\_{R,i} - \\bar M\_{R,i})(M\_{R,j} - \\bar M\_{R,j})\]}{\\sigma\_{M\_{R,i}} \\sigma\_{M\_{R,j}}}. \\\] Since the raw margin tells us how likely we can predict the correct value, the correlation defined above indicates how likely two trees are functioning. If all trees are similar, the correlation is high, and ensembling won't provide much in this situation. > [!NOTE] > > To get a scalar value of the whole model, the average correlation \\(\\bar \\rho\\) over all the possible pairs is calculated. ## Predicting Power The higher the [generalization power](), the better the model is at new predictions. To measure the goodness of a random forest, the population error can be used, \\\[ P\_{err} = P\_{\\mathscr D}(M(\\mathbf X, \\mathbf y)\< 0). \\\] It has been proved that **the error almost converges in the random forest as the number of trees gets large**[^/trees/tree.random-forest/#bib-Breiman2001-oj]. The upper bound of the population error is related to the strength and the mean correlation[^/trees/tree.random-forest/#bib-Breiman2001-oj], \\\[ P\_{err} \\leq \\frac{\\bar \\rho (1-s^2) }{s^2}. \\\] To get a grasp of this upper bound, we plot out the heatmap as a function of \\(\\bar \\rho\\) and \\(s\\). ![Upper Limit of population error]() We observe that 1. The stronger the strength, the lower the population error upper bound. 2. The smaller the correlation, the lower the population error upper bound. 3. If the strength is too low, it is very hard for the model to avoid errors. 4. If the correlation is very high, it is still possible to get a decent model if the strength is high. ## Random Forest Regressor Similar to decision trees, random forest can also be used as regressors. The random forest regressor population error is capped by the average population error of trees multiplied by the correlation of trees[^/trees/tree.random-forest/#bib-Breiman2001-oj]. To see how the regressor works with data, we construct an artificial problem. The code can be accessed . A random forest with 1600 estimators can estimate the following sin data. Note that this is in-sample fitting and prediction to demonstrate the capability of representing sin data. ![Sinusoid Data]() One observation is that not all the trees spit out the same values. We observe some quite dispersed predictions from the trees but the ensemble result is very close to the true values. ![Sinusoid Data Violin]() We generate a new dataset by adding some noise to the sin dataset. By adding uniform random noise, we introduce some variance but not much bias in the data. We are cheating a bit here because this kind of data is what random forest is good at. We train a random forest model with 1300 estimators using this noise data. Note that this is in-sample fitting and prediction to demonstrate the representation capability. ![Sinusoid Data with noise]() One observation is that not all the trees spit out the same values. The predictions from the trees are sometimes dispersed and not even bell-like, the ensemble result reflects the values of the true sin data. The ensemble results are even located at the center of the noisy data where the true sin values should be. However, we will see that the distribution of the predictions is more dispersed than the model trained without noise (see the tab "Comparing Tow Scenarios"). ![Sinusoid Noise Data Violin]() The following two charts show the boxes for the two trainings. ![Sinusoid Data box]() ![Sinusoid Noise Data box]() To see the differences between the box sizes for in a more quantitive way, we plot out the box plot of the box sizes for each training. ![Comparing box sizes for each training]() --- **Related:** [Gradient Boosted Trees]() [^/trees/tree.random-forest/#bib-Ho1995-gk]: Ho T.K.. Random decision forests. *Proceedings of 3rd International Conference on Document Analysis and Recognition*. 1995. [http://dx.doi.org/10.1109/ICDAR.1995.598994]() [^/trees/tree.random-forest/#bib-Hastie2013-tt]: Hastie T., Tibshirani R., Friedman J.. The Elements of Statistical Learning: Data Mining, Inference, and Prediction. *Springer Science & Business Media*. 2013. [https://play.google.com/store/books/details?id=yPfZBwAAQBAJ]() [^/trees/tree.random-forest/#bib-Breiman2001-oj]: Breiman L.. Random Forests. *Machine learning*. 2001. [https://doi.org/10.1023/A:1010933404324]() [^/trees/tree.random-forest/#bib-Bernard2010-tz]: Bernard S., Heutte L., Adam S.. A Study of Strength and Correlation in Random Forests. *Advanced Intelligent Computing Theories and Applications*. 2010. [http://dx.doi.org/10.1007/978-3-642-14831-6\_25]() # Gradient Boosted Trees > [!NOTE] > > **In one minute** > > Boosted trees are also an ensemble, but an additive one: the prediction is the sum of the trees' predictions, and training adds one tree at a time, each chosen to reduce the remaining loss. LightGBM and XGBoost are the popular implementations. > > **Read first:** [Random Forest]() Boosted trees is another ensemble method of trees. Similar to [random forest](), boosted trees makes prediction by combining the predictions from each tree. However, instead of performing average, boosted trees are additive models where the prediction \\(f(\\mathbf X)\\) is the additions of each predictions[^/trees/tree.gbdt/#bib-Hastie2013-tt], \\\[ f(\\mathbf X) = \\sum\_t^T f\_t(\\mathbf X), \\\] where \\(f\_t(\\mathbf X)\\) is the prediction for tree \\(i\\) and \\(T\\) is the total number of trees. Given such a setup, the training becomes very different from random forests. As of 2023, there are two popular implementations of boosted trees, [LightGBM]() and [XGBoost](). Training a boosted trees model finds a sequence of trees \\\[ \\{ f\_1, f\_2, \\cdots, f\_t, \\cdots, f\_T \\}. \\\] For a specified loss function \\(\\mathscr L(\\mathbf y, \\hat{\\mathbf y})\\), the sequence of trees helps reducing the loss step by step. At step \\(i\\), the loss is \\\[ \\mathscr L(y, f\_1(\\mathbf X) + f\_2(\\mathbf X) + \\cdots + f\_i(\\mathbf X) ). \\\] To optimize the model, we have to add a tree that reduces the loss the most and approximations are applied for numerical computations[^/trees/tree.gbdt/#bib-Chen2016-mi]. > [!NOTE] > > The [XGBoost documentation]() and the original paper on XGBoost explains the idea nicely with examples. > > Chen T, Guestrin C. XGBoost: A Scalable Tree Boosting System. arXiv \[cs.LG\]. 2016. Available: [http://arxiv.org/abs/1603.02754]() > > There are more than one realization of gradient boosted trees[^/trees/tree.gbdt/#bib-Ke2017-jv][^/trees/tree.gbdt/#bib-Shi2018-bk]. --- **Related:** [Forecasting with Trees Using Darts]() [^/trees/tree.gbdt/#bib-Hastie2013-tt]: Hastie T., Tibshirani R., Friedman J.. The Elements of Statistical Learning: Data Mining, Inference, and Prediction. *Springer Science & Business Media*. 2013. [https://play.google.com/store/books/details?id=yPfZBwAAQBAJ]() [^/trees/tree.gbdt/#bib-Chen2016-mi]: Chen T., Guestrin C.. XGBoost: A Scalable Tree Boosting System. 2016. [http://arxiv.org/abs/1603.02754]() [^/trees/tree.gbdt/#bib-Ke2017-jv]: Ke G., Meng Q., Finley T. et al.. LightGBM: A Highly Efficient Gradient Boosting Decision Tree. *Advances in Neural Information Processing Systems*. 2017. [https://proceedings.neurips.cc/paper/2017/file/6449f44a102fde848669bdd9eb6b76fa-Paper.pdf]() [^/trees/tree.gbdt/#bib-Shi2018-bk]: Shi Y., Li J., Li Z.. Gradient Boosting With Piece-Wise Linear Regression Trees. 2018. [http://arxiv.org/abs/1802.05640]() # Forecasting with Trees Using Darts > [!NOTE] > > **In one minute** > > Random forest and gradient boosted trees benchmarked on the air passenger data with Darts. Trees are poor at extrapolating beyond the data they were trained on, so the trend has to be removed first, without leaking information from the future; with that care, trees are simple, robust and strong forecasters. > > **Read first:** [Random Forest]() · [Gradient Boosted Trees]() Darts provides wrappers for tree-based models. In this section, we benchmark random forest and gradient-boosting decison tree (GBDT) on the famous [air passenger dataset](). Through the benchmarks, we will see the key advantage and disadvantage of tree-based models in forecasting. > [!NOTE] > > **Just Run It** > > The notebooks created to produce the results in this section can be found and . ## The Simple Random Forest We will build different models to demonstrate the strength and weakness of random forest models. The focus will be in-sample and out-of-sample predictions. We know that trees are not quite good at extrapolating into realms where the out-of-sample distribution is different from the training data, due to the constant values assigned on each leaf. Time series forecasting in real world are often non-stationary and heteroscedastic, which implies that the distribution during test phase may be different from the distribution of the training data. ### Data We choose the famous [air passenger data](). The dataset shows the number of air passengers in each month. ![AP Data]() ### Baseline Model: "Simply Wrap the Model on the Data" A naive idea is to simply wrap a tree-based model on the data. Here is choose RandomForest from scikit-learn. ![Simple RF]() The predictions are quite off. However, if we look into the in-sample predictions, i.e., time range that the model has already seen during training, we would not have observed such bad predictions. ![In sample Simple RF]() This indicates that there are some new patterns in the data to be forecasted. That is the distribution of the data is different, i.e., the level of the values is higher than before, and the variance is also higher. This is a typical case where trees are not good. However, trees can handle such cases if we preprocess the data to bring the data to the same level and also reduce the changes in variance. ### Detrend but also a Clairvoyant Model To confirm that this is due to the mismatch of the in-sample distribution and the out-of-sample distribution, we plot out the histograms of the training series and the test series. ![Distributions]() This hints that we should at least detrend the data. In this example, we use a simple moving average while assuming multiplicative components to detrend the data. The detrended data is shown below. Without even training the model, we immediately see that forecasting for such simple patterns is easier than the patterns in the raw data. ![detrended]() To illustrate that detrending helps, we will cheat a bit to detrend the whole series to confirm that the forecasts are better. ![Detrended RF]() > [!NOTE] > > **Distribution of Detrended Data** > > ![Distributions]() ### A Formal Model to Use Detrending and without Information Leak The above method leads to a great result, however, with information leakage during the detrending. Nevertheless, this indicates the performance of trees on out-of-sample predictions if we only predict on the cycle part of the series. In a real-world case, however, we have to predict the trend accurately for this to work. To better reconstruct the trend, we use [Box-Cox transformations]() to stablize the variance first. The following plot shows the transformed data. ![Box Cox]() With the transformed data, we build a simple linear trend using the training dataset and extrapolate the trend to the dates of the prediction. ![Linear Trend]() Finally, we fit a random forest model on the detrended data, i.e., Box-Cox transformed data - linear trend, then reconstruct the predictions, i.e., predictions + linear trend + Inverse Box-Cox transformation. We observed a much better performance than the first RF we built. ![box cox + linear trend]() ### Comparisons of the Three Random Forest Models Observations by eyes showed that cheating leads to the best result, followed by a simple linear detrend model. ![Comparison]() To formally benchmark the results, we computed several metrics. For most of the metrics, the detrend (cheating) model is the best, which is expected since it is a clairvoyant model peeks into the future. The second best is the box-cox + linear trend model. ![Metric comparison]() ## Gradient Boosted Trees Similar behavior is also observed for gradient-boosted decision trees (GBDT). We perform exactly the same steps as we did for random forest model. The results are shown below. For GBDT, we also tested the linear tree model too[^/trees/tree.darts/#lgbm_linear_tree]. ![Comparison]() > [!NOTE] > > **Why Linear Tree** > > For trees, the predictions are flat lines within a bucket of values. For example, we may get the same prediction for a given feature value 10 and 10.1 as the two values are so close to each other. However, without detrending, we expect the predictions to have a uplift trend in our data. > > To count for this, LightGBM has a parameter called `linear_tree`[^/trees/tree.darts/#lgbm_linear_tree]. This parameter allows the model to fit a linear model on the leaf nodes to capture the trend. This means that we do not need to detrend the data before fitting the model. In this specific example, we see that the linear tree model performs quite well. The benchmark metrics for the GBDT are shown below. As expected, linear tree and box-cox + linear trend models beat the baseline model. ![Metric comparison]() ## Trees are Powerful Up to this point, we may get the feeling that trees are not the best choices for forecasting. As a matter of fact, trees are widely used in many competitions and have achieved a lot in forecasting[^/trees/tree.darts/#bib-Januschowski2022-qr]. Apart from being simple and robust, trees can also be made probabilistic. Trees are also attractive as our first model to try because they usually already work quite well out of the box[^/trees/tree.darts/#lightgbm_params]. --- **Related:** [Time Series Forecasting Evaluation]() [^/trees/tree.darts/#lightgbm_params]: "Out of the box" sounds like something easy to do. However, if one ever reads the list of parameters of LightGBM, the thought of "easy" will immediately diminish. [^/trees/tree.darts/#lgbm_linear_tree]: LightGBM. Parameters — LightGBM 4.3.0.99 documentation. In: LightGBM \[Internet\]. \[cited 2 Feb 2024\]. Available: [https://lightgbm.readthedocs.io/en/latest/Parameters.html\#linear\_tree]() [^/trees/tree.darts/#bib-Januschowski2022-qr]: Januschowski T., Wang Y., Torkkola K. et al.. Forecasting with trees. *International journal of forecasting*. 2022. [https://www.sciencedirect.com/science/article/pii/S0169207021001679]() # Fundamentals of Deep Learning # Deep Learning Fundamentals > [!NOTE] > > **In one minute** > > An overview of the deep learning part: why a plain feedforward network is rarely enough, how self-supervised learning helps models generalize, and the notation used in the following chapters. Deep learning, as the rising method for time series forecasting, requires the knowledge of some fundamental principles. In this part, we explain and demonstrate some popular deep learning models. Note that we do not intend to cover all models but only discuss a few popular principles. The simplest deep learning model, is a fully connected [Feedforward Neural Network (FFNN)](). A FFNN might work for in-distribution predictions, it is likely to overfit and perform poorly for out-of-distribution predictions. In reality, most of the deep learning models are much more complicated than a FFNN, and a large population of deep learning models are utilizing the self-supervised learning concept, providing better generalizations[^/deep-learning-fundamentals/#bib-Liu2020-yh]. In the following chapters, we provide some popular deep learning architectures and cool ideas. > [!NOTE] > > **Notations** > > In this document, we use the following notations. > > - Sets, domains, abstract variables, \\(X\\), \\(Y\\); > - Probability distribution \\(P\\), \\(Q\\); > - Probability density \\(p\\), \\(q\\); > - Slicing arrays from index \\(i\\) to index \\(j\\) using \\({}\_{i:j}\\). --- **Related:** [Learning from Data]() · [Neural Networks]() [^/deep-learning-fundamentals/#bib-Liu2020-yh]: Liu X., Zhang F., Hou Z. et al.. Self-supervised Learning: Generative or Contrastive. 2020. [http://arxiv.org/abs/2006.08218]() # Learning from Data > [!NOTE] > > **In one minute** > > Learning from data means extracting compressed knowledge about the world from data. Predictions can come from induction followed by deduction (first find a model, then apply it) or from transduction (predict directly from the data). Learning from data is a practice of extracting compressed knowledge about the world from data. There are many frameworks of learning. For example, the induction, deduction, and transduction schema shows different possible paths to produce predictions. ``` graph LR P[Prediction] D[Data] M[Model] D --"Induction"--> M M --"Deduction"--> P D --"Transduction"--> P ``` There are two different approaches to making predictions based on some given data. 1. Perform induction to find a good model from the data, this is called induction. Once we have a model, we can use it to make predictions, this is called deduction. 2. Directly make predictions from the data, this is called transduction. > [!NOTE] > > ***The Nature of Statistical Learning Theory*** > > Vapnik's seminal book *The Nature of Statistical Learning Theory* is a very good read for the fundamentals of learning theories[^/deep-learning-fundamentals/learning/#bib-Vapnik2010-xf]. > > Vapnik also discussed some of the key ideas in a book chapter *Estimation of Dependences Based on Empirical Data*[^/deep-learning-fundamentals/learning/#bib-Vapnik2006-pn]. In the context of machine learning, Abu-Mostafa, Magdon-Ismail, and Lin summarized the machine learning problem using the following chart [^/deep-learning-fundamentals/learning/#bib-Abu-Mostafa2012-rk]. Ultimately, we need to find an approximation \\(g\\) of the true map \\(f\\) from features \\(\\mathcal X\\) to targets \\(\\mathcal Y\\) on a specific probability distribution of features \\(P\\). This process is done by using an algorithm to select a hypothesis that works. ``` flowchart LR X[Data Samples] A[Algorithm] H[Hypotheses Set] SH[Selected Hypothesis] X --> A H --> A A --> SH ``` Based on this framework, a machine learning process usually consists of three core components[^/deep-learning-fundamentals/learning/#bib-Domingos2012-wn]. 1. Representation: Encoded data and the problem representation. 2. Evaluation: An objective function to be evaluated that guides the model. 3. Optimization: An algorithm to optimize the model so it learns what we want it to do. We will reuse this framework again and again in the following sections of this chapter. --- **Related:** [Neural Networks]() [^/deep-learning-fundamentals/learning/#bib-Vapnik2010-xf]: Vapnik V.. The nature of statistical learning theory. *Springer*. 2010. [https://www.springer.com/gp/book/9780387987804]() [^/deep-learning-fundamentals/learning/#bib-Vapnik2006-pn]: Vapnik V.. Estimation of dependences based on empirical data. *Springer*. 2006. [https://sci-hub.se/https://link.springer.com/book/10.1007/0-387-34239-7]() [^/deep-learning-fundamentals/learning/#bib-Abu-Mostafa2012-rk]: Abu-Mostafa Y.S., Magdon-Ismail M., Lin H.. Learning from data: A short course. *AMLBook*. 2012. [https://www.semanticscholar.org/paper/Learning-From-Data-Abu-Mostafa-Magdon-Ismail/1c0ed9ed3201ef381cc392fc3ca91cae6ecfc698]() [^/deep-learning-fundamentals/learning/#bib-Domingos2012-wn]: Domingos P.. A few useful things to know about machine learning. *Communications of the ACM*. 2012. [https://dl.acm.org/doi/10.1145/2347736.2347755]() # Neural Networks > [!NOTE] > > **In one minute** > > An artificial neuron responds to its inputs more or less strongly, and a network composes many neurons into complicated functions. The page builds this intuition first, then explains why neural networks are universal approximators. > > **Read first:** [Learning from Data]() Neural networks have been a buzzword for machine learning in recent years. As indicated in the name, artificial neural networks are artificial neurons connected in a network. In this section, we discuss some intuitions and theories of neural networks. > [!NOTE] > > **Artificial vs Biological** > > Neuroscientists also discuss neural networks, or neuronal networks in their research. Those are different concepts from the artificial neural networks we are going to discuss here. In this book, we use the term neural networks to refer to artificial neural networks, unless otherwise specified. ## Intuitions We start with some intuitions of neural networks before discussing the theoretical implications. ### What is an Artificial Neuron What an artificial neuron does is respond to stimulations. This response could be strong or weak depending on the strength of the stimulations. Here is an example. ![Neuron response]() Using one simple single neuron, we do not have much to build. It is just the function we observe above. However, by connecting multiple neurons in a network, we could compose complicated functions and generalize the scaler function to multi-dimensional functions. Before we connect this neuron to a network, we study a few transformations first. The response function can be shifted, scaled, or inverted. The following figure shows the effect of these transformations. ![transformations]() ### Artificial Neural Network A simple network is a collection of neurons that respond to stimulations, which could come from the responses of other neurons. ![simple neural network]() A given input signal is spread onto three different neurons. The neurons respond to this signal separately before being combined with different weights. In the language of math, given input \\(x\\), output \\(y(x)\\) is \\\[y(x) = \\sum\_{k=1}^{3} x v\_k \* \\mathrm{activation}( w\_k \* x + u\_k )\\\] where \\(\\mathrm{activation}\\) is the activation function, i.e., the response behavior of the neuron. This is a single-layer structure. > [!NOTE] > > **\\(\\mathrm{activation} \\to \\sigma\\)** > > In the following discussions, we will use \\(\\sigma\\) as a drop in replacement for \\(\\mathrm{activation}\\). To extend this naive and shallow network, we could - increase the number of neurons on one layer, i.e., go wider, or - extend the number of layers, i.e., go deeper, or - add interactions between neurons, or - include recurrent connections in the network. ![multilayer]() ### Composition Effects To build up intuitions of how multiple neurons work together, we take an example of a network with two neurons. We will solve two problems: 1. Find out if a hotel room is hot or cold. 2. Find out if the hotel room is comfortable to stay. The first task can be solved using o single neuron. Suppose our input to the neuron is the temperature of the room. The output of the neuron is a binary value, 1 for hot and 0 for cold. The following figure shows the response of the neuron. ![single neuron classification]() In the figure above, we use red for "hot" and blue for "cold". In this example, the temperature being \\(T\_1\\) means the room is cold, while that being \\(T\_2\\) and \\(T\_3\\) indicate hot rooms. However, moving on the the second problem, such monotonic functions won't work. It is only comfortable to stay in the hotel room if the temperature is neither too high nor too low. Now consider two neurons in a network. One neuron has a monotonic increasing response to the temperature, while the other has a monotonic decreasing response. The following figure shows the combined response of the two neurons. We observe that the combined response is high only when the temperature is in a certain range. ![two neuron classification]() Suppose we have three rooms with temperatures \\(T\_1\\), \\(T\_2\\), \\(T\_3\\) respectively. Only \\(T\_2\\) falls into the region of large output value which corresponds to the habitable temperature. ![two neuron classification]() > [!NOTE] > > **Mathematical Formulation** > > The above example can be formulated as $$ f(x) = \\sum\_k v\_k \\sigma(w\_k x + u\_k) $$ where \\(\\sigma\\) is some sort of monotonic activation function. > > It is a form of single hidden layer feedforward network. We will discuss this in more detail in the following sections. These two examples hint that neural networks are good at classification tasks. Neural networks excel at a variety of tasks. Since this book is about time series, we will demonstrate the power of neural networks in time series analysis. ## Universal Approximators Even a single hidden layer feedforward network can approximate any measurable function, regardless of the activation function[^/deep-learning-fundamentals/neural-net/#bib-Hornik1989-nc]. In the case of the commonly discussed sigmoid function as an activation function, a neural network for real numbers becomes \\\[ \\sum\_k v\_k \\sigma(w\_k x + u\_k) \\\] It is a good approximation of continuous functions[^/deep-learning-fundamentals/neural-net/#bib-Cybenko1989-ro]. > [!NOTE] > > **Kolmogorov's Theorem** > > Kolmogorov's theorem shows that one can use a finite number of carefully chosen continuous functions to mix up by sums and multiplication with weights to a continuous multivariable function on a compact set[^/deep-learning-fundamentals/neural-net/#bib-Hassoun2021-sh]. ## Neural Networks Can be Complicated In practice, we observe a lot of problems when the number of neurons grows, e.g., the convergence during the training slows down if we have too many layers in the network (the vanishing gradient problem) [^/deep-learning-fundamentals/neural-net/#bib-Hochreiter2008]. > [!NOTE] > > **Training** > > We have not yet discussed how to adjust the parameters in a neural network. The process is called training. The most popular method is backpropagation[^/deep-learning-fundamentals/neural-net/#Nielsen]. The reader should understand that a good neural network model is not only about these naive examples but is about many different topics. For example, to solve the vanishing gradient problem, new architectures are proposed, e.g., residual blocks[^/deep-learning-fundamentals/neural-net/#bib-He2015-ie], new optimization techniques were proposed[^/deep-learning-fundamentals/neural-net/#bib-Huang2016-uz], and theories such as information highway also became the key to the success of deep neural networks[^/deep-learning-fundamentals/neural-net/#bib-Srivastava2015-te]. --- **Related:** [Recurrent Neural Networks]() [^/deep-learning-fundamentals/neural-net/#Nielsen]: Nielsen MA. How the backpropagation algorithm works. In: Neural networks and deep learning \[Internet\]. \[cited 22 Nov 2023\]. Available: [http://neuralnetworksanddeeplearning.com/chap2.html]() [^/deep-learning-fundamentals/neural-net/#bib-Hornik1989-nc]: Hornik K., Stinchcombe M., White H.. Multilayer feedforward networks are universal approximators. *Neural networks: the official journal of the International Neural Network Society*. 1989. [https://linkinghub.elsevier.com/retrieve/pii/0893608089900208]() [^/deep-learning-fundamentals/neural-net/#bib-Cybenko1989-ro]: Cybenko G.. Approximation by superpositions of a sigmoidal function. *Mathematics of Control, Signals, and Systems*. 1989. [http://link.springer.com/10.1007/BF02551274]() [^/deep-learning-fundamentals/neural-net/#bib-Hassoun2021-sh]: Hassoun M.. Fundamentals of Artificial Neural Networks. *The MIT Press, Massachusetts Institute of Technology*. 2021. [https://mitpress.mit.edu/9780262514675/fundamentals-of-artificial-neural-networks/]() [^/deep-learning-fundamentals/neural-net/#bib-Hochreiter2008]: Hochreiter S., Bengio Y., Frasconi P. et al.. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies. *A Field Guide to Dynamical Recurrent Neural Networks*. 2001. [^/deep-learning-fundamentals/neural-net/#bib-He2015-ie]: He K., Zhang X., Ren S. et al.. Deep Residual Learning for Image Recognition. 2015. [http://arxiv.org/abs/1512.03385]() [^/deep-learning-fundamentals/neural-net/#bib-Huang2016-uz]: Huang G., Sun Y., Liu Z. et al.. Deep networks with stochastic depth. 2016. [http://arxiv.org/abs/1603.09382]() [^/deep-learning-fundamentals/neural-net/#bib-Srivastava2015-te]: Srivastava R.K., Greff K., Schmidhuber J.. Highway Networks. 2015. [http://arxiv.org/abs/1505.00387]() # Recurrent Neural Networks > [!NOTE] > > **In one minute** > > A recurrent neural network feeds the output of a unit back into itself, so its state at each time step depends on the current input and its previous state. Unrolled over time it is a chain of copies of the same unit, and it is closely related to a first-order differential equation. > > **Read first:** [Neural Networks]() In the section [Neural Networks](), we discussed the feedforward neural network. > [!NOTE] > > **Biological Neural Networks** > > Biological neural networks contain recurrent units. There are theories that employ recurrent networks to explain our memory[^/deep-learning-fundamentals/recurrent-neural-networks/#bib-Grossberg:2013]. ## Recurrent Neural Network Architecture A recurrent neural network (RNN) can be achieved by including loops in the network, i.e., the output of a unit is fed back to itself. As an example, we show a single unit in the following figure. ![Basic RNN]() On the left, we have the unfolded (unrolled) RNN, while the representation on the right is the compressed form. A simplified mathematical representation of the RNN is as follows: \\\[ \\begin{equation} h(t) = f( W\_h h(t-1) + W\_x x(t) + b) \\label{eq-rnn-vanilla} \\end{equation} \\\] where \\(h(t)\\) represents the state of the unit at time \\(t\\), \\(x(t)\\) is the input at time \\(t\\). > [!NOTE] > > **RNN and First-order Differential Equation** > > There are different views of the nature of time series data. Many of the time series datasets are generated by physical systems that follow the laws of physics. Mathematicians and physicists already studied and built up the theories of such systems and the framework we are looking into is dynamical systems. > > The vanilla RNN described in \\(\\eqref{eq-rnn-vanilla}\\) is quite similar to a first-order differential equation. For simplicity we use RELU for \\(f(\\cdot)\\). > > Note that > > \\\[ h(t - 1) = h(t) + \\sum\_{n=1}^{\\infty} \\frac{h^{(n)} (t)}{n!} (-1)^n, \\\] > > where \\(h^{(n)}(t)\\) is the \\(n\\)th derivative of \\(h(t)\\). Assuming that it converges and higher order doesn't contribute much, we rewrite \\(\\eqref{eq-rnn-vanilla}\\) as > > \\\[ \\begin{equation} \\frac{\\mathrm d h(t)}{\\mathrm d t} = x'(t) + W\_h h(t), \\label{eq-rnn-1st-order-diff-eq} \\end{equation} \\\] > > where > > \\\[ \\begin{align} x'(t) =& W\_h^{-1} W\_x x(t) + b' \\\\ b' = & W\_h^{-1} b. \\end{align} \\\] > > We have reduced the RNN formula to a first-order differential equation. Without discussing the details, we know that an exponential component \\(e^{W\_h t}\\) will rise in the solution. The component may explode or shrink. Based on our intuition of differential equations, such a dynamical system usually just blows up or diminishes for a large number of iterations. It can also be shown explicitly if we write down the backprogation formula where the state in the far past contributes little to the gradient. This is the famous vanishing gradient problem in RNN[^/deep-learning-fundamentals/recurrent-neural-networks/#bib-Pascanu2012-qv]. One solution to this is to introduce memory in the iterations, e.g., long short-term memory (LSTM) [^/deep-learning-fundamentals/recurrent-neural-networks/#bib-Hochreiter1997-gm]. In the basic example of RNN shown above, the output of the hidden state is fed to itself in the next iteration. In theory, the value to feed back to the unit and how the input and output are calculated can be quite different in different setups [^/deep-learning-fundamentals/recurrent-neural-networks/#Amidi&Amidi][^/deep-learning-fundamentals/recurrent-neural-networks/#Karpathy2015]. In the section [Forecasting with RNN](), we will show some examples of the different setups. ## Step by Step: Unrolling an RNN The same unit is applied at every time step. Step through four time steps to see the state \\(h(t)\\) being passed along. A step-by-step diagram of a recurrent unit unrolled over four time steps. It needs JavaScript. In short: \\(h(t) = f(W\_h h(t-1) + W\_x x(t) + b)\\) is applied at each step with the same weights, so \\(h(4)\\) depends on all four inputs. --- **Related:** [Forecasting with RNN]() · [Neural ODE]() [^/deep-learning-fundamentals/recurrent-neural-networks/#Amidi&Amidi]: Amidi A, Amidi S. CS 230. In: Recurrent Neural Networks Cheatsheet \[Internet\]. \[cited 22 Nov 2023\]. Available: [https://stanford.edu/\~shervine/teaching/cs-230/cheatsheet-recurrent-neural-networks]() [^/deep-learning-fundamentals/recurrent-neural-networks/#Karpathy2015]: Karpathy A. The Unreasonable Effectiveness of Recurrent Neural Networks. In: Andrej Karpathy blog \[Internet\]. 2015 \[cited 22 Nov 2023\]. Available: [https://karpathy.github.io/2015/05/21/rnn-effectiveness/]() [^/deep-learning-fundamentals/recurrent-neural-networks/#bib-Grossberg:2013]: Grossberg S.. Recurrent neural networks. *Scholarpedia*. 2013. [https://doi.org/10.4249/scholarpedia.1888]() [^/deep-learning-fundamentals/recurrent-neural-networks/#bib-Pascanu2012-qv]: Pascanu R., Mikolov T., Bengio Y.. On the difficulty of training Recurrent Neural Networks. 2012. [http://arxiv.org/abs/1211.5063]() [^/deep-learning-fundamentals/recurrent-neural-networks/#bib-Hochreiter1997-gm]: Hochreiter S., Schmidhuber J.. Long short-term memory. *Neural computation*. 1997. [http://www.mitpressjournals.org/doi/10.1162/neco.1997.9.8.1735]() # Convolutional Neural Networks # Vanilla Transformers > [!NOTE] > > **In one minute** > > The transformer drops recurrence and relies on attention, which lets every position draw directly on every other position. The page summarizes the encoder-decoder structure, the attention mechanism and how positional encodings tell the model about order. > > **Read first:** [Neural Networks]() In the seminal paper *Attention is All You Need*, the legendary transformer architecture was born[^/transformers/transformers.vanilla/#bib-Vaswani2017-yg]. > [!NOTE] > > **Quote from *Attention Is All You Need*** > > "... the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output." Transformer has evolved a lot in the past few years and there are a galaxy of variants[^/transformers/transformers.vanilla/#bib-Amatriain2023-of]. ![Amatriain2023-of]() In this section, we will focus on the vanilla transformer. Jay Alammar wrote an excellent post, named [The Illustrated Transformer]()[^/transformers/transformers.vanilla/#illustrated_transformer]. We recommend the reader read the post. We won't cover everything in this section. However, for completeness, we will summarize some of the key ideas of transformers. > [!NOTE] > > **Formal Algorithms** > > For a formal description of the transformer-relevant algorithms, please refer to Phuong & Hutter (2022)[^/transformers/transformers.vanilla/#bib-Phuong2022-im]. ## The Vanilla Transformer In the **vanilla transformer**, we can find three key components: Encoder-Decoder, the attention mechanism, and the positional encoding. ### Encoder-Decoder It has an encoder-decoder architecture. ![Transformer encoder decoder high level]() We assume that the input \\(\\mathbf X\\) is already embedded and converted to tensors. The encoder-decoder is simulating the induction-deduction framework of learning. Input \\(\\mathbf X\\) is first encoded into a representation \\(\\hat{\\mathbf X}\\) that should be able to capture the minimal sufficient statistics of the input. Then, the decoder takes this representation of minimal sufficient statistics \\(\\hat{\\mathbf X}\\) and perform deduction to create the output \\(\\hat{\\mathbf Y}\\). ### Attention The key to a transformer is its attention mechanism. It utilizes the attention mechanism to look into the relations of the embeddings[^/transformers/transformers.vanilla/#bib-Vaswani2017-yg][^/transformers/transformers.vanilla/#bib-zhang2021dive]. To understand the attention mechanism, we need to understand the **query**, **key**, and **value**. In essence, the attention mechanism is a classifier that outputs the usefulness of the elements in the **value**, and the usefulness is represented using a matrix formed by the **query** and the **key**. \\\[ \\operatorname{Attention}(\\mathbf Q, \\mathbf K, \\mathbf V) = \\operatorname{softmax} \\left( \\frac{\\mathbf Q \\mathbf K^T}{\\sqrt{d\_k}} \\right)\\mathbf V, \\\] where \\(d\_k\\) is the dimension of the key \\(\\mathbf K\\). For example, we can construct the **query**, **key**, and **value** by applying a linear layer to the input \\(\\mathbf X\\). > [!NOTE] > > **Conventions** > > We follow the convention that the first index of \\(\\mathbf X\\) is the index for the input element. For example, if we have two words as our input, the \\(X\_{0j}\\) is the representation of the first word and \\(X\_{1j}\\) is that for the second. > > We also use Einstein notation in this section. | Name | Definition | Component Form | Comment | | --- | --- | --- | --- | | Query \\(\\mathbf Q\\) | \\(\\mathbf Q=\\mathbf X \\mathbf W^Q\\) | \\(Q\_{ij} = X\_{ik} W^{Q}\_{kj}\\) | Note that the weights \\(\\mathbf W^Q\\) can be used to adjust the size of the query. | | Key \\(\\mathbf K\\) | \\(\\mathbf K=\\mathbf X \\mathbf W^K\\) | \\(K\_{ij} = X\_{ik} W^{K}\_{kj}\\) | In the vanilla scaled-dot attention, the dimension of key is the same as the query. This is why \\(\\mathbf Q \\mathbf K^T\\) works. | | Value \\(\\mathbf V\\) | \\(\\mathbf V = \\mathbf X \\mathbf W^V\\) | \\(V\_{ij} = X\_{ik} W^{V}\_{kj}\\) | | The dot product \\(\\mathbf Q \\mathbf K^T\\) is \\\[ \\begin{align} \\mathbf A \\equiv \\mathbf Q \\mathbf K^T =& \\mathbf X \\mathbf W^{Q} {\\mathbf W^{K}}^T \\mathbf X^T \\\\ =& X\_{im} X\_{jn} W^{Q}\_{mk} W^{K}\_{nk}. \\end{align} \\\] which determines how the elements in the value tensor are mixed, \\(A\_{ij}V\_{jk}\\). For identity \\(\\mathbf A\\), we do not mix the rows of \\(\\mathbf V\\). > [!NOTE] > > **Classifier** > > The dot-product attention is like a classifier that outputs the usefulness of the elements in \\(\\mathbf V\\). After training, \\(\\mathbf A\\) should be able to make connections between the different input elements. We will provide a detailed example when discussing [the applications to time series](). #### Step by Step: Attention The formula above, one operation at a time. A step-by-step diagram of scaled dot-product attention. It needs JavaScript. In short: linear layers give the query, key and value; \\(\\mathbf Q \\mathbf K^T\\) scores every pair of positions; a softmax turns each row of scores into weights; the weights mix the rows of \\(\\mathbf V\\). ### Knowledge of Positions Positional information, or time order information for time series input, is encoded by a positional encoder that shifts the embeddings. The simplest positional encoder uses the cyclic nature of trig functions[^/transformers/transformers.vanilla/#bib-Vaswani2017-yg]. By adding such positional information directly to the values before the data flows into the attention mechanism, we can encode the positional information into the attention mechanism[^/transformers/transformers.vanilla/#Kazemnejad2019]. #### Try It: Sinusoidal Positional Encodings The chart shows the trigonometric encoding of *Attention Is All You Need*, \\(\\operatorname{PE}(pos, 2i) = \\sin(pos / 10000^{2i/d})\\) and \\(\\operatorname{PE}(pos, 2i+1) = \\cos(pos / 10000^{2i/d})\\): one column per position, one row per dimension. Pick a position to see how similar the encodings of the other positions are to it. An interactive heatmap of the sinusoidal positional encodings, with the similarity between a chosen position and all others. It needs JavaScript. --- **Related:** [Transformers for Time Series Forecasting]() [^/transformers/transformers.vanilla/#illustrated_transformer]: Alammar J. The Illustrated Transformer. In: Jay Alammar \[Internet\]. 27 Jun 2018 \[cited 14 Jun 2023\]. Available: [http://jalammar.github.io/illustrated-transformer/]() [^/transformers/transformers.vanilla/#Kazemnejad2019]: Kazemnejad A. Transformer Architecture: The Positional Encoding. In: Amirhossein Kazemnejad’s Blog \[Internet\]. 20 Sep 2019 \[cited 7 Nov 2023\]. Available: [https://kazemnejad.com/blog/transformer\_architecture\_positional\_encoding/]() [^/transformers/transformers.vanilla/#bib-Vaswani2017-yg]: Vaswani A., Shazeer N., Parmar N. et al.. Attention Is All You Need. 2017. [http://arxiv.org/abs/1706.03762]() [^/transformers/transformers.vanilla/#bib-Amatriain2023-of]: Amatriain X.. Transformer models: an introduction and catalog. *arXiv \[cs.CL\]*. 2023. [http://arxiv.org/abs/2302.07730]() [^/transformers/transformers.vanilla/#bib-Phuong2022-im]: Phuong M., Hutter M.. Formal Algorithms for Transformers. 2022. [http://arxiv.org/abs/2207.09238]() [^/transformers/transformers.vanilla/#bib-zhang2021dive]: Zhang A., Lipton Z.C., Li M. et al.. Dive into Deep Learning. *arXiv preprint arXiv:2106.11342*. 2021. # Dynamical Systems > [!NOTE] > > **In one minute** > > Much time series data is generated by dynamical systems, such as the chaotic Lorenz system, and differential equations are the natural tool to model them. Finding clean, interpretable equations by hand is hard. A lot of time series data are generated by dynamical systems. One of the most cited examples is the coordinates \\(x(t)\\), \\(y(t)\\), \\(z(t)\\) as functions of time \\(t\\) in a Lorenz system. > [!NOTE] > > **Lorenz System** > > A Lorenz system is defined by the Lorenz equations[^/dynamical-systems/#bib-enwiki:1186188179] > > \\\[ \\begin{align} \\frac{\\mathrm{d}x}{\\mathrm{d}t} &= \\sigma (y - x), \\\\ \\frac{\\mathrm{d}y}{\\mathrm{d}t} &= x (\\rho - z) - y, \\\\ \\frac{\\mathrm{d}z}{\\mathrm{d}t} &= x y - \\beta z, \\end{align} \\\] > > where \\(x\\), \\(y\\), and \\(z\\) are the coordinates of a particle. > > It is a chaotic system that is very sensitive to the initial conditions. > [!NOTE] > > **Dynamical Systems** > > Many real-world systems are dynamical systems. Differential equation is a handy tool to model a dynamical system. For example, the action potentials of a squid giant axon can be modeled by the famous [Hodgkin-Huxley model](). A naive philosophy to model time series is to come up with a set of differential equations to model the time series. However, finding clean and interpretable differential equations is not easy. It has been the top game in physics for centuries. In the following sections, we will discuss a few solutions to model data as dynamical systems. --- **Related:** [Neural ODE]() [^/dynamical-systems/#bib-enwiki:1186188179]: Wikipedia contributors. Lorenz system –- Wikipedia, The Free Encyclopedia. 2023. [https://en.wikipedia.org/w/index.php?title=Lorenz\_system&oldid=1186188179]() # Neural ODE > [!NOTE] > > **In one minute** > > A neural ODE combines neural networks with differential equations: a network models the rate of change of a system's state. Examples of differential equations build the intuition, and the finite difference form shows how such an equation is stepped forward in time. > > **Read first:** [Dynamical Systems]() Neural ODE is an elegant idea of combining neural networks and differential equations[^/dynamical-systems/neural-ode/#bib-Chen2018-mp]. In this section, we will first show some examples of differential equations and then discuss how to combine neural networks and differential equations. ## Ordinary Differential Equations A first-order ordinary differential equation is as simple as \\\[ \\begin{equation} \\frac{\\mathrm d h(t)}{\\mathrm dt} = f\_\\theta(h(t), t), \\label{eq:1st-order-ode} \\end{equation} \\\] where \\(h(t)\\) is the function that describes the state of a dynamical system. To build up intuitions, we show a few examples of differential equations below. > [!NOTE] > > **Examples of Differential Equations** > > > **Utility Code for the Following ODE (Run this first)** > > > > ``` > > from abc import ABC, abstractmethod > > import numpy as np > > from scipy.integrate import odeint > > import inspect > > > > from typing import Optional, Any > > > > import matplotlib.pyplot as plt > > import seaborn as sns; sns.set() > > > > class DiffEqn(ABC): > > """A first order differential equation and the corresponding solutions. > > > > :param t: time steps to solve the differential equation for > > :param y_0: initial condition of the ode > > """ > > def __init__(self, t: np.ndarray, y_0: float, **fn_args: Optional[Any]): > > self.t = t > > self.y_0 = y_0 > > self.fn_args = fn_args > > > > @abstractmethod > > def fn(self, y: float, t: np.ndarray) -> np.ndarray: > > pass > > > > def solve(self) -> np.ndarray: > > return odeint(self.fn, self.y_0, self.t) > > > > @abstractmethod > > def _formula(self) -> str: > > pass > > > > def __str__(self): > > return f"{self._formula()}" > > > > def __repr__(self): > > return f"{self._formula()}" > > > > def plot(self, ax: Optional[plt.Axes]=None): > > > > if ax is None: > > _, ax = plt.subplots(figsize=(10, 6.18)) > > > > sns.lineplot( > > x=self.t, y=self.solve()[:, 0], > > ax=ax > > ) > > > > ax.set_xlabel("t") > > ax.set_ylabel("y") > > ax.set_title(f"Solution for ${self}$ with {self.fn_args}") > > ``` > > The logistic model of infectious disease is > > \\\[ \\frac{dh(t)}{d t} = r \* y \* (1-y). \\\] > > ``` > class Infections(DiffEqn): > def fn(self, y: float, t: np.ndarray) -> np.ndarray: > r = self.fn_args["r"] > dydt = r * y * (1 - y) > return dydt > > def _formula(self): > return r"\frac{dh(t)}{d t} = r * y * (1-y)" > > infections_s = Infections(t, 0.1, r=0.9) > infections_s.plot() > ``` > > ![infectious model]() > > The following equation describes an exponentially growing \\(h(t)\\). > > \\\[ \\frac{\\mathrm d h(t)}{\\mathrm d t} = \\lambda h(t), \\\] > > with \\(\\lambda \> 0\\). > > ``` > class Exponential(DiffEqn): > def fn(self, y: float, t: np.ndarray) -> np.ndarray: > lbd = self.fn_args["lbd"] > dydt = lbd * y > > return dydt > > def _formula(self): > return r"\frac{dh(t)}{d t} = \lambda h(t)" > > y0_exponential = 1 > t = np.linspace(0, 10, 101) > lbd = 2 > > exponential = Exponential(t, y0_exponential, lbd=lbd) > exponential.plot() > ``` > > ![solution to the exponential growth differential equation]() > > We construct an oscillatory system using [sinusoid](), > > \\\[ \\frac{dh(t)}{d t} = \\sin(\\lambda t) t. \\\] > > Naively, we expect the oscillations to be large for larger \\(t\\). Taking the limit \\(t\\to\\infty\\), the first order derivative \\(\\frac{\\mathrm dy}{\\mathrm d t}\\to\\infty\\). With this limit, we expect the oscillation amplitude to be infinite. > > ``` > class SinMultiplyT(DiffEqn): > def fn(self, y: float, t: np.ndarray) -> np.ndarray: > lbd = self.fn_args["lbd"] > dydt = np.sin(lbd * t) * t > > return dydt > > def _formula(self): > return r"\frac{dh(t)}{d t} = \sin(\lambda t) t" > > y0_sin = 1 > t = np.linspace(0, 10, 101) > lbd = 2 > sin_multiply_t = SinMultiplyT(t, y0_sin, lbd=lbd) > sin_multiply_t.plot() > ``` > > ![ODE oscillatory]() > > We design a system that grows according to the receprocal of its value, > > \\\[ \\frac{dh(t)}{d t} = \\frac{1}{a \* y + b}. \\\] > > ``` > class Receprocal(DiffEqn): > def fn(self, y: float, t: np.ndarray) -> np.ndarray: > shift = self.fn_args["shift"] > scale = self.fn_args["scale"] > dydt = 1/(shift + scale * y) > return dydt > > def _formula(self): > return r"\frac{dh(t)}{d t} = \frac{1}{shift + scale * y}" > > receprocal = Receprocal(t, 1, shift=-5, scale=-10) > receprocal.plot() > ``` > > ![receprocal]() ## Finite Difference Form of Differential Equations Eq. \\(\\eqref{eq:1st-order-ode}\\) can be rewritten in the finite difference form as \\\[ \\frac{h(t+\\Delta t) - h(t)}{\\Delta t} = f\_\\theta(h(t), t), \\\] with \\(\\Delta t\\) small enough. > [!NOTE] > > **Derivatives** > > The definition of the first-order derivative is $$ h'(t) = \\lim\_{\\Delta t\\to 0} \\frac{h(t+\\Delta t) - h(t)}{\\Delta t}. $$ > > In a numerical computation, \\(\\lim\\) is approached by taking a small \\(\\Delta t\\). If we take \\(\\Delta t = 1\\), the equation becomes \\\[ \\begin{equation} h(t+1) = h(t) + f\_\\theta(h(t), t) \\label{eq:1st-order-ode-finite-difference-deltat-1} \\end{equation} \\\] > [!NOTE] > > **\\(\\Delta t = 1\\)? Rescale of Time \\(t\\).** > > As there is no absolute measure of time \\(t\\), we can always rescale \\(t\\) to \\(\\hat t\\) so that \\(\\Delta t = 1\\). However, for the sake of clarity, we will keep \\(t\\) as the time variable. Coming back to neural networks, if \\(h(t)\\) represents the state of a neural network block at depth \\(t\\), Eq. \\(\\eqref{eq:1st-order-ode-finite-difference-deltat-1}\\) is nothing fancy but the **residual connection** in ResNet[^/dynamical-systems/neural-ode/#bib-He2015-ie]. This connection between the finite difference form of a first-order differential equation and the residual connection leads to the new family of deep neural network models called neural ode[^/dynamical-systems/neural-ode/#bib-Chen2018-mp]. In a neural ODE, we treat each layer of a neural network as a function \\(h\\) of depth \\(t\\), i.e., the state of the layer is equivalent to a function \\(h(t)\\). However, we are not obliged to use \\(h\\) as the function to directly take in the raw input and output the raw output. NeuralODE is extremely flexible and we could build latent dynamical systems to represent some intrinsic dynamics. ![Neural ODE and Differential Equations]() > [!NOTE] > > **Solving Differential Equations** > > The right side of the Eq. \\(\\eqref{eq:1st-order-ode}\\) is called the Jacobian. Given any Jacobian \\(f(h(t), \\theta(t), t)\\), we can, at least numerically, perform integration to find out the value of \\(h(t)\\) at any \\(t=t\_N\\), > > \\\[ h(t\_N) = \\int\_{t\_0}^{t\_i} f(h(t), \\theta(t), t) \\mathrm dt. \\\] > > In this formalism, we find out the transformed input \\(h(t\_0)\\) by solving this differential equation. In traditional neural networks, we achieve this by stacking many layers of neural networks using skip connections. > > In the original Neural ODE paper, the authors used the so-called reverse-model derivative method[^/dynamical-systems/neural-ode/#bib-Chen2018-mp]. > > We will not dive deep into solving differential equations in this section. Instead, we will show some applications of neural ODEs in section [Time Series Forecasting with Neural ODE](). --- **Related:** [Recurrent Neural Networks]() · [Time Series Forecasting with Neural ODE]() [^/dynamical-systems/neural-ode/#bib-Chen2018-mp]: Chen R.T.Q., Rubanova Y., Bettencourt J. et al.. Neural Ordinary Differential Equations. 2018. [http://arxiv.org/abs/1806.07366]() [^/dynamical-systems/neural-ode/#bib-He2015-ie]: He K., Zhang X., Ren S. et al.. Deep Residual Learning for Image Recognition. 2015. [http://arxiv.org/abs/1512.03385]() # Energy-based Models > [!NOTE] > > **In one minute** > > Energy-based models give every configuration of the variables an energy, a scalar from which a probability density follows through a partition function, as in statistical physics. Compatible configurations get low energy, that is, high probability density. Energy-based models (EBM) establish relations between different possible values of variables using "energy functions"[^/energy-based-models/intro/#bib-Le_Cun2006-ta]. In an EBM, any input data point can be assigned a probability density[^/energy-based-models/intro/#Lippe]. Similar to statistical physics, we can create such probability densities using a partition function. As easy as it sounds, such probability densities usually require a scalar function similar to the energy function in statistical physics. When building the objective functions, we require the configurations that should have the same target label to have low energy, or higher probability density, i.e., to be compatible. --- **Related:** [Denoising Diffusion Probabilistic Models]() [^/energy-based-models/intro/#Lippe]: Lippe P. Tutorial 9: Deep Autoencoders — UvA DL Notebooks v1.1 documentation. In: UvA Deep Learning Tutorials \[Internet\]. \[cited 20 Sep 2021\]. Available: [https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial\_notebooks/tutorial9/AE\_CIFAR10.html]() [^/energy-based-models/intro/#bib-Le_Cun2006-ta]: Le Cun Y., Chopra S., Hadsell R. et al.. A Tutorial on Energy-Based Learning. 2006. # Denoising Diffusion Probabilistic Models > [!NOTE] > > **In one minute** > > Diffusion models connect the data space and a latent space through a diffusion process that is assumed to be invertible, which keeps the otherwise intractable computations manageable. The page works through the objective, an example with five steps, the reverse process for a Gaussian and the optimization. Many philosophically beautiful deep learning ideas face the tractability problem. Many deep learning models utilize the concept of latent space, e.g., \\(\\mathbf z\\), which is usually a compression of the real data space, e.g., \\(\\mathbf x\\), to enable easier computations for our task. However, such models usually require the computation of an intractable marginalization of the joint distribution \\(p(\\mathbf x, \\mathbf z)\\) over the latent space[^/energy-based-models/ebm.diffusion/#bib-Luo2022-hz]. To make such computations tractable, we have to apply approximations or theoretical assumptions. Diffusion models in deep learning establish the connection between the real data space \\(\\mathbf x\\) and the latent space \\(\\mathbf z\\) assuming invertible [diffusion processes]() [^/energy-based-models/ebm.diffusion/#bib-Sohl-Dickstein2015-th] [^/energy-based-models/ebm.diffusion/#bib-Ho2020-er]. ## Objective In a denoising diffusion model, given an input \\(\\mathbf x^0\\) drawn from a complicated and unknown distribution \\(q(\\mathbf x^0)\\), we find - a latent space with a simple and manageable distribution, e.g., normal distribution, and - the transformations from \\(\\mathbf x^0\\) to \\(\\mathbf x^n\\), as well as - the transformations from \\(\\mathbf x^n\\) to \\(\\mathbf x^0\\). > [!NOTE] > > **Image Data Example** > > The following figure is taken from Sohl-Dickstein et al. (2015)[^/energy-based-models/ebm.diffusion/#bib-Ho2020-er]. > > ![]() > > The forward process, shown in the first row, diffuses the original spiral data at \\(t=0\\) into a Gaussian noise at \\(t=T\\). The reverse process, shown in the second row, recovers the original data from \\(t=T\\) into the image at \\(t=0\\). > > In the following texts, we use \\(n\\) instead of \\(t\\). ### An Example with \\(N=5\\) For example, with \\(N=5\\), the forward process is ``` flowchart LR x0 --> x1 --> x2 --> x3 --> x4 --> x5 ``` and the reverse process is ``` flowchart LR x5 --> x4 --> x3 --> x2 --> x1 --> x0 ``` The joint distribution we are searching for is \\\[ q(\\mathbf x^1, \\mathbf x^2, \\mathbf x^3, \\mathbf x^4, \\mathbf x^5 \\vert \\mathbf x^0) = q(\\mathbf x^5\\vert \\mathbf x^4) q(\\mathbf x^4\\vert \\mathbf x^3) q(\\mathbf x^3\\vert \\mathbf x^2)q(\\mathbf x^2\\vert \\mathbf x^1)q(\\mathbf x^1\\vert \\mathbf x^0), \\\] A diffusion model assumes a simple diffusion process, e.g., \\\[ \\begin{equation} q(\\mathbf x^n \\vert \\mathbf x^{n-1}) \\equiv \\mathcal N (\\mathbf x^n ; \\sqrt{ 1 - \\beta\_n} \\mathbf x ^{n -1}, \\beta\_n\\mathbf I). \\label{eq-guassian-noise} \\end{equation} \\\] This simulates an information diffusion process. The information in the original data is gradually smeared. If the chosen diffusion process is reversible, the reverse process of it can be modeled by a similar Markov process \\\[ p\_\\theta (\\mathbf x^0, \\mathbf x^1, \\mathbf x^2, \\mathbf x^3, \\mathbf x^4, \\mathbf x^5) = p\_\\theta (\\mathbf x^0 \\vert \\mathbf x^1) p\_\\theta (\\mathbf x^1 \\vert \\mathbf x^2) p\_\\theta (\\mathbf x^2 \\vert \\mathbf x^3) p\_\\theta (\\mathbf x^3 \\vert \\mathbf x^4) p\_\\theta (\\mathbf x^4 \\vert \\mathbf x^5) p(\\mathbf x^5). \\\] This reverse process is the denoising process. As long as our model estimates \\(p\_\\theta (\\mathbf x^n \\vert \\mathbf x^{n-1})\\) nicely, we can go \\(\\mathbf x^0 \\to \\mathbf x^N\\) and \\(\\mathbf x^N \\to \\mathbf x^0\\). ### The Reverse Process: A Gaussian Example With Eq \\(\\eqref{eq-guassian-noise}\\), the reverse process is \\\[ \\begin{equation} p\_\\theta (\\mathbf x^{n-1} \\vert \\mathbf x^n) = \\mathcal N ( \\mathbf x^{n-1} ; \\mu\_\\theta(\\mathbf x^n, n), \\Sigma\_\\theta(\\mathbf x^n, n)\\mathbf I). \\label{eqn-guassian-reverse-process} \\end{equation} \\\] ### Step by Step: Forward and Reverse The example with \\(N=5\\), one stage at a time. A step-by-step diagram of a diffusion model with five steps. It needs JavaScript. In short: the forward process \\(q\\) adds noise step by step until \\(\\mathbf x^5\\) is close to pure noise; the model \\(p\_\\theta\\) learns to undo one step at a time, so new data is generated by starting from noise and applying the reverse steps. ### Summary - Forward: perturbs data to noise, step by step; - Reverse: converts noise to data, step by step. ``` flowchart LR prior["prior distribution"] data --"forward Markov chain"--> noise noise --"reverse Markov chain"--> data prior --"sampling"--> noise ``` ## Optimization The forward chain is predefined. To close the loop, we have to find \\(p\_\\theta\\). A natural choice for our loss function is the negative log-likelihood, \\\[ \\mathbb E\_{q(\\mathbf x^0)} \\left( - \\log ( p\_\\theta (\\mathbf x^0) ) \\right). \\\] (Ho et al., 2020) proved that the above loss has an upper bound related to the diffusion process defined in Eq \\(\\eqref{eq-guassian-noise}\\)[^/energy-based-models/ebm.diffusion/#Rasul2021] \\\[ \\begin{align} &\\operatorname{min}\_\\theta \\mathbb E\_{q(\\mathbf x^0)} \\\\ \\leq & \\operatorname{min}\_\\theta \\mathbb E\_{q(\\mathbf x^{0:N})} \\left\[ -\\log p(\\mathbf x^N) - \\sum\_{n=1}^{N} \\log \\frac{p\_\\theta (\\mathbf x^{n-1}\\vert \\mathbf x^n)}{q(\\mathbf x^n \\vert \\mathbf x^{n-1})} \\right\] \\\\ =& \\operatorname{min}\_\\theta \\mathbb E\_{\\mathbf x^0, \\epsilon} \\left\[ \\frac{\\beta\_n^2}{2\\Sigma\_\\theta \\alpha\_n (1 - \\bar \\alpha\_n)} \\lVert \\epsilon - \\epsilon\_\\theta ( \\sqrt{ \\bar \\alpha\_n} \\mathbf x^0 + \\sqrt{1-\\bar \\alpha\_n} \\epsilon , n ) \\rVert \\right\] \\end{align} \\\] where \\(\\epsilon\\) is a sample from \\(\\mathcal N(0, \\mathbf I)\\). The second step assumes the Gaussian noise in Eq \\(\\eqref{eq-guassian-noise}\\), which is equivalent to[^/energy-based-models/ebm.diffusion/#Rasul2021] \\\[ q(\\mathbf x^n \\vert \\mathbf x^0) = \\mathcal N (\\mathbf x^n ; \\sqrt{\\bar \\alpha\_n} \\mathbf x^0, (1 - \\bar \\alpha\_n)\\mathbf I), \\\] with \\(\\alpha\_n = 1 - \\beta \_ n\\), \\(\\bar \\alpha \_ n = \\Pi \_ {i=1}^n \\alpha\_i\\), and \\(\\Sigma\_\\theta\\) in Eq \\(\\eqref{eqn-guassian-reverse-process}\\). ## Code Rogge & Rasul (2022) wrote [a post]() with detailed annotations of the denoising diffusion probabilistic model[^/energy-based-models/ebm.diffusion/#Rogge2022]. --- **Related:** [TimeGrad Using Diffusion Model]() · [Variational AutoEncoder]() [^/energy-based-models/ebm.diffusion/#Rasul2021]: Rasul K, Seward C, Schuster I, Vollgraf R. Autoregressive Denoising Diffusion Models for Multivariate Probabilistic Time Series Forecasting. arXiv \[cs.LG\]. 2021. Available: [http://arxiv.org/abs/2101.12072]() [^/energy-based-models/ebm.diffusion/#Rogge2022]: Rogge N, Rasul K. The Annotated Diffusion Model. In: Hugging Face Blog \[Internet\]. 7 Jun 2022 \[cited 18 Feb 2023\]. Available: [https://huggingface.co/blog/annotated-diffusion]() [^/energy-based-models/ebm.diffusion/#bib-Luo2022-hz]: Luo C.. Understanding Diffusion Models: A Unified Perspective. 2022. [http://arxiv.org/abs/2208.11970]() [^/energy-based-models/ebm.diffusion/#bib-Sohl-Dickstein2015-th]: Sohl-Dickstein J., Weiss E.A., Maheswaranathan N. et al.. Deep Unsupervised Learning using Nonequilibrium Thermodynamics. 2015. [http://arxiv.org/abs/1503.03585]() [^/energy-based-models/ebm.diffusion/#bib-Ho2020-er]: Ho J., Jain A., Abbeel P.. Denoising Diffusion Probabilistic Models. 2020. [http://arxiv.org/abs/2006.11239]() # Generative Models > [!NOTE] > > **In one minute** > > The generative models in this part share three pieces: an encoder, an explicit latent space and a decoder. ![Generative Models]() Generative models come with - an encoder, - an explicit latent space, and - a decoder. --- **Related:** [Autoencoders]() · [Variational AutoEncoder]() · [Flow]() # Autoregressive Model > [!NOTE] > > **In one minute** > > An autoregressive model describes each variable conditioned on the ones before it. The page also sorts out the different notations the literature uses for those preceding variables. ![Generative AR basics]() An autoregressive (AR) model is autoregressive, \\\[ \\begin{equation} \\log p\_\\theta (x) = \\sum\_{t=1}^T \\log p\_\\theta ( x\_{t} \\mid \\{x\_{\ [!NOTE] > > **Notations and Conventions** > > In AR models, we have to mention the preceding nodes (\\(\\{x\_{\ > ![]() > > There are different notations for such relations. > > - In Uria et al., the authors use \\(p(x\_{o\_d}\\mid \\mathbf x\_{o\_{\ - In Liu et al. and Papamakarios et al., the authors use \\(p(x\_{t}\\mid \\mathbf x\_{1:t-1})\\) [^/self-supervised/generative/autoregressive/#Liu2020][^/self-supervised/generative/autoregressive/#Papamakarios2017]. > - In Germain et al., the authors use \\(p(x\_t\\mid \\mathbf x\_{\ > In the current review, we expanded the vector notation \\(\\mathbf x\_{\) [^/self-supervised/generative/autoregressive/#Triebe2019]: Triebe O, Laptev N, Rajagopal R. AR-Net: A simple Auto-Regressive Neural Network for time-series. arXiv \[cs.LG\]. 2019. Available: [http://arxiv.org/abs/1911.12436]() [^/self-supervised/generative/autoregressive/#Ho2019]: Ho G. George Ho. In: Eigenfoo \[Internet\]. 9 Mar 2019 \[cited 19 Sep 2021\]. Available: [https://www.eigenfoo.xyz/deep-autoregressive-models/]() [^/self-supervised/generative/autoregressive/#Papamakarios2017]: Papamakarios G, Pavlakou T, Murray I. Masked Autoregressive Flow for Density Estimation. arXiv \[stat.ML\]. 2017. Available: [http://arxiv.org/abs/1705.07057]() [^/self-supervised/generative/autoregressive/#Germain2015]: Germain M, Gregor K, Murray I, Larochelle H. MADE: Masked autoencoder for distribution estimation. 32nd International Conference on Machine Learning, ICML 2015. 2015;2: 881–889. Available: [http://arxiv.org/abs/1502.03509]() [^/self-supervised/generative/autoregressive/#Liu2020]: Liu X, Zhang F, Hou Z, Wang Z, Mian L, Zhang J, et al. Self-supervised Learning: Generative or Contrastive. arXiv \[cs.LG\]. 2020. Available: [http://arxiv.org/abs/2006.08218]() [^/self-supervised/generative/autoregressive/#Lippe]: Lippe P. Tutorial 12: Autoregressive Image Modeling — UvA DL Notebooks v1.1 documentation. In: UvA Deep Learning Tutorials \[Internet\]. \[cited 20 Sep 2021\]. Available: [https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial\_notebooks/tutorial12/Autoregressive\_Image\_Modeling.html]() [^/self-supervised/generative/autoregressive/#rogen]: rogen-george. rogen-george/Deep-Autoregressive-Model. In: GitHub \[Internet\]. \[cited 20 Sep 2021\]. Available: [https://github.com/rogen-george/Deep-Autoregressive-Model]() # Autoencoders > [!NOTE] > > **In one minute** > > An autoencoder encodes its input into a compact latent space and decodes it back. The simplest version is two small neural networks, an encoder and a decoder, trained with a loss such as cross entropy for binary data. Autoencoders (AE) are machines that encode inputs into a compact latent space. ![AE]() > [!TIP] > > **Notation: dot (\\(\\cdot\\))** > > We use a single vertically centered dot, i.e., \\(\\cdot\\), to indicate that the function or machine can take in arguments. A simple autoencoder can be achieved using two neural nets, e.g., \\\[ \\begin{align} {\\color{green}h} &= {\\color{blue}g}{\\color{blue}(}{\\color{blue}b} + {\\color{blue}w} x{\\color{blue})} \\\\ \\hat x &= {\\color{red}\\sigma}{\\color{red}(c} + {\\color{red}v} {\\color{green}h}{\\color{red})}, \\end{align} \\\] where in this simple example, - \\({\\color{blue}g(b + w \\cdot )}\\) is the encoder, and - \\({\\color{red}\\sigma(c + v \\cdot )}\\) is the decoder. For binary labels, we can use a simple cross entropy as the loss. ## Code See Lippe[^/self-supervised/generative/ae/#Lippe]. --- **Related:** [Variational AutoEncoder]() [^/self-supervised/generative/ae/#Lippe]: Lippe P. Tutorial 9: Deep Autoencoders — UvA DL Notebooks v1.1 documentation. In: UvA Deep Learning Tutorials \[Internet\]. \[cited 20 Sep 2021\]. Available: [https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial\_notebooks/tutorial9/AE\_CIFAR10.html]() # Variational AutoEncoder > [!NOTE] > > **In one minute** > > A variational autoencoder introduces a variational distribution q to handle the integral over the latent variable. Neural networks only have to model the parameters of simple Gaussian distributions, and the loss is explained term by term. > > **Read first:** [Autoencoders]() Variational AutoEncoder (VAE) is very different from [AE](). In VAE, we introduce a variational distribution \\(q\\) to help us work out the weighted integral after introducing the latent space variable \\(z\\), \\\[ \\begin{align} \\ln p\_\\theta(x) &= \\int \\left(\\ln p\_\\theta (x\\mid z) \\right)p(z) \\,\\mathrm d z \\\\ &= \\int \\left(\\ln\\frac{q\_{\\phi}(z\\mid x)}{q\_{\\phi}(z\\mid x)} p\_\\theta (x\\mid z) \\right) p(z) \\, \\mathrm d z \\end{align} \\\] In the above derivation, - \\({}\_\\theta\\) is the model for inference, and - \\({}\_\\phi\\) is the model for variational approximation. > [!TIP] > > **Tricks** > > - \\(p\_\\theta(x\\mid z)\\) is usually Gaussian distribution of \\(x\\) but with mean parameterized by the latent variable \\(z\\) and the model parameters \\(\\theta\\). > - The latent space variable \\(p(z)\\) is usually assumed to be a normal distribution. > - The marginalization of the latent variable increase the expressive power. > - Instead of modeling a complex likelihood \\(p(x\\mid z)\\) directly, we only need to model parameters of Gaussian distributions, e.g., a function \\(f(z, \\theta)\\) for the mean of the Gaussian distribution. ![Gaussian Latent Space]() > From simple distribution in latent space to a more complex distribution. \[Doersch2016\] The demo looks great. However, sampling from latent space becomes more difficult as the dimension of the latent space increase. We need a more efficient way to sample from the latent space. We use the variational method which uses a model that samples \\(z\\) based on \\(x\\) to sample \\(z\\), i.e., introduce a function \\(q(z\\mid x)\\) to help us with sampling. \\\[ \\begin{align} \\ln p\_\\theta(x) &= \\int \\left(\\ln p\_\\theta (x\\mid z) \\right)p(z) \\,\\mathrm d z \\\\ &= \\int \\left(\\ln\\frac{q\_{\\phi}(z\\mid x)}{q\_{\\phi}(z\\mid x)} p\_\\theta (x\\mid z) \\right) p(z) \\, \\mathrm d z \\\\ &= \\int dz q(z\\mid x) \\ln \\frac{p(x,z)}{q(z\\mid x)} + \\int dz q(z\\mid x) \\ln \\frac{q(z\\mid x)}{p(z\\mid x)} \\\\ &= - \\left\[ D\_{\\mathrm{KL}} ( q\_{\\phi}(z\\mid x) \\mathrel{\\Vert} p(z) ) - \\mathbb E\_q ( \\ln p\_\\theta (x\\mid z) ) \\right\] + D\_{\\mathrm{KL}}( q(z\\mid x)\\parallel p(z\\mid x) ) \\\\ & \\geq - \\left\[ D\_{\\mathrm{KL}} ( q\_{\\phi}(z\\mid x) \\mathrel{\\Vert} p(z) ) - \\mathbb E\_q ( \\ln p\_\\theta (x\\mid z) ) \\right\] \\\\ &\\equiv - F(x) \\\\ &\\equiv \\mathcal L . \\end{align} \\\] In the derivation, we used \\(\\int dz q(z\\mid x) = 1\\). The term \\(F(x)\\) is the free energy, while the negative of it, \\(-F(x)=\\mathcal L\\), is the so-called [Evidence Lower Bound (ELBO)](), \\\[ \\mathcal L = - D\_{\\mathrm{KL}} ( q\_{\\phi}(z\\mid x) \\mathrel{\\Vert} p(z) ) + \\mathbb E\_q ( \\ln p\_\\theta (x\\mid z) ). \\\] We also dropped the term \\(D\_{\\mathrm{KL}}( q(z\\mid x)\\parallel p(z\\mid x) )\\) which is always non-negative. The reason is that we can not maximize this KL divergence as we do not know \\(p(z\\mid x)\\). But the KL divergence is always non-negative. So if we find a \\(q\\) that can maximize \\(\\mathcal L\\), then we are also minimizing the KL divergence (with a function \\(q(z\\mid x)\\) that is close to \\(p(z\\mid x)\\)) and maximizing the loglikelihood loss. Now we only need to find a way to maximize \\(\\mathcal L\\). > [!TIP] > > **More about this ELBO** > > We do not know \\(p(x,z)\\) either but we can rewrite \\(\\mathcal L\\), > > \\\[\\begin{align} \\mathcal L(q) =& \\int dz q(z\\mid x) \\ln\\frac{p(x,z)}{q(z\\mid x)} \\\\\\\\ =& \\int dz q(z\\mid x)\\ln \\frac{p(x\\mid z)p(z)}{q(z\\mid x)} \\\\\\\\ = & \\int dz q(z\\mid x) \\ln p(x\\mid z) + \\int dz q(z\\mid x) \\ln \\frac{p(z)}{q(z\\mid x)} \\\\\\\\ = & \\int dz q(z\\mid x) \\ln p(x\\mid z) - \\operatorname{KL} \\left( q(z\\mid x) \\parallel p(z) \\right) \\end{align}\\\] > > Our loss function becomes > > \\\[- \\mathcal L(q) = - \\mathbb E\_{q} \\ln {\\color{red}p(x\\mid z)} + \\operatorname{KL} \\left( {\\color{blue}q(z\\mid x) }\\parallel p(z) \\right),\\\] > > where \\({\\color{blue}q(z\\mid x) }\\) is our encoder which encodes data \\(x\\) to the latent data \\(z\\), and \\({\\color{red}p(x\\mid z)}\\) is our decoder. The second term ensures our encoder is similar to our priors. ## Using Neural networks We model the parameters of the Gaussian distribution \\(p\_\\theta(x\\mid z)\\), e.g., \\(f(z, \\theta)\\), using a neural network. In reality, we choose a gaussian form of the variational functional with the mean and variance depending on the data \\(x\\) and the latent variable \\(z\\) \\\[ q(z\\mid x) = \\mathcal N ( \\mu(x,z), \\Sigma (x,z) ). \\\] We have \\\[ \\begin{align} &\\ln p\_\\theta(x\\mid z) \\\\ =& \\ln \\mathscr N( x\\mid f(z, \\theta), \\sigma^2 I )\\\\ =& \\ln \\left( \\frac{1}{\\sqrt{2\\pi \\sigma^2}} \\exp{\\left( -\\frac{(x -f(z,\\theta)^2)}{\\sigma^2} \\right)} \\right) \\\\ =& -(x - f(z, \\theta))^2 + \\mathrm{Const.} \\end{align} \\\] > [!NOTE] > > **Why don't we simply draw \\(q\\) from \\(p(z)\\)?** > > If we are sort of minimizing the KL divergence \\(\\operatorname{KL} \\left( {\\color{blue}q(z\\mid x) }\\parallel p(z) \\right)\\) too, why don't we simply draw \\(q\\) from \\(p(z)\\)? First of all, we also have to take care of the first term. Secondly, we need a latent space that connects to the actual data for reconstruction. ## Structure ![Simple VAE]() Doersch wrote a very nice tutorial on VAE[^/self-supervised/generative/vae/#Doersch2016]. We can find the detailed structures of VAE. Another key component of VAE is the **reparametrization trick**. The variational approximation \\(q\_\\phi\\) is usually a Gaussian distribution. Once we get the parameters for the Gaussian distribution, we will have to sample from the Gaussian distribution based on the parameters. However, this sampling process prohibits us from propagating errors. The reparametrization trick solves this problem. ### Step by Step: One Pass through a VAE A step-by-step diagram of one pass through a variational autoencoder. It needs JavaScript. In short: the encoder outputs the mean and variance of \\(q\_\\phi(z\\mid x)\\), a latent \\(z\\) is sampled from it, the decoder \\(p\_\\theta(x\\mid z)\\) reconstructs the data, and the loss combines the reconstruction term with the KL divergence to the prior \\(p(z)\\). ## Loss Explanation ![VAE Loss]() > VAE Loss Explained [^/self-supervised/generative/vae/#Doersch2016] ## Code See Lippe[^/self-supervised/generative/vae/#Lippe]. --- **Related:** [ELBO]() · [Forecasting with VAE]() [^/self-supervised/generative/vae/#Doersch2016]: Doersch C. Tutorial on Variational Autoencoders. arXiv \[stat.ML\]. 2016. Available: [http://arxiv.org/abs/1606.05908]() [^/self-supervised/generative/vae/#Lippe]: Lippe P. Tutorial 9: Deep Autoencoders — UvA DL Notebooks v1.1 documentation. In: UvA Deep Learning Tutorials \[Internet\]. \[cited 20 Sep 2021\]. Available: [https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial\_notebooks/tutorial9/AE\_CIFAR10.html]() # Flow > [!NOTE] > > **In one minute** > > A flow model transforms a simple distribution into a complex one through a chain of coordinate transformations, tracking the density with the Jacobian. It runs in a generative direction (sample, then transform) or a normalizing direction (simplify the data distribution). ![Generative Flow]() For a probability density \\(p(x)\\) and a transformation of coordinate \\(x=g(z)\\) or \\(z=f(x)\\), the density can be expressed using the coordinate transformations, i.e., \\\[ \\begin{align} p(x) &= \\tilde p (f(x)) \\lvert \\operatorname{det} \\operatorname{D} g(f(x)) \\rvert^{-1} \\\\ &= \\tilde p(f(x)) \\lvert \\operatorname{det}\\operatorname{D} f(x) \\rvert \\end{align} \\\] where the Jacobian is \\\[ \\operatorname{D} g(z) \\to \\frac{\\partial }{\\partial z} g. \\\] The operation \\(g\_{\*}\\circ \\tilde p(z)\\) is the push forward of \\(\\tilde p(z)\\). The operation \\(g\_{\*}\\) will pushforward simple distribution \\(\\tilde p(z)\\) to a more complex distribution \\(p(x)\\). - The generative direction: sample \\(z\\) from distribution \\(\\tilde p(z)\\), apply transformation \\(g(z)\\); - The normalizing direction: "simplify" \\(p(x)\\) to some simple distribution \\(\\tilde p(z)\\). The key to the flow model is the chaining of the transformations \\\[ \\operatorname{det} \\operatorname{D} f(x) = \\Pi\_{i=1}^N \\operatorname{det} \\operatorname{D} f\_i (x\_i) \\\] where \\\[ \\begin{align} x\_i &= g\_i \\circ \\cdots \\circ g\_1 (z)\\\\ &= f\_{i+1} \\circ \\cdots \\circ f\_N (x). \\end{align} \\\] --- **Related:** [Forecasting with Flow]() [^/self-supervised/generative/flow/#Liu2020]: Liu X, Zhang F, Hou Z, Wang Z, Mian L, Zhang J, et al. Self-supervised Learning: Generative or Contrastive. arXiv \[cs.LG\]. 2020. Available: [http://arxiv.org/abs/2006.08218]() # GAN > [!NOTE] > > **In one minute** > > A GAN trains a generator to fool a discriminator, a minimax game whose optimum is reached only when the generated distribution equals the data distribution, compared through the Jensen-Shannon divergence. The page covers the vanilla GAN, f-GAN and InfoGAN, with code. GAN is a **generative neural sampler**[^/self-supervised/adversarial/gan/#Nowozin2016]. To train the sampler, the task of GAN is designed to generate features \\(X\\) from a latent space \\(\\xi\\) and class labels \\(Y\\), \\\[\\xi, Y \\to X.\\\] Many different formulations of GANs are proposed. As an introduction to this topic, we will discuss vanilla GAN in this section[^/self-supervised/adversarial/gan/#Goodfellow2014]. ## GAN Theory ### The Minimax Game Loss The minimax game is a game to "minimizing the possible loss for a worst-case"[^/self-supervised/adversarial/gan/#minimax_wiki]. In GAN, the game is to train the generator \\({\\color{red}G}\\) to fool the discriminator \\({\\color{green}D}\\) while minimizing the discrimination error of \\({\\color{green}D}\\). Goodfellow prosed a loss[^/self-supervised/adversarial/gan/#Goodfellow2014] \\\[ \\begin{equation} \\underset{{\\color{red}G}}{\\operatorname{min}}\\underset{{\\color{green}D}}{\\operatorname{max}} V({\\color{green}D}, {\\color{red}G}) = \\mathbb E\_{x\\sim p\_{data}} \\left\[ \\log {\\color{green}D}(x) \\right\] + \\mathbb E\_{z\\sim p\_z} \\left\[ \\log( 1- {\\color{green}D}({\\color{red}G}(z)) ) \\right\]. \\end{equation} \\\] ### Divergence Goodfellow et al proved that the global minimum of such a setup is reached only if only \\(p\_{G} = p\_\\text{data}\\). GAN compares the generated distribution to the data distribution, using the Jensen-Shannon divergence[^/self-supervised/adversarial/gan/#Goodfellow2014], \\\[ \\operatorname{D}\_{\\text{JS}}(p\_\\text{data}\\Vert p\_{{\\color{red}G}}) = \\frac{1}{2}\\left\[ \\operatorname{D}\_\\text{KL} \\left( p\_\\text{data} \\bigg\\Vert \\frac{p\_\\text{data} + p\_{\\color{red}G}}{2} \\right) + \\operatorname{D}\_\\text{KL} \\left( p\_{{\\color{red}G}} \\bigg\\Vert \\frac{p\_\\text{data} + p\_{\\color{red}G}}{2} \\right) \\right\]. \\\] > [!WARNING] > > **Off by a Constant** > > The value function of GAN for fixed \\(G\\) is slightly different from JS divergence[^/self-supervised/adversarial/gan/#Goodfellow2014], > > \\\[ \\underset{G}{\\operatorname{max}}V({\\color{red}G},{\\color{green}D}) = 2 \\operatorname{D}\_\\text{JS}( p\_\\text{data} \\Vert p\_{\\color{red}G} ) - \\log 4. \\\] ### Alternating Training GAN training requires two stages, - train discriminator \\({\\color{green}D}\\), and - train generator \\({\\color{red}G}\\). ![GAN Alternating Training]() ## GAN Code We built a simple GAN using MNIST dataset. The generated images look quite close to handwritings. ![]() ``` import matplotlib.pyplot as plt import torch from pathlib import Path import torchvision import torchvision.transforms as transforms from loguru import logger from torch import nn import click logger.debug(f"Setting device ...") device = "" if torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") logger.info(f"Device in use: {device}") def plot_images(image_samples, target): """Plot a grid of images and save to a file.""" if not Path(target).parent.exists(): Path(target).parent.mkdir(parents=True) # real_samples, mnist_labels = next(iter(train_loader)) for i in range(16): ax = plt.subplot(4, 4, i + 1) plt.imshow(image_samples[i].reshape(28, 28), cmap="gray_r") plt.xticks([]) plt.yticks([]) plt.savefig(target) def get_data_loaders(batch_size=32, data_dir="data/mnist", download=True, plot_samples=True): """Get MNIST data and built a dataloader for the dataset""" transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))] ) train_set = torchvision.datasets.MNIST( root=data_dir, train=True, download=download, transform=transform ) train_loader = torch.utils.data.DataLoader( train_set, batch_size=batch_size, shuffle=True ) if plot_samples: real_samples, mnist_labels = next(iter(train_loader)) plot_images(real_samples, target="assets/real_images/real_image_samples.png") return train_loader class Discriminator(nn.Module): """The discrimnator should take data that has the dimension of the image and spit out a probability""" def __init__(self): super().__init__() self.model = nn.Sequential( nn.Linear(784, 1024), nn.ReLU(), nn.Dropout(0.3), nn.Linear(1024, 512), nn.ReLU(), nn.Dropout(0.3), nn.Linear(512, 256), nn.ReLU(), nn.Dropout(0.3), nn.Linear(256, 1), nn.Sigmoid(), ) def forward(self, x): x = x.view(x.size(0), 784) output = self.model(x) return output class Generator(nn.Module): """The generator should take in some noise data (a latent space data) and spit out an image. We use the input noise as a trick to make the generator more general """ def __init__(self): super().__init__() self.model = nn.Sequential( # nn.Linear(10, 100), # nn.ReLU(), nn.Linear(100, 256), nn.ReLU(), nn.Linear(256, 512), nn.ReLU(), nn.Linear(512, 1024), nn.ReLU(), nn.Linear(1024, 784), nn.Tanh(), ) def forward(self, x): output = self.model(x) output = output.view(x.size(0), 1, 28, 28) return output @click.command() @click.option("--epochs", default=50, help="Number of epochs for the training") @click.option("--learning_rate", "-lr", default=0.0001, help="Learning rate for the optimizer") @click.option("--batch_size", default=32, help="Batch size") @click.option("--data_dir", default="data/mnist", help="Directory for storing the dataset") @click.option("--download_mnist", "-d", default=True, type=bool, help="Whether to download MNIST data") @click.option("--random_seed", "-rs", default=42, type=int, help="Random seed for the random generators") def main(epochs, learning_rate, batch_size, data_dir, download_mnist, random_seed): latent_space_dim = 100 torch.manual_seed(random_seed) # check the dtypes logger.debug( f"torch tensor dtype: {torch.tensor([1.2, 3]).dtype}" ) # torch.set_default_dtype(torch.float64) # logger.debug( # f"set torch tensor dtype to 64: {torch.tensor([1.2, 3]).dtype}" # ) train_loader = get_data_loaders( batch_size=batch_size, data_dir=data_dir, download=download_mnist ) logger.debug(f"Training data is ready") discriminator = Discriminator().to(device=device) generator = Generator().to(device=device) loss_function = nn.BCELoss() optimizer_discriminator = torch.optim.Adam( discriminator.parameters(), lr=learning_rate ) optimizer_generator = torch.optim.Adam(generator.parameters(), lr=learning_rate) for epoch in range(epochs): for n, (real_samples, mnist_labels) in enumerate(train_loader): # We prepare some data for training the discriminator # Here we will prepare both the generated data and the real data real_samples = real_samples.to(device=device) real_samples_labels = torch.ones((batch_size, 1)).to(device=device) latent_space_samples = torch.randn((batch_size, latent_space_dim)).to(device=device) # logger.debug(f"Latent space samples: {latent_space_samples}") generated_samples = generator(latent_space_samples) # logger.debug(f"Generated samples:{generated_samples}") generated_samples_labels = torch.zeros((batch_size, 1)).to(device=device) all_samples = torch.cat((real_samples, generated_samples)) all_samples_labels = torch.cat((real_samples_labels, generated_samples_labels)) # Training the discriminator # The discrinimator is trained using the samples we generated above, i.e. # the generated samples and the real images discriminator.zero_grad() output_discriminator = discriminator(all_samples) loss_discriminator = loss_function(output_discriminator, all_samples_labels) loss_discriminator.backward() optimizer_discriminator.step() # Generate some noise data for training the generator # latent_space_samples_generator = torch.randn((batch_size, latent_space_dim)).to(device=device) # Training the generator using the training optimizer generator.zero_grad() generated_samples_generator = generator(latent_space_samples_generator) output_discriminator_generated = discriminator(generated_samples_generator) loss_generator = loss_function( output_discriminator_generated, real_samples_labels ) loss_generator.backward() optimizer_generator.step() # Show loss if n == batch_size - 1: print(f"Epoch: {epoch} Loss D.: {loss_discriminator}") print(f"Epoch: {epoch} Loss G.: {loss_generator}") logger.debug(f"Plotting for epoch: {epoch} ...") latent_space_samples_epoch = torch.randn(batch_size, latent_space_dim).to(device=device) generated_samples_epoch = generator(latent_space_samples_epoch) generated_samples_epoch = generated_samples_epoch.cpu().detach() plot_images(generated_samples_epoch, target=f"assets/generated_images/generated_image_samples_{epoch}.png") logger.debug(f"Saved plots for epoch: {epoch}") latent_space_samples = torch.randn(batch_size, latent_space_dim).to(device=device) generated_samples = generator(latent_space_samples) logger.debug(f"Plot generated images...") generated_samples = generated_samples.cpu().detach() plot_images(generated_samples, target="assets/generated_images/generated_image_samples.png") if __name__ == "__main__": main() ``` ## f-GAN The essence of [GAN]() is comparing the generated distribution \\(p\_G\\) and the data distribution \\(p\_\\text{data}\\). The vanilla GAN considers the Jensen-Shannon divergence \\(\\operatorname{D}\_\\text{JS}(p\_\\text{data}\\Vert p\_{G})\\). The discriminator \\({\\color{green}D}\\) serves the purpose of forcing this divergence to be small. > [!NOTE] > > **Why do we need the discriminator?** > > If the JS divergence is an objective, why do we need the discriminator? Even in f-GAN we need a functional to approximate the f-divergence. This functional we choose works like the discriminator of GAN. There exists a more generic form of JS divergence, which is called [f-divergence]()[^/self-supervised/adversarial/gan/#f-divergence_wiki]. f-GAN obtains the model by estimating the f-divergence between the data distribution and the generated distribution[^/self-supervised/adversarial/gan/#Nowozin2016]. ### Variational Divergence Minimization The Variational Divergence Minimization (VDM) extends the variational estimation of f-divergence[^/self-supervised/adversarial/gan/#Nowozin2016]. VDM searches for the saddle point of an objective \\(F({\\color{red}\\theta}, {\\color{blue}\\omega})\\), i.e., min w.r.t. \\(\\theta\\) and max w.r.t \\({\\color{blue}\\omega}\\), where \\({\\color{red}\\theta}\\) is the parameter set of the generator \\({\\color{red}Q\_\\theta}\\), and \\({\\color{blue}\\omega}\\) is the parameter set of the variational approximation to estimate f-divergence, \\({\\color{blue}T\_\\omega}\\). The objective \\(F({\\color{red}\\theta}, {\\color{blue}\\omega})\\) is related to the choice of \\(f\\) in f-divergence and the variational functional \\({\\color{blue}T}\\), \\\[ \\begin{align} & F(\\theta, \\omega)\\\\ =& \\mathbb E\_{x\\sim p\_\\text{data}} \\left\[ {\\color{blue}T\_\\omega}(x) \\right\] - \\mathbb E\_{x\\sim {\\color{red}Q\_\\theta} } \\left\[ f^\*({\\color{blue}T\_\\omega}(x)) \\right\] \\\\ =& \\mathbb E\_{x\\sim p\_\\text{data}} \\left\[ g\_f(V\_{\\color{blue}\\omega}(x)) \\right\] - \\mathbb E\_{x\\sim {\\color{red}Q\_\\theta} } \\left\[ f^\*(g\_f(V\_{\\color{blue}\\omega}(x))) \\right\]. \\end{align} \\\] In the above objective, - \\(f^\*\\) is the [Legendre–Fenchel transformation]() of \\(f\\), i.e., \\(f^\*(t) = \\operatorname{sup}\_{u\\in \\mathrm{dom}\_f}\\left\\{ ut - f(u) \\right\\}\\). > [!TIP] > > **\\(T\\)** > > The function \\(T\\) is used to estimate the lower bound of f-divergence[^/self-supervised/adversarial/gan/#Nowozin2016]. > [!TIP] > > **Choice of \\(g\_f\\) and \\(V\\)** > > Nowozin et al provided a table for \\(g\_f\\) and \\(V\\)[^/self-supervised/adversarial/gan/#Nowozin2016]. > > ![]() We estimate - \\(\\mathbb E\_{x\\sim p\_\\text{data}}\\) by sampling from the mini-batch, and - \\(\\mathbb E\_{x\\sim {\\color{red}Q\_\\theta} }\\) by sampling from the generator. > [!NOTE] > > **Reduce to GAN** > > The VDM loss can be reduced to the [loss of GAN]() by setting[^/self-supervised/adversarial/gan/#Nowozin2016] > > \\\[ \\begin{align} \\log {\\color{green}D\_\\omega} =& g\_f(V\_{\\color{blue}\\omega}(x)) \\\\ \\log \\left( 1 - {\\color{green}D\_\\omega} \\right) =& -f^\*\\left( g\_f(V\_{\\color{blue}\\omega}(x)) \\right). \\end{align} \\\] > > It is straightforward to validate that the following result is a solution to the above set of equations, > > \\\[ g\_f(V) = \\log \\frac{1}{1 + e^{-V}}. \\\] ### Code - [minlee077/f-GAN-pytorch]() - [shayneobrien/generative-models]() ## InfoGAN In GAN, the latent space input is usually random noise, e.g., Gaussian noise. The objective of [GAN]() is a very generic one. It doesn't say anything about how exactly the latent space will be used. This is not desirable in many problems. We would like to have more interpretability in the latent space. InfoGAN introduced constraints to the objective to enforce the interpretability of the latent space[^/self-supervised/adversarial/gan/#Chen2016]. ### Constraint The constraint InfoGAN proposed is [mutual information](), \\\[ \\underset{{\\color{red}G}}{\\operatorname{min}} \\underset{{\\color{green}D}}{\\operatorname{max}} V\_I ({\\color{green}D}, {\\color{red}G}) = V({\\color{green}D}, {\\color{red}G}) - \\lambda I(c; {\\color{red}G}(z,c)), \\\] where - \\(c\\) is the latent code, - \\(z\\) is the random noise input, - \\(V({\\color{green}D}, {\\color{red}G})\\) is the objective of GAN, - \\(I(c; {\\color{red}G}(z,c))\\) is the mutual information between the input latent code and generated data. Using the lambda multiplier, we punish the model if the generator loses information in latent code \\(c\\). ### Training ![InfoGAN]() The training steps are almost the same as [GAN]() but with one extra loss to be calculated in each mini-batch. 1. Train \\(\\color{red}G\\) using loss: \\(\\operatorname{MSE}(v', v)\\); 2. Train \\(\\color{green}D\\) using loss: \\(\\operatorname{MSE}(v', v)\\); 3. Apply Constraint: 1. Sample data from mini-batch; 2. Calculate loss \\(\\lambda\_{l} H(l';l)+\\lambda\_c \\operatorname{MSE}(c,c')\\) ### Python Code [eriklindernoren/PyTorch-GAN]() --- **Related:** [Forecasting with GAN]() [^/self-supervised/adversarial/gan/#Nowozin2016]: Nowozin S, Cseke B, Tomioka R. f-GAN: Training Generative Neural Samplers using Variational Divergence Minimization. arXiv \[stat.ML\]. 2016. Available: [http://arxiv.org/abs/1606.00709]() [^/self-supervised/adversarial/gan/#minimax_wiki]: Contributors to Wikimedia projects. Minimax. In: Wikipedia \[Internet\]. 5 Aug 2021 \[cited 6 Sep 2021\]. Available: [https://en.wikipedia.org/wiki/Minimax]() [^/self-supervised/adversarial/gan/#Goodfellow2014]: Goodfellow IJ, Pouget-Abadie J, Mirza M, Xu B, Warde-Farley D, Ozair S, et al. Generative Adversarial Networks. arXiv \[stat.ML\]. 2014. Available: [http://arxiv.org/abs/1406.2661]() [^/self-supervised/adversarial/gan/#Liu2020]: Liu X, Zhang F, Hou Z, Wang Z, Mian L, Zhang J, et al. Self-supervised Learning: Generative or Contrastive. arXiv \[cs.LG\]. 2020. Available: [http://arxiv.org/abs/2006.08218]() [^/self-supervised/adversarial/gan/#Arjovsky2017]: Arjovsky M, Chintala S, Bottou L. Wasserstein GAN. arXiv \[stat.ML\]. 2017. Available: [http://arxiv.org/abs/1701.07875]() [^/self-supervised/adversarial/gan/#f-divergence_wiki]: Contributors to Wikimedia projects. F-divergence. In: Wikipedia \[Internet\]. 17 Jul 2021 \[cited 6 Sep 2021\]. Available: [https://en.wikipedia.org/wiki/F-divergence\#Instances\_of\_f-divergences]() [^/self-supervised/adversarial/gan/#convex_conjugate_wiki]: Contributors to Wikimedia projects. Convex conjugate. In: Wikipedia \[Internet\]. 20 Feb 2021 \[cited 7 Sep 2021\]. Available: [https://en.wikipedia.org/wiki/Convex\_conjugate]() [^/self-supervised/adversarial/gan/#Chen2016]: Chen X, Duan Y, Houthooft R, Schulman J, Sutskever I, Abbeel P. InfoGAN: Interpretable Representation Learning by Information Maximizing Generative Adversarial Nets. arXiv \[cs.LG\]. 2016. Available: [http://arxiv.org/abs/1606.03657]() [^/self-supervised/adversarial/gan/#Agakov2004]: Agakov DBF. The im algorithm: a variational approach to information maximization. Adv Neural Inf Process Syst. 2004. Available: [https://books.google.com/books?hl=en&lr=&id=0F-9C7K8fQ8C&oi=fnd&pg=PA201&dq=Algorithm+variational+approach+Information+Maximization+Barber+Agakov&ots=TJGrkVS610&sig=yTKM2ZdcZQBTY4e5Vqk42ayUDxo]() # Time Series Forecasting with Deep Learning # Time Series Forecasting with Deep Learning > [!NOTE] > > **In one minute** > > Deep learning models train on batches, so a time series first has to be cut into fixed-length inputs and targets. The page shows the DataFrameDataset class of the ts\_dl\_utils package, which slides along the time axis with a history length, a horizon and an optional gap, and what its first data point looks like. > > **Read first:** [The Time Delay Embedding Representation]() In the chapter [Deep Learning Fundamentals](), we discussed some deep learning models. In this chapter, we will discuss how to apply deep learning models to time series forecasting problems. ## Creating Dataset for Deep Learning Models Deep learning models usually require batches of data to train. For time series data, we need to slice along the time axis to create batches. In section [The Time Delay Embedding Representation](), we discussed methods to represent time series data. In this section, we provide an example. In our [`ts_dl_utils` package](), we provide a class called `DataFrameDataset`. This class moves along the time axis and cuts the time series into multiple data points. ```` from typing import Tuple import numpy as np import pandas as pd from loguru import logger from torch.utils.data import Dataset class DataFrameDataset(Dataset): """A dataset from a pandas dataframe. For a given pandas dataframe, this generates a pytorch compatible dataset by sliding in time dimension. ```python ds = DataFrameDataset( dataframe=df, history_length=10, horizon=2 ) ``` :param dataframe: input dataframe with a DatetimeIndex. :param history_length: length of input X in time dimension in the final Dataset class. :param horizon: number of steps to be forecasted. :param gap: gap between input history and prediction """ def __init__( self, dataframe: pd.DataFrame, history_length: int, horizon: int, gap: int = 0 ): super().__init__() self.dataframe = dataframe self.history_length = history_length self.horzion = horizon self.gap = gap self.dataframe_rows = len(self.dataframe) self.length = ( self.dataframe_rows - self.history_length - self.horzion - self.gap + 1 ) def moving_slicing(self, idx: int, gap: int = 0) -> Tuple[np.ndarray, np.ndarray]: x, y = ( self.dataframe[idx : self.history_length + idx].values, self.dataframe[ self.history_length + idx + gap : self.history_length + self.horzion + idx + gap ].values, ) return x, y def _validate_dataframe(self) -> None: """Validate the input dataframe. - We require the dataframe index to be DatetimeIndex. - This dataset is null aversion. - Dataframe index should be sorted. """ if not isinstance( self.dataframe.index, pd.core.indexes.datetimes.DatetimeIndex ): raise TypeError( "Type of the dataframe index is not DatetimeIndex" f": {type(self.dataframe.index)}" ) has_na = self.dataframe.isnull().values.any() if has_na: logger.warning("Dataframe has null") has_index_sorted = self.dataframe.index.equals( self.dataframe.index.sort_values() ) if not has_index_sorted: logger.warning("Dataframe index is not sorted") def __getitem__(self, idx: int) -> Tuple[np.ndarray, np.ndarray]: if isinstance(idx, slice): if (idx.start < 0) or (idx.stop >= self.length): raise IndexError(f"Slice out of range: {idx}") step = idx.step if idx.step is not None else 1 return [ self.moving_slicing(i, self.gap) for i in range(idx.start, idx.stop, step) ] else: if idx >= self.length: raise IndexError("End of dataset") return self.moving_slicing(idx, self.gap) def __len__(self) -> int: return self.length ```` For example, give a time series dataset, | index | y | | ---: | ---: | | 0 | 0 | | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | 4 | | 5 | 5 | | 6 | 6 | | 7 | 7 | | 8 | 8 | | 9 | 9 | | 10 | 10 | | 11 | 11 | | 12 | 12 | | 13 | 13 | | 14 | 14 | The first data point of `DataFrameDataset(dataframe=df, history_length=10, horizon=1)` will be ``` (array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]), array([[10]])) ``` ## Try It: Slicing a Series into Data Points The widget uses the same 15-row dataframe as the example above. Change `history_length`, `horizon` and `gap` to see which rows become the input `x` and the target `y` of each data point, and how many data points the dataset has. *Interactive demo: enable JavaScript to slice the example dataframe into data points.* --- **Related:** [Pendulum Dataset]() · [Notebooks and Utilities for Tutorials]() # Pendulum Dataset > [!NOTE] > > **In one minute** > > A synthetic dataset from a damped pendulum: the angle follows a cosine whose amplitude decays exponentially, with the period set by the length of the pendulum. The models in this chapter are trained to forecast this series, and the page gives the code that generates it. We create a synthetic dataset based on the physical model called pendulum. The pendulum is modeled as a damped harmonic oscillator, i.e., \\\[ \\theta(t) = \\theta(0) \\cos(2 \\pi t / p)\\exp(-\\beta t), \\\] where \\(\\theta(t)\\) is the angle of the pendulum at time \\(t\\). The period \\(p\\) is calculated using \\\[ p = 2 \\pi \\sqrt{L / g}, \\\] with \\(L\\) being the length of the pendulum and \\(g\\) being the surface gravity. ![Pendulum data]() ``` import math from functools import cached_property from typing import Dict, List import pandas as pd class Pendulum: """Class for generating time series data for a pendulum. The pendulum is modelled as a damped harmonic oscillator, i.e., $$ \theta(t) = \theta(0) \cos(2 \pi t / p)\exp(-\beta t), $$ where $\theta(t)$ is the angle of the pendulum at time $t$. The period $p$ is calculated using $$ p = 2 \pi \sqrt{L / g}, $$ with $L$ being the length of the pendulum and $g$ being the surface gravity. :param length: Length of the pendulum. :param gravity: Acceleration due to gravity. """ def __init__(self, length: float, gravity: float = 9.81) -> None: self.length = length self.gravity = gravity @cached_property def period(self) -> float: """Calculate the period of the pendulum.""" return 2 * math.pi * math.sqrt(self.length / self.gravity) def __call__( self, num_periods: int, num_samples_per_period: int, initial_angle: float = 0.1, beta: float = 0, ) -> Dict[str, List[float]]: """Generate time series data for the pendulum. Returns a list of floats representing the angle of the pendulum at each time step. :param num_periods: Number of periods to generate. :param num_samples_per_period: Number of samples per period. :param initial_angle: Initial angle of the pendulum. """ time_step = self.period / num_samples_per_period steps = [] time_series = [] for i in range(num_periods * num_samples_per_period): t = i * time_step angle = ( initial_angle * math.cos(2 * math.pi * t / self.period) * math.exp(-beta * t) ) steps.append(t) time_series.append(angle) return {"t": steps, "theta": time_series} pen = Pendulum(length=100) df = pd.DataFrame(pen(10, 400, initial_angle=1, beta=0.001)) _, ax = plt.subplots(figsize=(10, 6.18)) df.plot(x="t", y="theta", ax=ax) ``` We take this time series and ask our model to forecast the next step (**forecast horizon is 1**). > [!NOTE] > > **PyTorch Dataset and Lightning DataModule** > > In our tutorials, we will use Pytorch lightning excessively. We defined some useful modules in our and [📓 this notebook](). --- **Related:** [Time Series Forecasting with Deep Learning]() · [Forecasting with Feedforward Neural Networks]() # Forecasting with Feedforward Neural Networks > [!NOTE] > > **In one minute** > > A feedforward network with five hidden layers forecasts the pendulum series from 100 past steps: first one step ahead across a gap of 10 steps, then three steps ahead. It beats the naive forecast on all three metrics, and a small trained model runs in the browser at the end of the page. > > **Read first:** [Neural Networks]() · [Pendulum Dataset]() > [!NOTE] > > **Jupyter Notebook Available** > > We have a [📓 notebook]() for this section which includes all the code used in this section. > [!NOTE] > > **Introduction to Neural Networks** > > We explain the theories of neural networks in [this section](). Please read it first if you are not familiar with neural networks. Feedforward neural networks are simple but powerful models for time series forecasting. In this section, we will build a simple feedforward neural network to forecast our [pendulum physics data](). ## Feedforward Neural Network Model We build a feedforward neural network with 5 hidden layers. The input is passed to the first hidden layer, and the output of the first hidden layer is passed to the second hidden layer. The output of the second hidden layer is passed to the third hidden layer, and so on. The output of the last hidden layer is passed to the output layer. The output layer outputs the forecasted values. ``` flowchart TD input_layer["Input Layer (100)"] output_layer["Output Layer (1)"] subgraph hidden_layers["Hidden Layers"] hidden_layer_1["Hidden Layer (512)"] hidden_layer_2["Hidden Layer (256)"] hidden_layer_3["Hidden Layer (64)"] hidden_layer_4["Hidden Layer (256)"] hidden_layer_5["Hidden Layer (512)"] hidden_layer_1 --> hidden_layer_2 hidden_layer_2 --> hidden_layer_3 hidden_layer_3 --> hidden_layer_4 hidden_layer_4 --> hidden_layer_5 end input_layer --> hidden_layers hidden_layers --> output_layer ``` ``` from typing import Dict, List import dataclasses from torch.utils.data import Dataset, DataLoader from torch import nn import torch @dataclasses.dataclass class TSFFNParams: """A dataclass to be served as our parameters for the model. :param hidden_widths: list of dimensions for the hidden layers """ hidden_widths: List[int] class TSFeedForward(nn.Module): """Feedforward networks for univaraite time series modeling. :param history_length: the length of the input history. :param horizon: the number of steps to be forecasted. :param ffn_params: the parameters for the FFN network. """ def __init__( self, history_length: int, horizon: int, ffn_params: TSFFNParams ): super().__init__() self.ffn_params = ffn_params self.history_length = history_length self.horizon = horizon self.regulate_input = nn.Linear( self.history_length, self.ffn_params.hidden_widths[0] ) self.hidden_layers = nn.Sequential( *[ self._linear_block(dim_in, dim_out) for dim_in, dim_out in zip( self.ffn_params.hidden_widths[:-1], self.ffn_params.hidden_widths[1:] ) ] ) self.regulate_output = nn.Linear( self.ffn_params.hidden_widths[-1], self.horizon ) @property def ffn_config(self) -> Dict: return dataclasses.asdict(self.ffn_params) def _linear_block(self, dim_in, dim_out): return nn.Sequential(*[nn.Linear(dim_in, dim_out), nn.ReLU()]) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.regulate_input(x) x = self.hidden_layers(x) return self.regulate_output(x) ``` ## Results We take 100 time steps as the input history and forecast 1 time step into the future, but with a gap of 10 time steps. ![Task]() > [!NOTE] > > **Why the Gap** > > Since the differences between each steps are tiny, forecasting immediate next step is quite easy. We add a gap to make the forecasting problem a bit harder. > [!NOTE] > > **Training** > > The details for model training can be found in this [📓 notebook](). We will skip the details but show the loss curve here. > > ![Training]() We plotted the forecasts for a test dataset that was held out from training. The forecasts are plotted in red and the ground truth is plotted in green. For a sense of goodness, we also added the naive forecast (forecasting the last observed value) in blue. ![Results]() The feedforward neural network learned the damped sine wave pattern of the pendulum. To quantify the results, we compute a few metrics. | Metric | FFN | Naive | | --- | --- | --- | | Mean Absolute Error | **0.017704** | 0.092666 | | Mean Squared Error | **0.000571** | 0.010553 | | Symmetric Mean Absolute Percentage Error | **0.010806** | 0.050442 | Since the differences between each time step are small, the naive forecast performs quite well. ## Multi-horizon Forecasting We perform a similar experiment but forecast 3 time steps into the future. We plot out some samples. In the plot, the orange shaded regions are the predictions. From these samples, we observe that the forecasts make sense. ![multihorizon sample]() To observe the quality of the whole time range, we plot out the first forecast step and the corresponding ground truth. The naive forecast plotted in blue has an obvious shift, while the feedforward neural network plotted in red is much closer to the ground truth. ![multihorizon results]() | Metric | FFN | Naive | | --- | --- | --- | | Mean Absolute Error | **0.024640** | 0.109485 | | Mean Squared Error | **0.001116** | 0.014723 | | Symmetric Mean Absolute Percentage Error | **0.015637** | 0.059591 | ## Try a Trained Model in Your Browser The demo below runs a small feedforward network like the one above, trained offline with PyTorch (`scripts/pendulum_onnx.py`) on pendulums of different lengths and starting angles, this time using the full nonlinear equation of motion instead of the small-angle formula. The model was exported to ONNX and runs in your browser with ONNX Runtime Web: it reads the first 24 angles and forecasts the next 24, or 72 if you switch to the autoregressive rollout, which feeds its own forecasts back in. Push \\(\\theta\_0\\) towards 170° to see it struggle: near the top the pendulum hardly moves during the context window, so small errors decide when it falls. *Interactive demo: enable JavaScript to run the pendulum forecaster in your browser.* --- **Related:** [Forecasting with RNN]() · [Time Series Forecasting Metrics]() # Forecasting with RNN > [!NOTE] > > **In one minute** > > An RNN with a single recurrent block and a hidden size of 64 forecasts the pendulum series, one step and three steps ahead, each across a gap of 10 steps. After a few seconds of training it follows the oscillation and scores much better than the naive forecast. > > **Read first:** [Recurrent Neural Networks]() · [Pendulum Dataset]() > [!NOTE] > > **Jupyter Notebook Available** > > We have a [📓 notebook]() for this section which includes all the code used in this section. > [!NOTE] > > **Introduction to Neural Networks** > > We explain the theories of neural networks in [this section](). Please read it first if you are not familiar with neural networks. In section [Recurrent Neural Network]() we discussed the basics of RNN. In this section, we will build an RNN model to forecast our [pendulum time series data](). ## RNN Model We build an RNN model with an input size of 96, a hidden size of 64 and one single RNN block. We use L1 loss in the trainings. ``` from typing import Dict import dataclasses from torch.utils.data import Dataset, DataLoader from torch import nn import torch @dataclasses.dataclass class TSRNNParams: """A dataclass to be served as our parameters for the model. :param hidden_size: number of dimensions in the hidden state :param input_size: input dim :param num_layers: number of units stacked """ input_size: int hidden_size: int num_layers: int = 1 class TSRNN(nn.Module): """RNN for univaraite time series modeling. :param history_length: the length of the input history. :param horizon: the number of steps to be forecasted. :param rnn_params: the parameters for the RNN network. """ def __init__(self, history_length: int, horizon: int, rnn_params: TSRNNParams): super().__init__() self.rnn_params = rnn_params self.history_length = history_length self.horizon = horizon self.regulate_input = nn.Linear( self.history_length, self.rnn_params.input_size ) self.rnn = nn.RNN( input_size=self.rnn_params.input_size, hidden_size=self.rnn_params.hidden_size, num_layers=self.rnn_params.num_layers, batch_first=True ) self.regulate_output = nn.Linear( self.rnn_params.hidden_size, self.horizon ) @property def rnn_config(self) -> Dict: return dataclasses.asdict(self.rnn_params) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.regulate_input(x) x, _ = self.rnn(x) return self.regulate_output(x) ``` ## One Step Forecasting Similar to [Forecasting with Feedforward Neural Networks](), we take 100 time steps as the input history and forecast 1 time step into the future, but with a gap of 10 time steps. > [!NOTE] > > **Training** > > The details for model training can be found in this [📓 notebook](). We will skip the details but show the loss curve here. > > ![Training]() With just a few seconds of training, our RNN model can capture the pattern of the pendulum time series data. ![RNN Result (Univariate, Horizon 1)]() The metrics are listed in the following table. | Metric | RNN | Naive | | --- | --- | --- | | Mean Absolute Error | 0.007229 | 0.092666 | | Mean Squared Error | 0.000074 | 0.010553 | | Symmetric Mean Absolute Percentage Error | 0.037245 | 0.376550 | ## Multi-Horizon Forecasting We also trained the same model to forecast 3 steps into the future and also with a gap of 10 time steps. > [!NOTE] > > **Training** > > The details for model training can be found in this [📓 notebook](). We will skip the details but show the loss curve here. > > ![Training]() Visualizing a few examples of the forecasts, it looks reasonable in many cases. ![RNN Multihorizon sample]() Similar to the single step forecast, we visualize a specific time step in the forecasts and comparing it to the ground truths. Here we choose to visualize the second time step in the forecasts. ![RNN multihorizon results]() The metrics are listed in the following table. | Metric | RNN | Naive | | --- | --- | --- | | Mean Absolute Error | 0.006714 | 0.109485 | | Mean Squared Error | 0.000069 | 0.014723 | | Symmetric Mean Absolute Percentage Error | 0.032914 | 0.423563 | --- **Related:** [Forecasting with Feedforward Neural Networks]() · [Transformers for Time Series Forecasting]() # Transformers for Time Series Forecasting > [!NOTE] > > **In one minute** > > An encoder-only transformer forecasts the univariate pendulum series: a linear layer shapes the input, the encoder processes it and a second linear layer produces the forecast. It beats the naive forecast one step and three steps ahead, and the page closes with the transformer variants designed for forecasting and the packages that implement them. > > **Read first:** [Vanilla Transformers]() · [Pendulum Dataset]() > [!NOTE] > > **Jupyter Notebook Available** > > We have a [📓 notebook]() for this section which includes all the code used in this section. > [!NOTE] > > **Introduction to Transformers** > > We explain the theories of transformers in [this section](). Please read it first if you are not familiar with transformers. [Transformer]() is a good candidate for time series forecasting due to its sequence modeling capability[^/time-series-deep-learning/timeseries.transformer/#bib-Ahmed2022-wl][^/time-series-deep-learning/timeseries.transformer/#bib-Wen2022-fc]. In this section, we will introduce some basic ideas of transformer-based models for time series forecasting. ## Transformer for Univariate Time Series Forecasting We take a simple [Univariate time series forecasting]() task as an example. There are implementations of transformers for multivariate time series forecasting with all sorts of covariates, but we focus on univariate forecasting problem for simplicity. ### Dataset In this example, we use the [pendulum physics dataset](). ### Model We built a naive transformer that only has an encoder. The input is passed to a linear layer to convert the tensor to the shape accepted by the encoder. The tensor is then passed to the encoder. The output of the encoder is passed to another linear layer to convert the tensor to the shape of the output. ``` flowchart TD input_linear_layer[Linear Layer for Input] positional_encoder[Positional Encoder] encoder[Encoder] output_linear_layer[Linear Layer for Output] input_linear_layer --> positional_encoder positional_encoder --> encoder encoder --> output_linear_layer ``` > [!NOTE] > > **Decoder is Good for Covariates** > > A decoder in a transformer model is good for capturing [future covariates](). In our problem, we do not have any covariates at all. > [!NOTE] > > **Positional Encoder** > > In this experiment, we do not include positional encoder as it introduces more complexities but it doesn't help that much in our case[^/time-series-deep-learning/timeseries.transformer/#bib-Zhang2019-pq]. ### Evaluations > [!NOTE] > > **Training** > > The details for model training can be found in this [📓 notebook](). We will skip the details but show the loss curve here. > > ![Training]() We trained the model using a history length of 50 and plotted the forecasts for a test dataset that was held out from training. The forecasts are plotted in red and the ground truth is plotted in blue. ![Vanilla Transformer Result (Univariate, Horizon 1)]() The forecasts roughly captured the patterns of the pendulum. To quantify the results, we compute a few metrics. | Metric | Vanilla Transformer | Naive | | --- | --- | --- | | Mean Absolute Error | **0.050232** | 0.092666 | | Mean Squared Error | **0.003625** | 0.010553 | | Symmetric Mean Absolute Percentage Error | **0.108245** | 0.376550 | ## Multi-horizon Forecasting We perform a similar experiment for multi-horizon forecasting (horizon=3). We plot out some samples. In the plot, the orange-shaded regions are the predictions. ![Transformer m step result]() To verify that the forecasts make sense, we also plot out a few samples. ![Transformer m step samples]() The following is a table of the metrics. | Metric | Vanilla Transformer | Naive | | --- | --- | --- | | Mean Absolute Error | **0.057219** | 0.109485 | | Mean Squared Error | **0.004241** | 0.014723 | | Symmetric Mean Absolute Percentage Error | **0.112247** | 0.423563 | ## Generalization The vanilla transformer has its limitations. For example, it doesn't capture the correlations between the series that well. There are many variants of transformers that are designed just for time series forecasting[^/time-series-deep-learning/timeseries.transformer/#bib-Lim2019-hd][^/time-series-deep-learning/timeseries.transformer/#bib-Wu2021-zp][^/time-series-deep-learning/timeseries.transformer/#bib-Zhou2020-ov][^/time-series-deep-learning/timeseries.transformer/#bib-Nie2022-ww][^/time-series-deep-learning/timeseries.transformer/#bib-Zhou2022-ry][^/time-series-deep-learning/timeseries.transformer/#bib-Liu2023-wf]. A few forecasting packages implemented transformers for time series forecasting. For example, the [neuralforecast]() package by Nixtla has [implemented]() TFT, Informer, AutoFormer, FEDFormer, and PatchTST, as of November 2023. An alternative is [darts](). These packages provide documentation and we encourage the reader to check them out for more complicated use cases of transformer-based models. --- **Related:** [Time Series Forecasting Tasks]() · [Forecasting with RNN]() [^/time-series-deep-learning/timeseries.transformer/#bib-Ahmed2022-wl]: Ahmed S., Nielsen I.E., Tripathi A. et al.. Transformers in time-series analysis: A tutorial. 2022. [http://dx.doi.org/10.1007/s00034-023-02454-8]() [^/time-series-deep-learning/timeseries.transformer/#bib-Wen2022-fc]: Wen Q., Zhou T., Zhang C. et al.. Transformers in time series: A survey. 2022. [http://arxiv.org/abs/2202.07125]() [^/time-series-deep-learning/timeseries.transformer/#bib-Zhang2019-pq]: Zhang Y., Jiang Q., Li S. et al.. You may not need order in time series forecasting. *arXiv \[cs.LG\]*. 2019. [http://arxiv.org/abs/1910.09620]() [^/time-series-deep-learning/timeseries.transformer/#bib-Lim2019-hd]: Lim B., Arik S.O., Loeff N. et al.. Temporal fusion transformers for interpretable multi-horizon time series forecasting. 2019. [http://arxiv.org/abs/1912.09363]() [^/time-series-deep-learning/timeseries.transformer/#bib-Wu2021-zp]: Wu H., Xu J., Wang J. et al.. Autoformer: Decomposition Transformers with Auto-Correlation for long-term series forecasting. 2021. [https://github.com/thuml/Autoformer]() [^/time-series-deep-learning/timeseries.transformer/#bib-Zhou2020-ov]: Zhou H., Zhang S., Peng J. et al.. Informer: Beyond efficient transformer for long sequence time-series forecasting. 2020. [http://arxiv.org/abs/2012.07436]() [^/time-series-deep-learning/timeseries.transformer/#bib-Nie2022-ww]: Nie Y., Nguyen N.H., Sinthong P. et al.. A time series is worth 64 words: Long-term forecasting with transformers. 2022. [http://arxiv.org/abs/2211.14730]() [^/time-series-deep-learning/timeseries.transformer/#bib-Zhou2022-ry]: Zhou T., Ma Z., Wen Q. et al.. FEDformer: Frequency Enhanced Decomposed Transformer for long-term series forecasting. 2022. [http://arxiv.org/abs/2201.12740]() [^/time-series-deep-learning/timeseries.transformer/#bib-Liu2023-wf]: Liu Y., Hu T., Zhang H. et al.. ITransformer: Inverted Transformers are effective for time series forecasting. 2023. [http://arxiv.org/abs/2310.06625]() # Forecasting with Convolutional Neural Networks # Forecasting with VAE # Forecasting with Flow # Forecasting with GAN # Time Series Forecasting with Neural ODE > [!NOTE] > > **In one minute** > > A neural ODE, built with torchdyn and with a small neural network as its field, forecasts the pendulum series from 100 past steps. It suits this dataset because the pendulum is itself generated by a differential equation; the page reports one-step and three-step results against the naive forecast. > > **Read first:** [Neural ODE]() · [Pendulum Dataset]() > [!NOTE] > > **Jupyter Notebook Available** > > We have a [📓 notebook]() for this section which includes all the code used in this section. > [!NOTE] > > **Introduction to Neural ODE** > > We explain the theories of neuralode in [this section](). Please read it first if you are not familiar with neural ode. In the section [Neural ODE](), we have introduced the concept of neural ODE. In this section, we will show how to use neural ODE to do time series forecasting. ## A Neural ODE Model We built a single hidden layer neural network as the field, ``` graph TD input["Input (100)"] input_layer["Hidden Layer (100)"] output_layer["Output Layer (100)"] hidden_layer["Hidden Layer (256)"] output["Output (1)"] input --> input_layer input_layer --> hidden_layer hidden_layer --> output_layer output_layer --> output ``` The model is built using the package called [torchdyn]() [^/time-series-deep-learning/timeseries.neural-ode/#bib-Poli_TorchDyn_Implicit_Models]. > [!NOTE] > > **Packages** > > Apart from the torchdyn package we used here, there is another package called [torchdiffeq]() [^/time-series-deep-learning/timeseries.neural-ode/#bib-Chen_torchdiffeq_2021] which is developed by the authors of neural ode. ## Single Step Forecasts We trained the model using a history length of 100 and only forecast one step (with a gap of 10 between the input and target). The result is shown below. ![Results]() Neural ODE is a good forecaster for our pendulum dataset since the pendulum is simply generated by a differential equation. The metrics are also computed and listed below. | Metric | Neural ODE | Naive | | --- | --- | --- | | Mean Absolute Error | **0.003052** | 0.092666 | | Mean Squared Error | **0.000009** | 0.010553 | | Symmetric Mean Absolute Percentage Error | **0.021231** | 0.376550 | > [!NOTE] > > **Training** > > The training loss is shown below. > > ![Training]() ## Multi-Step Forecasts We perform a similar experiment but forecast 3 steps. ![NODE results]() We plot out some samples and shade the predictions using orange color. The plot below shows that the forecasts are mostly on the right trend. ![NODE samples]() | Metric | Neural ODE | Naive | | --- | --- | --- | | Mean Absolute Error | **0.038421** | 0.109485 | | Mean Squared Error | **0.001478** | 0.014723 | | Symmetric Mean Absolute Percentage Error | **0.153392** | 0.423563 | --- **Related:** [Dynamical Systems]() · [Forecasting with RNN]() [^/time-series-deep-learning/timeseries.neural-ode/#bib-Poli_TorchDyn_Implicit_Models]: Poli M., Massaroli S., Yamashita A. et al.. TorchDyn: Implicit Models and Neural Numerical Methods in PyTorch. [https://github.com/DiffEqML/torchdyn]() [^/time-series-deep-learning/timeseries.neural-ode/#bib-Chen_torchdiffeq_2021]: Chen R.T.Q.. torchdiffeq. 2021. [https://github.com/rtqichen/torchdiffeq]() # TimeGrad Using Diffusion Model > [!NOTE] > > **In one minute** > > TimeGrad (Rasul et al., 2021) turns the denoising diffusion model into a probabilistic forecaster for multivariate series. The forecast is factorized autoregressively over time, an RNN state carries the time dynamics into the denoising network, and repeating the reverse process many times gives the quantiles. > > **Read first:** [Denoising Diffusion Probabilistic Models]() · [Recurrent Neural Networks]() Rasul et al., (2021) proposed a probabilistic forecasting model using denoising diffusion models. ## Autoregressive > [!NOTE] > > **Multivariate Forecasting Problem** > > Given an input sequence \\(\\mathbf x\_{t-K: t}\\), we forecast \\(\\mathbf x\_{t+1:t+H}\\). > > See this section for more [Time Series Forecasting Tasks](). > [!NOTE] > > **Notation** > > We use \\(x^0\\) to denote the actual time series. The super script \\({}^{0}\\) will be used to represent the non-diffused values. To apply the [denoising diffusion model]() in a multivariate forecasting problem, we define our forecasting task as the following autoregressive problem, \\\[ q(\\mathbf x^0\_{t\_0:T} \\vert \\mathbf x^0\_{1:t\_0 - 1}) = \\Pi\_{t=t\_0}^T q(\\mathbf x^0\_t \\vert \\mathbf x^0\_{1:t-1}). \\\] ![AR]() At each time step \\(t\\), we build a denoising diffusion model. ## Time Dynamics Note that in the denoising diffusion model, we minimize \\\[ \\operatorname{min}\_\\theta \\mathbb E\_{q(\\mathbf x^0)} \\left\[ -\\log p\_\\theta (\\mathbf x^0) \\right\] \\\] The above loss becomes that of the denoising model for a single time step. Explicitly, \\\[ \\operatorname{min}\_\\theta \\mathbb E\_{q(\\mathbf x^0\_t )} \\left\[ -\\log p\_\\theta (\\mathbf x^0\_t) \\right\]. \\\] Time dynamics can be easily captured by some RNN. To include the time dynamics, we use the RNN state built using the time series data of the previous time step \\(\\mathbf h\_{t-1}\\)[^/time-series-deep-learning/timeseries.deep-learning.timegrad/#Rasul2021] \\\[ \\operatorname{min}\_\\theta \\mathbb E\_{q(\\mathbf x^0\_t )} \\left\[ -\\log p\_\\theta (\\mathbf x^0\_t \\vert \\mathbf h\_{t-1}) \\right\]. \\\] Apart from the usual time dimension \\(t\\), the autoregressive denoising diffusion model has another dimension to optimize: the diffusion step \\(n\\) for each time \\(t\\). The loss for each time step \\(t\\) is[^/time-series-deep-learning/timeseries.deep-learning.timegrad/#Rasul2021] \\\[ \\begin{equation} \\mathcal L\_t = \\mathbb E\_{\\mathbf x^0\_t, \\epsilon, n} \\left\[ \\lVert \\epsilon - \\epsilon\_\\theta ( \\sqrt{\\bar \\alpha\_n} \\mathbf x^0\_t + \\sqrt{1-\\bar \\alpha\_n}\\epsilon, \\mathbf h\_{t-1}, n ) \\rVert^2 \\right\]. \\label{eq:ddpm-loss} \\end{equation} \\\] That being said, we just need to minimize \\(\\mathcal L\_t\\) for each time step \\(t\\). ## Training Algorithm The input data is sliced into fixed length time series \\(\\mathbf x\_t^0\\). Since Eq \\eqref{eq:ddpm-loss} shows that a loss can be calculated for arbitrary \\(n\\) without depending on any previous diffusion steps \\(n-1\\), the training can be done by both random sampling in \\(\\mathbf x\_t^0\\) and \\(n\\). See Rasul et al. (2021)[^/time-series-deep-learning/timeseries.deep-learning.timegrad/#Rasul2021]. ![Training]() ## How to Forecast After training, we obtain the time dynamics encoding \\(\\mathbf h\_T\\), with which the denoising steps can be calculated using the reverse process \\\[ \\mathbf x^{n-1}\_{T+1} = \\frac{1}{\\sqrt{\\alpha\_n}} \\left( \\mathbf x^n\_{T+1} - \\frac{\\beta\_n}{\\sqrt{1 - \\bar\\alpha\_n}} \\epsilon\_\\theta( \\mathbf x^n\_{T+1}, \\mathbf h\_{T}, n ) \\right) + \\sqrt{\\Sigma\_\\theta} \\mathbf z, \\\] where \\(\\mathbf z \\sim \\mathcal N(\\mathbf 0, \\mathbf I)\\). For example, \\\[ \\mathbf x^{0}\_{T+1} = \\frac{1}{\\sqrt{\\alpha\_1}} \\left( \\mathbf x^1\_{T+1} - \\frac{\\beta\_1}{\\sqrt{1 - \\bar\\alpha\_1}} \\epsilon\_\\theta( \\mathbf x^1\_{T+1}, \\mathbf h\_{T}, 1 ) \\right) + \\sqrt{\\Sigma\_\\theta} \\mathbf z. \\\] ## It is Probabilistic The quantiles is calculated by repeating many times for each forecasted time step[^/time-series-deep-learning/timeseries.deep-learning.timegrad/#Rasul2021]. ## Code An implementation of the model can be found in the package [pytorch-ts]() [^/time-series-deep-learning/timeseries.deep-learning.timegrad/#bib-Rasul_PyTorchTS]. --- **Related:** [Time Series Forecasting Tasks]() · [Autoregressive Model]() [^/time-series-deep-learning/timeseries.deep-learning.timegrad/#Rasul2021]: Rasul K, Seward C, Schuster I, Vollgraf R. Autoregressive Denoising Diffusion Models for Multivariate Probabilistic Time Series Forecasting. arXiv \[cs.LG\]. 2021. Available: [http://arxiv.org/abs/2101.12072]() [^/time-series-deep-learning/timeseries.deep-learning.timegrad/#bib-Rasul_PyTorchTS]: Rasul K.. PyTorchTS. [https://github.com/zalandoresearch/pytorch-ts]() # Supplementary # Supplementary Materials In this part, we showcase some supplementary materials such as jupyter notebooks. # Notebooks and Utilities for Tutorials > [!NOTE] > > **In one minute** > > How to run the notebooks of this book: install the Python environment with poetry, create a Jupyter kernel named deep-learning, and use the ts\_dl\_utils package, which holds the helpers shared by the tutorials. All the notebooks are located in the folder `dl/notebooks`. To run these notebooks, we need to set up our Python environment first. We use [poetry]() to manage our Python environment. For the argument of this choice, please refer to [Engineering Tips](). ## Install Requirements and Create Jupyter Kernel First of all, we need to install all the requirements, ``` poetry install ``` or install certain groups using ``` poetry install --with notebook,visualization,torch,darts ``` To create a Jupyter kernel for the notebooks, run ``` poetry run ipython kernel install --user --name=deep-learning ``` and a Jupyter kernel named `deep-learning` will be created. ## Utilities We have a few utilities that we use in our tutorials. Most of them are located in the package `ts_dl_utils` located in the folder `dl/notebooks/ts_dl_utils`. In principle, the notebooks we provided should work without installing this package. The package is also installed in the environment if you run `poetry install` just in case one uses the kernel `deep-learning` created above to run some personal notebooks located in other folders. --- **Related:** [Python]() · [Time Series Forecasting with Deep Learning]() # Box-Cox Transformation ``` from typing import Any, Dict import matplotlib.pyplot as plt import pandas as pd from darts import TimeSeries from darts.dataprocessing.transformers import BoxCox from darts.datasets import AirPassengersDataset from darts.utils import statistics as dus ``` ``` ap_series = AirPassengersDataset().load() _, ax = plt.subplots(figsize=(10, 6.18)) ap_series.plot(label=f"Air Passenger Original Data", ax=ax) ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) boxcox_opt = BoxCox() ap_boxcox_opt_transformed = boxcox_opt.fit_transform(ap_series) ap_boxcox_opt_transformed.plot( label=rf"$\lambda={boxcox_opt._fitted_params[0].item():0.3f}$", ax=ax ) ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) lmbda = 0.01 boxcox = BoxCox(lmbda=lmbda) boxcox_transformed = boxcox.fit_transform(ap_series) boxcox_transformed.plot(label=f"Box-Cox Transformed Data (lambdax={lmbda})", ax=ax) ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) for lmbda in [0.01, 0.1, 0.2]: boxcox_lmbda = BoxCox(lmbda=lmbda) boxcox_lmbda_transformed = boxcox_lmbda.fit_transform(ap_series) boxcox_lmbda_transformed.plot( label=f"Box-Cox Transformed Data (lambda={lmbda})", ax=ax ) ``` ## Plot and Check Variance ``` def var_series(series: TimeSeries, window: int = 36) -> TimeSeries: series_rolling_var = TimeSeries.from_dataframe( series.to_dataframe().rolling(window=window).var().dropna() ) return series_rolling_var def check_stationary(series: TimeSeries) -> Dict[str, Any]: return { "is_stationary": dus.stationarity_tests(series), "kpss": dus.stationarity_test_kpss(series), "adf": dus.stationarity_test_adf(series), } ``` ``` boxcox_grid = [] lmbdas = [0.01, 0.1] rolling_window = 12 for idx, lmbda in enumerate(lmbdas): boxcox_lmbda = BoxCox(lmbda=lmbda) boxcox_lmbda_transformed = boxcox_lmbda.fit_transform(ap_series) var_lmbda_series = var_series(boxcox_lmbda_transformed, window=rolling_window) _, ax = plt.subplots(figsize=(10, 6.18)) var_lmbda_series.plot( label=f"Variance (Rolling Window={rolling_window}) (Box-Cox lambda={lmbda})", ax=ax, ) plt.show() ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) var_ap_series = var_series(ap_series, window=rolling_window) var_ap_series.plot(label=f"Variance (Rolling Window={rolling_window})", ax=ax) ``` # A Dataset Generated by Damped Pendulum In this notebook, we demo a dataset we created to simulate the oscillations of a pendulum. ``` from functools import cached_property from typing import List, Tuple ``` ``` import lightning as L import matplotlib as mpl import matplotlib.animation as animation import matplotlib.pyplot as plt import pandas as pd from torchmetrics import MetricCollection from torchmetrics.regression import ( MeanAbsoluteError, MeanAbsolutePercentageError, MeanSquaredError, SymmetricMeanAbsolutePercentageError, ) from ts_dl_utils.datasets.dataset import DataFrameDataset from ts_dl_utils.datasets.pendulum import Pendulum, PendulumDataModule from ts_dl_utils.evaluation.evaluator import Evaluator from ts_dl_utils.naive_forecasters.last_observation import LastObservationForecaster ``` ## Data We create a dataset that models a damped pendulum. The pendulum is modelled as a damped harmonic oscillator, i.e., \\\[ \\theta(t) = \\theta(0) \\cos(2 \\pi t / p)\\exp(-\\beta t), \\\] where \\(\\theta(t)\\) is the angle of the pendulum at time \\(t\\). The period \\(p\\) is calculated using \\\[ p = 2 \\pi \\sqrt{L / g}, \\\] with \\(L\\) being the length of the pendulum and \\(g\\) being the surface gravity. ``` pen = Pendulum(length=200) ``` ``` df = pd.DataFrame( pen(num_periods=5, num_samples_per_period=100, initial_angle=1, beta=0.01) ) ``` Since the damping constant is very small, the data generated is mostly a sin wave. ``` _, ax = plt.subplots(figsize=(10, 6.18)) df.plot(x="t", y="theta", ax=ax) ``` ### PyTorch and Lighting DataModule ``` history_length = 100 horizon = 5 ``` ``` ds = DataFrameDataset(dataframe=df, history_length=history_length, horizon=horizon) ``` ``` print( f""" There were {len(df)} rows in the dataframe\n We got {len(ds)} data points in the dataset (history length: {history_length}, horizon: {horizon}) """ ) ``` We can create a [LightningDataModule for Lightning](). When training/evaluating using Lightning, we only need to pass this object `pdm` to the training. ``` pdm = PendulumDataModule( history_length=history_length, horizon=horizon, dataframe=df[["theta"]] ) ``` ## Naive Forecasts ``` prediction_truths = [i[1].squeeze() for i in pdm.predict_dataloader()] ``` ``` trainer_naive = L.Trainer(precision="64") lobs_forecaster = LastObservationForecaster(horizon=horizon) lobs_predictions = trainer_naive.predict(model=lobs_forecaster, datamodule=pdm) ``` ``` evaluator = Evaluator(step=0) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator.y_true(dataloader=pdm.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator.y(lobs_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` evaluator.metrics(lobs_predictions, pdm.predict_dataloader()) ``` Naive forecaster works well since we do not have dramatic changes between two time steps. ## Delayed Embedding ``` 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") ```` # Forecast Reconciliation This is a notebook for the section [Hierarchical Time Series Reconciliation](). import re import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns ``` import sympy as sp from darts import TimeSeries from darts.utils.model_selection import train_test_split from darts.utils.statistics import plot_pacf sns.reset_orig() plt.rcParams["figure.figsize"] = (10, 6.18) print(plt.rcParams.get("figure.figsize")) ``` ## Some MinT Matrics This section shows a few examples of the MinT method. We use these examples to interpret how MinT works. ``` m_l = 3 m_w_diag_elements = tuple(sp.Symbol(f"W_{i}") for i in range(1, m_l + 1)) m_s_ident_diag = np.diag([1] * (m_l - 1)).tolist() m_w_diag_elements, m_s_ident_diag ``` ``` class MinTMatrices: def __init__(self, levels: int): self.levels = levels @property def s(self): s_ident_diag = np.diag([1] * (self.levels - 1)).tolist() return sp.Matrix( [ [1] * (self.levels - 1), ] + s_ident_diag ) @property def w_diag_elements(self): return tuple(sp.Symbol(f"W_{i}") for i in range(1, self.levels + 1)) @property def w(self): return sp.Matrix(np.diag(self.w_diag_elements).tolist()) @property def p_left(self): return sp.Inverse(sp.MatMul(sp.Transpose(self.s), sp.Inverse(self.w), self.s)) @property def p_right(self): return sp.MatMul(sp.Transpose(self.s), sp.Inverse(self.w)) @property def p(self): return sp.MatMul(self.p_left, self.p_right) @property def s_p(self): return sp.MatMul(self.s, self.p) @property def s_p_numerical(self): return sp.lambdify(self.w_diag_elements, self.s_p) def visualize_s_p(self, w_elements, ax): sns.heatmap(self.s_p_numerical(*w_elements), annot=True, cbar=False, ax=ax) ax.grid(False) ax.set(xticklabels=[], yticklabels=[]) ax.tick_params(bottom=False, left=False) ax.set_title(f"$W_{{diag}} = {w_elements}$") return ax ``` ``` mtm_3 = MinTMatrices(levels=3) ``` ``` print( f"s: {sp.latex(mtm_3.s)}\n" f"p: {sp.latex(mtm_3.p.as_explicit())}\n" f"s_p: {sp.latex(mtm_3.s_p.as_explicit())}\n" ) ``` ``` mtm_3.s ``` ``` mtm_3.p ``` ``` mtm_3.s_p.as_explicit() ``` ``` mtm_3.w_diag_elements ``` ``` mtm_3.s_p_numerical(1, 2, 3) ``` ``` w_elements = [(1, 1, 1), (2, 1, 1)] fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(4 * 2, 4)) for idx, w in enumerate(w_elements): mtm_3.visualize_s_p(w, axes[idx]) fig.show() ``` ``` mtm_4 = MinTMatrices(levels=4) print( f"s: {sp.latex(mtm_4.s)}\n" f"p: {sp.latex(mtm_4.p.as_explicit())}\n" f"s_p: {sp.latex(mtm_4.s_p.as_explicit())}\n" ) w_elements = [(1, 1, 1, 1), (3, 1, 1, 1)] fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(4 * 2, 4)) for idx, w in enumerate(w_elements): mtm_4.visualize_s_p(w, axes[idx]) fig.show() ``` ``` mtm_5 = MinTMatrices(levels=5) print( f"s: {sp.latex(mtm_5.s)}\n" f"p: {sp.latex(mtm_5.p.as_explicit())}\n" f"s_p: {sp.latex(mtm_5.s_p.as_explicit())}\n" ) w_elements = [(1, 1, 1, 1, 1), (4, 1, 1, 1, 1)] fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(4 * 2, 4)) for idx, w in enumerate(w_elements): mtm_5.visualize_s_p(w, axes[idx]) fig.show() ``` ## Load data We load a small sample of the M5 dataset. ``` df = pd.read_csv( "https://github.com/datumorphism/dataset-m5-simplified/raw/main/dataset/m5_store_sales.csv", index_col="date", ) ``` ``` df["Total"] = df[["CA", "TX", "WI"]].sum(axis="columns") ``` ``` df.index = pd.to_datetime(df.index) ``` ``` re_simple_col = re.compile(r"'(\w{2}_\d{1})'") df.rename( columns={ c: re_simple_col.findall(c)[0] for c in df.columns if re_simple_col.findall(c) }, inplace=True, ) ``` ``` df.head() ``` ``` value_columns = df.columns.tolist() value_columns ``` ``` hierarchy = { "CA_1": ["CA"], "CA_2": ["CA"], "CA_3": ["CA"], "CA_4": ["CA"], "TX_1": ["TX"], "TX_2": ["TX"], "TX_3": ["TX"], "WI_1": ["WI"], "WI_2": ["WI"], "WI_3": ["WI"], "CA": ["Total"], "TX": ["Total"], "WI": ["Total"], } ``` ``` ts = TimeSeries.from_dataframe( df, value_cols=value_columns, freq="d", hierarchy=hierarchy ) ``` ``` ts ``` ## Visualize and Validate the Data ``` ts_sample = ts.drop_after(ts.time_index[20]) ``` ``` ts_sample[["CA", "CA_1", "CA_2", "CA_3", "CA_4"]].plot() ``` ``` ts_sample["CA"].plot(label="CA") (ts_sample["CA_1"] + ts_sample["CA_2"] + ts_sample["CA_3"] + ts_sample["CA_4"]).plot( label="CA_1 + CA_2 + CA_3 + CA_4", linestyle="--", color="r" ) ``` ## Forecasts We split the dataset into two time series, `ts_train` and `ts_test`. We will hold out `ts_test` from training. ``` ts.time_index ``` ``` ts_train, ts_test = ts.split_after(ts.time_index[1863]) ts_train["Total"].plot(label="Train") ts_test["Total"].plot(label="Test") ``` We check the partial autocorrelation function to choose some parameters for our models. ``` plot_pacf(ts_train["Total"]) ``` ``` from darts.models import LightGBMModel ``` ``` model_params = {"lags": 14, "linear_tree": True, "output_chunk_length": 10} model = LightGBMModel(**model_params) ``` ``` model.fit(ts_train) ``` ``` model.save("lightgbm.pkl") ``` ``` ts_pred = model.predict(n=len(ts_test)) ``` We check the performance visually for CA. The patterns looks similar but the scales are a bit off. ``` ca_columns = ["CA", "CA_1", "CA_2", "CA_3", "CA_4"] ts_test[ca_columns].plot() ts_pred[ca_columns].plot(linestyle="--") ``` ``` vis_columns = ["CA_4"] ts_test[vis_columns].plot() ts_pred[vis_columns].plot(linestyle="--") ``` The forecasts are not coherent. ``` ts_pred["Total"].plot(label="CA") (ts_pred["CA"] + ts_pred["TX"] + ts_pred["WI"]).plot( label="CA + TX + WI", linestyle="--", color="r" ) ``` ``` ts_pred["CA"].plot(label="CA") (ts_pred["CA_1"] + ts_pred["CA_2"] + ts_pred["CA_3"] + ts_pred["CA_4"]).plot( label="CA_1 + CA_2 + CA_3 + CA_4", linestyle="--", color="r" ) ``` ## Reconciliation ``` from darts.dataprocessing.transformers import MinTReconciliator ``` ``` reconciliator = MinTReconciliator(method="wls_val") ``` ``` reconciliator.fit(ts_train) ts_pred_recon = reconciliator.transform(ts_pred) ``` ``` ts_pred_recon["Total"].plot(label="CA") (ts_pred_recon["CA"] + ts_pred_recon["TX"] + ts_pred_recon["WI"]).plot( label="CA + TX + WI", linestyle="--", color="r" ) ``` ``` ts_pred_recon["CA"].plot(label="CA") ( ts_pred_recon["CA_1"] + ts_pred_recon["CA_2"] + ts_pred_recon["CA_3"] + ts_pred_recon["CA_4"] ).plot(label="CA_1 + CA_2 + CA_3 + CA_4", linestyle="--", color="r") ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) ca_columns = ["CA", "CA_1", "CA_2", "CA_3", "CA_4"] ts_test[ca_columns].plot(ax=ax) ts_pred_recon[ca_columns].plot(linestyle="--", ax=ax) ``` ### What Changed ``` ts_pred_recon_shift = ts_pred_recon - ts_pred ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) ts_pred_recon_shift[["Total", "CA", "WI", "TX"]].plot(ax=ax) ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) ts_pred_recon_shift[ca_columns + ["Total"]].plot(ax=ax) ``` To see how the predictions are shifted during reconciliation, we plot out the changes from reconciliation as box plots. ``` ts_pred_recon_shift[ca_columns + ["Total"]].to_dataframe().plot.box() ``` ``` ts_pred_recon_shift["CA"].to_dataframe().plot.box() ``` ``` ts_pred_recon_shift[["Total", "CA", "TX", "WI"]].to_dataframe().plot.box( title="Box Plot for Reconciled - Original Prediction" ) ``` ``` ts_pred_recon_shift[["Total", "CA", "TX", "WI"]].to_dataframe() ``` ``` max(ts_pred.values().max(), ts_pred_recon.values().max()) ``` ``` chart_component = "Total" chart_max = max( ts_pred[chart_component].values().max(), ts_pred_recon[chart_component].values().max(), ) chart_min = min( ts_pred[chart_component].values().min(), ts_pred_recon[chart_component].values().min(), ) fig, ax = plt.subplots(figsize=(10, 10)) ax.scatter(ts_pred[chart_component].values(), ts_pred_recon[chart_component].values()) ax.plot(np.linspace(chart_min, chart_max), np.linspace(chart_min, chart_max)) ``` ``` chart_component = "CA" chart_max = max( ts_pred[chart_component].values().max(), ts_pred_recon[chart_component].values().max(), ) chart_min = min( ts_pred[chart_component].values().min(), ts_pred_recon[chart_component].values().min(), ) fig, ax = plt.subplots(figsize=(10, 10)) ax.scatter(ts_pred[chart_component].values(), ts_pred_recon[chart_component].values()) ax.plot(np.linspace(chart_min, chart_max), np.linspace(chart_min, chart_max)) ``` ### Can Reconciliations Adjust Bias? We create some artificial bias by shifting one of the series down and then perform reconciliations. This assumes that the reconciliation already learned about the general patterns on different levels, since we only manually shift the predictions only. The training is not touched. ``` reconciliator_pred_bias = MinTReconciliator(method="wls_val") ``` ``` df_pred_biased = ts_pred.to_dataframe().copy() df_pred_biased["CA_1"] = df_pred_biased["CA_1"] * 0.5 ts_pred_biased = TimeSeries.from_dataframe(df_pred_biased, hierarchy=ts_pred.hierarchy) ts_pred["CA_1"].plot(label="Original Prediction for CA_1") ts_pred_biased["CA_1"].plot(label="Manually Shifted Prediction for CA_1") ``` ``` reconciliator_pred_bias.fit(ts_pred_biased) ts_pred_biased_recon = reconciliator_pred_bias.transform(ts_pred_biased) ``` ``` ts_pred["CA_1"].plot(label="Original Prediction for CA_1") ts_pred_biased["CA_1"].plot(label="Manually Shifted Prediction for CA_1") ts_pred_biased_recon["CA_1"].plot(label="Reconciled Shifted Prediction for CA_1") ``` ``` ts_pred_biased_recon["CA"].plot(label="CA") ( ts_pred_biased_recon["CA_1"] + ts_pred_biased_recon["CA_2"] + ts_pred_biased_recon["CA_3"] + ts_pred_biased_recon["CA_4"] ).plot(label="CA_1 + CA_2 + CA_3 + CA_4", linestyle="--", color="r") ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) ca_columns = ["CA", "CA_1", "CA_2", "CA_3", "CA_4"] ts_test[ca_columns].plot(ax=ax) ts_pred_biased_recon[ca_columns].plot(linestyle="--", ax=ax) ``` ``` reconciliator_mint_cov = MinTReconciliator(method="mint_cov") reconciliator_mint_cov.fit(ts_pred - ts_test) ts_test[ca_columns].plot() reconciliator_mint_cov.transform(ts_pred)[ca_columns].plot(linestyle="--") ``` # Tree Basics ``` import json from typing import List, Literal, Union import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn import tree sns.set() ``` ## Generate Data We generate some artificial dataset about whether to go to the office or work from home. We will use three features, `["health", "weather", "holiday"]`. And people are only going to the office, iff - health=1: not sick, - weather=1: good weather, - holiday=0: not holiday. We use `1` to indicate that we go to the office. ```` class WFHData: """ Generate a dataset about wheter to go to the office. Go to the office, if and only if - I am healthy, - the weather is good, - not holiday. Represented in the feature values, this condition is `[1,1,0]`. However, we also randomize the target value based on `randomize_prob`: - `randomize_prob=0`: keep perfect data, no randomization - `randomize_prob=1`: use the wrong target value. The rules are inverted. ```python wfh = WFHData(length=10) ``` :param length: the number of data points to generate. :param randomize_prob: the probability of randomizing the target values. `0` indicates that we keep the perfect target value based on rules. :param seed: random generator seed. """ def __init__(self, length: int, randomize_prob: int = 0, seed: int = 42): self.randomize_prob = randomize_prob self.length = length self.rng = np.random.default_rng(seed) self.x = self._generate_feature_values() self.y = self._generate_target_values() @property def feature_names(self) -> List[str]: return ["health", "weather", "holiday"] @property def target_names(self) -> List[str]: return ["go_to_office"] @property def feature_dataframe(self) -> pd.DataFrame: return pd.DataFrame(self.x, columns=self.feature_names) @property def target_dataframe(self) -> pd.DataFrame: return pd.DataFrame(self.y, columns=self.target_names) def _generate_feature_values(self) -> List[List[Literal[0, 1]]]: """Generate the values for the three features The values can only be either `0` or `1`. """ return self.rng.choice([0, 1], (self.length, len(self.feature_names))).tolist() def _perfect_target(self) -> List[Literal[0, 1]]: """Create target value based on rules: Go to the office, if and only if - I am healthy, - the weather is good, - not holiday. Represented in the feature values, this condition is `[1,1,0]`. """ target = [] for i in self.x: if i == [1, 1, 0]: target.append(1) else: target.append(0) return target @staticmethod def _randomize_target(y, rng, probability: float) -> Literal[0, 1]: """Randomly choose from the current value `y` and its alternative. For example, if current value of `y=0`, its alternative is `1`. We will randomly choose from `0` and `1` based on the specified probability. If `probability=0`, we return the current value, i.e., `0`. If `probability=0`, we return the alternative value, i.e., `1`. Otherwise, it is randomly selected based on the probability. """ alternative_y = 1 if y == 0 else 0 return rng.choice( [y, alternative_y], 1, p=(1 - probability, probability) ).item() def _generate_target_values(self) -> List[Literal[0, 1]]: """Generate the target values""" y = self._perfect_target() y = [self._randomize_target(i, self.rng, self.randomize_prob) for i in y] return y ```` ``` wfh_demo = WFHData(length=10) ``` ``` wfh_demo.feature_dataframe ``` ``` wfh_demo.target_dataframe ``` ## Decision Tree on Perfect Data ``` wfh_pure = WFHData(length=100, randomize_prob=0) ``` ``` clf_pure = tree.DecisionTreeClassifier() clf_pure.fit(wfh_pure.feature_dataframe, wfh_pure.target_dataframe) ``` ``` fig, ax = plt.subplots(figsize=(15, 15)) tree.plot_tree(clf_pure, feature_names=wfh_pure.feature_names, ax=ax) ax.set_title("Tree Trained on Perfect Data") ``` ## Impure Data ``` wfh_impure = WFHData(length=100, randomize_prob=0.1) ``` ``` clf_impure = tree.DecisionTreeClassifier( max_depth=20, min_samples_leaf=1, min_samples_split=0.0001 ) clf_impure.fit(wfh_impure.feature_dataframe, wfh_impure.target_dataframe) ``` ``` fig, ax = plt.subplots(figsize=(15, 10)) tree.plot_tree(clf_impure, feature_names=wfh_impure.feature_names, ax=ax) ax.set_title("Tree Trained on Imperfect Data") ``` ## Understand Gini Impurity ### Gini Impurity for 2 possible classes ``` def gini_2(p1: float, p2: float) -> Union[None, float]: """Compute the Gini impurity for the two input values.""" if p1 + p2 <= 1: return p1 * (1 - p1) + p2 * (1 - p2) else: return None ``` ``` gini_2_test_p1 = np.linspace(0, 1, 1001) gini_2_test_p2 = np.linspace(0, 1, 1001) ``` ``` gini_2_test_impurity = [ [gini_2(p1, p2) for p1 in gini_2_test_p1] for p2 in gini_2_test_p2 ] ``` ``` df_gini_2_test = pd.DataFrame( gini_2_test_impurity, index=[f"{i:0.2f}" for i in gini_2_test_p2], columns=[f"{i:0.2f}" for i in gini_2_test_p1], ) ``` ``` fig, ax = plt.subplots(figsize=(12, 10)) sns.heatmap(df_gini_2_test.loc[::-1,], ax=ax) ax.set_xlabel("$p_1$") ax.set_ylabel("$p_2$") ax.set_title("Gini Impurity for Data with 2 Possible Values") ``` ### Gini Impurity for 3 possible classes ``` def gini_3(p1: float, p2: float) -> Union[None, float]: """Computes the gini impurity for three potential classes""" if p1 + p2 <= 1: return p1 * (1 - p1) + p2 * (1 - p2) + (1 - p1 - p2) * (p1 + p2) else: return None ``` ``` gini_3_test_p1 = np.linspace(0, 1, 1001) gini_3_test_p2 = np.linspace(0, 1, 1001) gini_3_test_impurity = [ [gini_3(p1, p2) for p1 in gini_3_test_p1] for p2 in gini_3_test_p2 ] df_gini_3_test = pd.DataFrame( gini_3_test_impurity, index=[f"{i:0.2f}" for i in gini_3_test_p2], columns=[f"{i:0.2f}" for i in gini_3_test_p1], ) ``` ``` fig, ax = plt.subplots(figsize=(12, 10)) sns.heatmap(df_gini_3_test.loc[::-1,], ax=ax) ax.set_xlabel("$p_1$") ax.set_ylabel("$p_2$") ax.set_title("Gini Impurity for Data with 3 Possible Values") ``` # Random Forest Playground Outline 1. Generate data of specific functions 2. Fit the functions using ensemble methods 3. Analyze the trees ``` import matplotlib as mpl import matplotlib.pyplot as plt import pandas as pd import sklearn.tree as _tree from sklearn.ensemble import RandomForestRegressor from sklearn.feature_selection import ( SelectFromModel, SelectKBest, chi2, mutual_info_regression, ) from sklearn.model_selection import ( GridSearchCV, RandomizedSearchCV, cross_val_score, learning_curve, train_test_split, validation_curve, ) from sklearn.pipeline import Pipeline from sklearn.tree import DecisionTreeRegressor ``` ``` mpl.rcParams["axes.unicode_minus"] = False from random import random ``` ``` import numpy as np import seaborn as sns from joblib import dump, load ``` ## Model ### Components ``` # Number of trees in random forest n_estimators = [int(x) for x in np.linspace(1000, 4000, 11)] # Number of features to consider at every split max_features = ["auto", "sqrt"] # Maximum number of levels in tree max_depth = [int(x) for x in range(10, 30, 2)] max_depth.append(None) # Minimum number of samples required to split a node min_samples_split = [0.001, 0.01, 0.02, 0.05, 0.1, 0.2] # Minimum number of samples required at each leaf node min_samples_leaf = [10, 20, 30, 40, 50] # Method of selecting samples for training each tree bootstrap = [True, False] rf_random_grid = { "rf__n_estimators": n_estimators, # "rf__max_features": max_features, "rf__max_depth": max_depth, "rf__min_samples_split": min_samples_split, "rf__min_samples_leaf": min_samples_leaf, "rf__bootstrap": bootstrap, } rf = RandomForestRegressor(random_state=42, oob_score=True) ########## pipeline_steps = [ ("rf", rf), ] pipeline = Pipeline(pipeline_steps) ``` ``` def pred_true_comparison_plot(dataframe, ax, pred_sample=100): sns.scatterplot( dataframe, x="x", y="y", ax=ax, label="y", marker=".", ec="face", s=5 ) sns.scatterplot( dataframe.sample(100), x="x", y="y_pred", ax=ax, label="y_pred", marker="+", s=100, linewidth=2, ) return ax def predictions_each_estimators(x, rf_model): preds = [] for i in x: i_preds = [] for est in rf_model.best_estimator_["rf"].estimators_: i_preds.append(est.predict([[i]]).tolist()) i_preds = sum(i_preds, []) preds.append(i_preds) return {"x": pd.DataFrame(x, columns=["x"]), "preds": pd.DataFrame(preds)} ``` ### Data without Noise ``` X_sin = [6 * random() for i in range(10000)] y_sin = np.sin(X_sin) X_sin_test = [6 * random() for i in range(10000)] y_sin_test = np.sin(X_sin_test) ``` ``` df_sin = pd.DataFrame( { "x": X_sin, "y": y_sin, } ) ``` ``` model = RandomizedSearchCV( pipeline, cv=10, param_distributions=rf_random_grid, verbose=3, n_jobs=-1 ) ``` ``` model.fit(df_sin[["x"]], df_sin["y"].values.ravel()) ``` ``` sin_score = model.score(df_sin[["x"]], df_sin["y"].values.ravel()) ``` ``` model.best_params_ ``` ``` # dump(model, "reports/rf_sin.joblib") ``` ``` fig, ax = plt.subplots(figsize=(10 * 10, 4 * 10)) _tree.plot_tree(model.best_estimator_["rf"].estimators_[0], fontsize=7) ``` Plot out the result ``` df_sin["y_pred"] = model.predict(df_sin[["x"]]) ``` ``` df_sin ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) pred_true_comparison_plot(df_sin, ax) ax.set_title(f"Random Forest on Sin Data; $R^2$ Score: {sin_score:0.2f}") plt.legend() ``` Plot out the boxplots of each data point ``` est_sample_skip = 100 ``` ``` sin_est_pred = predictions_each_estimators(sorted(X_sin_test)[::est_sample_skip], model) ``` ``` df_sin_est_quantiles = pd.merge( sin_est_pred["x"], sin_est_pred["preds"].quantile(q=[0.75, 0.25], axis=1).T, how="left", left_index=True, right_index=True, ) df_sin_est_quantiles["boxsize"] = ( df_sin_est_quantiles[0.75] - df_sin_est_quantiles[0.25] ) ``` ``` fig, ax = plt.subplots(figsize=(10, 1.5 * 6.18)) fig_skip = 5 ax.violinplot( sin_est_pred["preds"].values.tolist()[::fig_skip], positions=sin_est_pred["x"].x.tolist()[::fig_skip], ) sns.lineplot(df_sin, x="x", y="y", ax=ax, label="y") plt.xticks([]) # ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(range(10))) # ax.set_xticklabels([f"{i:0.2f}" for i in sin_est_pred["x"].x]) ax.set_title( "Violin Plot for All Predictions of Each Tree in a Random Forest on Some Sin Data Points" ) ``` ``` fig, ax = plt.subplots(figsize=(10, 2 * 6.18)) fig_skip = 5 ax.boxplot( sin_est_pred["preds"].values.tolist()[::fig_skip], positions=sin_est_pred["x"].x.tolist()[::fig_skip], ) sns.lineplot(df_sin, x="x", y="y", ax=ax, label="y") ax.set_xticklabels([f"{i:0.2f}" for i in sin_est_pred["x"].x[::fig_skip]]) ax.set_title("Box Plot for Tree Predictions on Random Forest on Sin Data") ``` ``` df_sin_est_quantiles ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.barplot(df_sin_est_quantiles, x="x", y="boxsize") ax.set_xticklabels([f"{i:0.2f}" for i in sin_est_pred["x"].x]) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.histplot(df_sin_est_quantiles.boxsize, ax=ax) ax.set_yscale("log") ax.set_xscale("log") ``` ### Data with Noise ``` X_sin_noise = np.array([6 * random() for i in range(10000)]) y_sin_noise = np.array([i + 0.1 * (random() - 0.5) for i in np.sin(X_sin_noise)]) df_sin_noise = pd.DataFrame({"x": X_sin_noise, "y": y_sin_noise}) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.lineplot(df_sin_noise, x="x", y="y", ax=ax, label="y") ``` ``` model_noise = RandomizedSearchCV( pipeline, cv=10, param_distributions=rf_random_grid, verbose=3, n_jobs=-1 ) ``` ``` model_noise.fit(df_sin_noise[["x"]], df_sin_noise["y"].values.ravel()) ``` ``` sin_noise_score = model_noise.score(df_sin_noise[["x"]], df_sin_noise["y"]) ``` ``` model_noise.best_params_ ``` ``` # dump(model_noise, "reports/rf_sin_noise.joblib") ``` ``` fig, ax = plt.subplots(figsize=(9 * 10, 4 * 10)) _tree.plot_tree(model_noise.best_estimator_["rf"].estimators_[0], fontsize=7) ``` ``` df_sin_noise["y_pred"] = model_noise.predict(df_sin_noise[["x"]]) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) pred_true_comparison_plot(df_sin_noise, ax) ax.set_title( f"Random Forest on Sin Data with Noise; Test $R^2$ Score: {sin_noise_score:0.2f}" ) plt.legend() ``` ``` sin_noise_est_pred = predictions_each_estimators( sorted(X_sin_noise)[::100], model_noise ) ``` ``` df_sin_noise_est_quantiles = pd.merge( sin_noise_est_pred["x"], sin_noise_est_pred["preds"].quantile(q=[0.75, 0.25], axis=1).T, how="left", left_index=True, right_index=True, ) df_sin_noise_est_quantiles["boxsize"] = ( df_sin_noise_est_quantiles[0.75] - df_sin_noise_est_quantiles[0.25] ) ``` ``` fig, ax = plt.subplots(figsize=(10, 1.5 * 6.18)) fig_skip = 5 ax.violinplot( sin_noise_est_pred["preds"].values.tolist()[::fig_skip], positions=sin_noise_est_pred["x"].x.tolist()[::fig_skip], ) sns.scatterplot( df_sin_noise, x="x", y="y", ax=ax, label="y", marker=".", ec="face", s=1 ) plt.xticks([]) ax.set_title( "Violin Plot for All Predictions of Each Tree in a Random Forest on Some Sin Data Points" ) ``` ``` fig, ax = plt.subplots(figsize=(10, 2 * 6.18)) fig_skip = 5 ax.boxplot( sin_noise_est_pred["preds"].values.tolist()[::fig_skip], positions=sin_noise_est_pred["x"].x.tolist()[::fig_skip], ) sns.scatterplot( df_sin_noise, x="x", y="y", ax=ax, label="y", marker=".", ec="face", s=1 ) ax.set_xticklabels([f"{i:0.2f}" for i in sin_noise_est_pred["x"].x[::fig_skip]]) ax.set_title("Box Plot for Tree Predictions on Random Forest on Sin Data") ``` ``` df_sin_noise_est_quantiles["model"] = "with_noise" df_sin_est_quantiles["model"] = "no_noise" df_quantiles = pd.concat( [ df_sin_est_quantiles[["model", "boxsize"]], df_sin_noise_est_quantiles[["model", "boxsize"]], ] ) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.boxplot(df_quantiles, x="boxsize", y="model", ax=ax) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.histplot( df_sin_noise_est_quantiles.boxsize, # bins=20, ax=ax, kde=True, label="with Noise", stat="probability", binwidth=0.002, binrange=(0, 0.07), ) sns.histplot( df_sin_est_quantiles.boxsize, # bins=20, ax=ax, kde=True, label="without Noise", stat="probability", binwidth=0.002, binrange=(0, 0.07), ) plt.legend() ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.kdeplot( df_sin_noise_est_quantiles.boxsize, # bins=20, ax=ax, # hist=False, label="with Noise", ) sns.kdeplot( df_sin_est_quantiles.boxsize, # bins=20, ax=ax, # hist=True, label="without Noise", ) plt.legend() ``` ## Generalization Error \\\[ P\_{err} \\leq \\frac{\\bar \\rho (1-s^2) }{s^2}. \\\] ``` def generalization_error(rhob, s): res = rhob * (1 - s**2) / s**2 if res > 1: res = 1 return res ``` ``` generalization_error(0.2, 0.8) ``` ``` pe_data = [ [generalization_error(rhob, s) for s in np.linspace(0.01, 0.1, 10)] for rhob in np.linspace(0.01, 0.1, 10) ] pe_data_s_label = [s for s in np.linspace(0.01, 0.1, 10)] pe_data_rhob_label = [rhob for rhob in np.linspace(0.01, 0.1, 10)] fig, ax = plt.subplots(figsize=(10, 10)) sns.heatmap(pe_data, center=0, ax=ax) ax.set_xlabel("s") ax.set_ylabel("correlation") ax.set_xticklabels([f"{i:0.2f}" for i in pe_data_s_label]) ax.set_yticklabels([f"{i:0.2f}" for i in pe_data_rhob_label]) ``` ``` temp_space = np.linspace(0.1, 1, 91) pe_data = [[generalization_error(rhob, s) for s in temp_space] for rhob in temp_space] pe_data_s_label = [s for s in temp_space] pe_data_rhob_label = [rhob for rhob in temp_space] fig, ax = plt.subplots(figsize=(12, 10)) sns.heatmap(pe_data, center=0, ax=ax) ax.set_xlabel("s") ax.set_ylabel("correlation") ax.set_xticklabels([f"{i:0.2f}" for i in (ax.get_xticks() + 0.1) / 100]) ax.set_yticklabels([f"{i:0.2f}" for i in (ax.get_yticks() + 0.1) / 100]) for label in ax.xaxis.get_ticklabels()[::2]: label.set_visible(False) for label in ax.yaxis.get_ticklabels()[::2]: label.set_visible(False) ax.set_title("Upper Limit of Generalization Error of Random Forest") ``` # Forecasting with Trees Using Darts In this notebook, we explore some basic ideas of how to forecast using trees with the help of the package called [Darts](). ``` from typing import Callable, Dict, List ``` ``` import darts.utils as du import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from darts import TimeSeries, metrics from darts.dataprocessing.transformers import BoxCox from darts.datasets import AirPassengersDataset from darts.models import LightGBMModel, NaiveDrift, RandomForest from sklearn.linear_model import LinearRegression ``` ## Following the Darts Official Tutorial Darts provides a [tutorial here]() to help the users get started. Here we replicate some of them to provide a minimal working example for tree-based models. ``` darts_air_passenger_series = AirPassengersDataset().load() darts_air_passenger_series.plot() ``` ``` darts_air_passenger_series ``` From the outputs, we see that the time series dataset contains montly data for 144 months. ``` train_series_length = 120 test_series_length = len(darts_air_passenger_series) - train_series_length train_series_length, test_series_length ``` ``` ( darts_air_passenger_train, darts_air_passenger_test, ) = darts_air_passenger_series.split_before(train_series_length) darts_air_passenger_train.plot(label="Training Data") darts_air_passenger_test.plot(label="Test Data") ``` ### First Random Forest Model ``` ap_horizon = len(darts_air_passenger_test) ap_rf_params = dict(lags=52, output_chunk_length=ap_horizon) ``` ``` rf_ap = RandomForest(**ap_rf_params) ``` ``` rf_ap.fit(darts_air_passenger_train) ``` To observe how the model performs on the training data, we predict a time range that has already seen by the model during training. ``` darts_air_passenger_train.drop_after( darts_air_passenger_train.time_index[-ap_horizon] ).plot(label="Prediction Input") darts_air_passenger_train.drop_before( darts_air_passenger_train.time_index[-ap_horizon] ).plot(label="True Values") rf_ap.predict( n=ap_horizon, series=darts_air_passenger_train.drop_after( darts_air_passenger_train.time_index[-ap_horizon] ), ).plot(label="Predictions (In-sample)", linestyle="--") ``` The predictions looks amazing. However, we all know that tree-based models are not good at out of sample extrapolations. In our case, the trend of the time series may cause some problems. To test this idea, we plot out the predictions for the test date range. ``` darts_air_passenger_train.plot(label="Train") darts_air_passenger_test.plot(label="Test") pred_rf_ap = rf_ap.predict(n=ap_horizon) pred_rf_ap.plot(label="Prediction", linestyle="--") ``` ### Detrending Helps We train the same model but with the detrended dataset, and reconstruct the predictions using the trend. This method demonstrate that detrended data is easier for random forest. ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.histplot( darts_air_passenger_train.to_dataframe(), x="#Passengers", kde=True, binwidth=50, binrange=(0, 700), label="Training Distribution", stat="probability", ax=ax, ) sns.histplot( darts_air_passenger_test.to_dataframe(), x="#Passengers", kde=True, binwidth=50, binrange=(0, 700), label="Test Distribution", stat="probability", color="r", ax=ax, ) ax.set_xlabel("# Passengers") plt.legend() ``` ``` ( darts_air_passenger_trend, darts_air_passenger_seasonal, ) = du.statistics.extract_trend_and_seasonality( darts_air_passenger_series, # model=du.utils.ModelMode.ADDITIVE, # method="STL" ) darts_air_passenger_series.plot() darts_air_passenger_trend.plot() (darts_air_passenger_trend * darts_air_passenger_seasonal).plot() ``` ``` ( darts_air_passenger_seasonal_train, darts_air_passenger_seasonal_test, ) = darts_air_passenger_seasonal.split_before(120) darts_air_passenger_seasonal_train.plot(label="Seasonal Component Train") darts_air_passenger_seasonal_test.plot(label="Seasonal Component Test") ``` ``` darts_air_passenger_seasonal_test.to_dataframe() ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.histplot( darts_air_passenger_seasonal_train.to_dataframe(), x="0", kde=True, binwidth=0.1, binrange=(0.7, 1.3), label="Training Distribution", stat="probability", # fill=False, ax=ax, ) sns.histplot( darts_air_passenger_seasonal_test.to_dataframe(), x="0", kde=True, binwidth=0.1, binrange=(0.7, 1.3), label="Test Distribution", stat="probability", color="r", # fill=False, ax=ax, ) ax.set_xlabel("# Passengers") plt.legend() ``` ``` rf_ap_seasonal = RandomForest(**ap_rf_params) ``` ``` rf_ap_seasonal.fit(darts_air_passenger_seasonal_train) ``` ``` darts_air_passenger_train.plot(label="Train") darts_air_passenger_test.plot(label="Test") pred_rf_ap_seasonal = rf_ap_seasonal.predict( n=ap_horizon ) * darts_air_passenger_trend.drop_before(119) pred_rf_ap_seasonal.plot(label="Trend * Predicted Seasonal Component", linestyle="--") ``` This indiates that the performance of trees on out of sample predictions if we only predict on the cycle part of the series. In a real world case, however, we have to predict the trend accurately for this to work. To better reconstruct the trend, there are also tricks like [Box-Cox transformations](). ## Train, Test, and Metrics It is not easy to determine a best model simply looking at the charts. We need some metrics. ``` air_passenger_boxcox = BoxCox() darts_air_passenger_train_boxcox = air_passenger_boxcox.fit_transform( darts_air_passenger_train ) darts_air_passenger_test_boxcox = air_passenger_boxcox.transform( darts_air_passenger_test ) darts_air_passenger_train_boxcox.plot(label="Train (Box-Cox Transformed)") darts_air_passenger_test_boxcox.plot(label="Test (Box-Cox Transformed)") ``` ``` def linear_trend_model(series: TimeSeries) -> LinearRegression: """Fit a linear trend of the series. This can be used to find the linear model using training data. :param series: training timeseries """ positional_index_start = 0 series_trend, _ = du.statistics.extract_trend_and_seasonality(series) model = LinearRegression() length = len(series_trend) model.fit( np.arange(positional_index_start, positional_index_start + length).reshape( length, 1 ), series_trend.values(), ) return model def find_linear_trend( series: TimeSeries, model, positional_index_start: int = 0 ) -> TimeSeries: """Using the fitted linear model to find or extrapolate the linear trend. :param series: train or test timeseries :param model: LinearRegression model that has `predict` method :param positional_index_start: the position of the first value in the original timeseries. """ length = len(series) linear_preds = model.predict( np.arange(positional_index_start, positional_index_start + length).reshape( length, 1 ) ).squeeze() dataframe = pd.DataFrame( {"date": series.time_index, "# Passengers": linear_preds} ).set_index("date") return TimeSeries.from_dataframe(dataframe) ``` ``` ap_trend_lm = linear_trend_model(darts_air_passenger_train_boxcox) ap_trend_lm ``` ``` ap_trend_linear_train = find_linear_trend( model=ap_trend_lm, series=darts_air_passenger_train_boxcox ) ap_trend_linear_test = find_linear_trend( model=ap_trend_lm, series=darts_air_passenger_test_boxcox, positional_index_start=train_history_length, ) darts_air_passenger_train_boxcox.plot(label="Train") ap_trend_linear_train.plot(label="Linear Trend (Train)") darts_air_passenger_test_boxcox.plot(label="Test") ap_trend_linear_test.plot(label="Linear Trend (Test)") ``` ``` darts_air_passenger_train_transformed = ( darts_air_passenger_train_boxcox - ap_trend_linear_train ) darts_air_passenger_train_transformed.plot() ``` ``` rf_bc_lt = RandomForest(**ap_rf_params) rf_bc_lt.fit(darts_air_passenger_train_transformed) ``` ``` darts_air_passenger_train.plot() darts_air_passenger_test.plot() pred_rf_bc_lt = boxcox.inverse_transform( rf_bc_lt.predict(n=ap_horizon) + ap_trend_linear_test ) pred_rf_bc_lt.plot(label="Box-Cox + Linear Detrend Predictions", linestyle="--") ``` ### Metrics ``` darts_air_passenger_test.plot(label="Test") pred_rf_ap.plot(label="Simple RF", linestyle="--") pred_rf_ap_seasonal.plot(label="RF on Global Detrended Data (Cheating)", linestyle="--") pred_rf_bc_lt.plot(label="Box-Cox + Linear Detrend", linestyle="--") ``` ``` benchmark_metrics = [ metrics.mae, metrics.mape, metrics.mse, metrics.rmse, metrics.smape, metrics.r2_score, ] ``` ``` def benchmark_predictions( series_true: TimeSeries, series_prediction: TimeSeries, metrics: List[Callable], experiment_id: str, ) -> Dict: results = [] for m in benchmark_metrics: results.append( { "metric": f"{m.__name__}", "value": m(series_true, series_prediction), "experiment": experiment_id, } ) return results ``` ``` benchmark_results = [] for i, pred in zip( ["simple_rf", "detrended_cheating", "boxcox_linear_trend"], [pred_rf_ap, pred_rf_ap_seasonal, pred_rf_bc_lt], ): benchmark_results += benchmark_predictions( series_true=darts_air_passenger_test, series_prediction=pred, metrics=benchmark_metrics, experiment_id=i, ) df_benchmark_metrics = pd.DataFrame(benchmark_results) df_benchmark_metrics ``` ``` metric_chart_grid = sns.FacetGrid( df_benchmark_metrics, col="metric", hue="metric", col_wrap=2, height=4, aspect=1 / 0.618, sharey=False, ) metric_chart_grid.map( sns.barplot, "experiment", "value", order=df_benchmark_metrics.experiment.unique() ) # for axes in metric_chart_grid.axes.flat: # _ = axes.set_xticklabels(axes.get_xticklabels(), rotation=90) # metric_chart_grid.fig.tight_layout(w_pad=1) ``` # Forecasting with Boosted Trees Using Darts In this notebook, we explore some basic ideas of how to forecast using trees with the help of the package called [Darts](). On macOS, LightGBM crashes when it starts OpenMP after PyTorch has (darts imports PyTorch), so import it first. import lightgbm \# noqa: F401 \# isort: skip ``` from typing import Callable, Dict, List import darts.utils as du import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from darts import TimeSeries, metrics from darts.dataprocessing.transformers import BoxCox from darts.datasets import AirPassengersDataset from darts.models import LightGBMModel, NaiveDrift from sklearn.linear_model import LinearRegression ``` ## Following the Darts Official Tutorial Darts provides a [tutorial here]() to help the users get started. Here we replicate some of them to provide a minimal working example for tree-based models. ``` darts_air_passenger_series = AirPassengersDataset().load() darts_air_passenger_series.plot() ``` ``` darts_air_passenger_series ``` From the outputs, we see that the time series dataset contains montly data for 144 months. ``` train_series_length = 120 test_series_length = len(darts_air_passenger_series) - train_series_length train_series_length, test_series_length ``` ``` ( darts_air_passenger_train, darts_air_passenger_test, ) = darts_air_passenger_series.split_before(train_series_length) darts_air_passenger_train.plot(label="Training Data") darts_air_passenger_test.plot(label="Test Data") ``` ### First Random Forest Model ``` ap_horizon = len(darts_air_passenger_test) ap_gbdt_params = dict(lags=52, output_chunk_length=ap_horizon) ``` ``` gbdt_ap = LightGBMModel(**ap_gbdt_params) ``` ``` gbdt_ap.fit(darts_air_passenger_train) ``` Insample predictions: We plot out the predictions for the last 24 days in the training data. ``` darts_air_passenger_train.drop_after( darts_air_passenger_train.time_index[-ap_horizon] ).plot(label="Prediction Input") darts_air_passenger_train.drop_before( darts_air_passenger_train.time_index[-ap_horizon] ).plot(label="True Values") gbdt_ap.predict( n=ap_horizon, series=darts_air_passenger_train.drop_after( darts_air_passenger_train.time_index[-ap_horizon] ), ).plot(label="Predictions (In-sample)", linestyle="--") ``` To observe the actual performance, we plot out the predictions of the test dates. ``` darts_air_passenger_train.plot(label="Train") darts_air_passenger_test.plot(label="Test") pred_gbdt_ap = gbdt_ap.predict(n=ap_horizon) pred_gbdt_ap.plot(label="Prediction", linestyle="--") ``` ### Detrending Helps We train the same model but with the detrended dataset, and reconstruct the predictions using the trend. ``` ( darts_air_passenger_trend, darts_air_passenger_seasonal, ) = du.statistics.extract_trend_and_seasonality( darts_air_passenger_series, # model=du.utils.ModelMode.ADDITIVE, # method="STL" ) darts_air_passenger_series.plot() darts_air_passenger_trend.plot() (darts_air_passenger_trend * darts_air_passenger_seasonal).plot() ``` ``` ( darts_air_passenger_seasonal_train, darts_air_passenger_seasonal_test, ) = darts_air_passenger_seasonal.split_before(120) darts_air_passenger_seasonal_train.plot(label="Seasonal Component Train") darts_air_passenger_seasonal_test.plot(label="Seasonal Component Test") ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.histplot( darts_air_passenger_seasonal_train.to_dataframe(), x="0", kde=True, binwidth=0.1, binrange=(0.7, 1.3), label="Training Distribution", stat="probability", # fill=False, ax=ax, ) sns.histplot( darts_air_passenger_seasonal_test.to_dataframe(), x="0", kde=True, binwidth=0.1, binrange=(0.7, 1.3), label="Test Distribution", stat="probability", color="r", # fill=False, ax=ax, ) ax.set_xlabel("# Passengers") plt.legend() ``` ``` gbdt_ap_seasonal = LightGBMModel(**ap_gbdt_params) ``` ``` gbdt_ap_seasonal.fit(darts_air_passenger_seasonal_train) ``` ``` darts_air_passenger_train.plot(label="Train") darts_air_passenger_test.plot(label="Test") pred_rf_ap_seasonal = gbdt_ap_seasonal.predict( n=ap_horizon ) * darts_air_passenger_trend.drop_before(119) pred_rf_ap_seasonal.plot(label="Trend * Predicted Seasonal Component", linestyle="--") ``` This indiates that the performance of trees on out of sample predictions if we only predict on the cycle part of the series. In a real world case, however, we have to predict the trend accurately for this to work. To better reconstruct the trend, there are also tricks like [Box-Cox transformations](). ## Train, Test, and Metrics It is not easy to determine a best model simply looking at the charts. We need some metrics. ``` air_passenger_boxcox = BoxCox() darts_air_passenger_train_boxcox = air_passenger_boxcox.fit_transform( darts_air_passenger_train ) darts_air_passenger_test_boxcox = air_passenger_boxcox.transform( darts_air_passenger_test ) darts_air_passenger_train_boxcox.plot(label="Train (Box-Cox Transformed)") darts_air_passenger_test_boxcox.plot(label="Test (Box-Cox Transformed)") ``` ``` def linear_trend_model(series: TimeSeries) -> LinearRegression: """Fit a linear trend of the series. This can be used to find the linear model using training data. :param series: training timeseries """ positional_index_start = 0 series_trend, _ = du.statistics.extract_trend_and_seasonality(series) model = LinearRegression() length = len(series_trend) model.fit( np.arange(positional_index_start, positional_index_start + length).reshape( length, 1 ), series_trend.values(), ) return model def find_linear_trend( series: TimeSeries, model, positional_index_start: int = 0 ) -> TimeSeries: """Using the fitted linear model to find or extrapolate the linear trend. :param series: train or test timeseries :param model: LinearRegression model that has `predict` method :param positional_index_start: the position of the first value in the original timeseries. """ length = len(series) linear_preds = model.predict( np.arange(positional_index_start, positional_index_start + length).reshape( length, 1 ) ).squeeze() dataframe = pd.DataFrame( {"date": series.time_index, "# Passengers": linear_preds} ).set_index("date") return TimeSeries.from_dataframe(dataframe) ``` ``` ap_trend_lm = linear_trend_model(darts_air_passenger_train_boxcox) ap_trend_lm ``` ``` ap_trend_linear_train = find_linear_trend( model=ap_trend_lm, series=darts_air_passenger_train_boxcox ) ap_trend_linear_test = find_linear_trend( model=ap_trend_lm, series=darts_air_passenger_test_boxcox, positional_index_start=train_series_length, ) darts_air_passenger_train_boxcox.plot(label="Train") ap_trend_linear_train.plot(label="Linear Trend (Train)") darts_air_passenger_test_boxcox.plot(label="Test") ap_trend_linear_test.plot(label="Linear Trend (Test)") ``` ``` darts_air_passenger_train_transformed = ( darts_air_passenger_train_boxcox - ap_trend_linear_train ) darts_air_passenger_train_transformed.plot() ``` ``` gbdt_bc_lt = LightGBMModel(**ap_gbdt_params) gbdt_bc_lt.fit(darts_air_passenger_train_transformed) ``` ``` darts_air_passenger_train.plot() darts_air_passenger_test.plot() pred_gbdt_bc_lt = air_passenger_boxcox.inverse_transform( gbdt_bc_lt.predict(n=ap_horizon) + ap_trend_linear_test ) pred_gbdt_bc_lt.plot(label="Box-Cox + Linear Detrend Predictions", linestyle="--") ``` ## Linear Tree Horizon Detrending is not the only possibility. LightGBM implements a linear tree version of the base learners. ``` ap_gbdt_linear_tree_params = dict( lags=52, output_chunk_length=ap_horizon, linear_tree=True ) ``` ``` gbdt_linear_tree_ap = LightGBMModel(**ap_gbdt_linear_tree_params) ``` ``` gbdt_linear_tree_ap.fit(darts_air_passenger_train) ``` ``` darts_air_passenger_train.plot(label="Train") darts_air_passenger_test.plot(label="Test") pred_gbdt_linear_tree_ap = gbdt_linear_tree_ap.predict(n=ap_horizon) pred_gbdt_linear_tree_ap.plot(label="Linear Tree Prediction", linestyle="--") ``` ### Metrics ``` darts_air_passenger_test.plot(label="Test") pred_gbdt_ap.plot(label="Simple GBDT", linestyle="--") pred_rf_ap_seasonal.plot( label="GBDT on Global Detrended Data (Cheating)", linestyle="--" ) pred_gbdt_bc_lt.plot(label="GBDT on Box-Cox + Linear Detrend Data", linestyle="--") pred_gbdt_linear_tree_ap.plot(label="Linear Tree|", linestyle="--", color="r") ``` ``` benchmark_metrics = [ metrics.mae, metrics.mape, metrics.mse, metrics.rmse, metrics.smape, metrics.r2_score, ] ``` ``` def benchmark_predictions( series_true: TimeSeries, series_prediction: TimeSeries, metrics: List[Callable], experiment_id: str, ) -> Dict: results = [] for m in benchmark_metrics: results.append( { "metric": f"{m.__name__}", "value": m(series_true, series_prediction), "experiment": experiment_id, } ) return results ``` ``` benchmark_results = [] for i, pred in zip( ["simple_gbdt", "detrended_cheating", "boxcox_linear_trend", "linear_tree"], [pred_gbdt_ap, pred_rf_ap_seasonal, pred_gbdt_bc_lt, pred_gbdt_linear_tree_ap], ): benchmark_results += benchmark_predictions( series_true=darts_air_passenger_test, series_prediction=pred, metrics=benchmark_metrics, experiment_id=i, ) df_benchmark_metrics = pd.DataFrame(benchmark_results) df_benchmark_metrics ``` ``` metric_chart_grid = sns.FacetGrid( df_benchmark_metrics, col="metric", hue="metric", col_wrap=2, height=4, aspect=1 / 0.618, sharey=False, ) metric_chart_grid.map( sns.barplot, "experiment", "value", order=df_benchmark_metrics.experiment.unique() ) # for axes in metric_chart_grid.axes.flat: # _ = axes.set_xticklabels(axes.get_xticklabels(), rotation=90) # metric_chart_grid.fig.tight_layout(w_pad=1) ``` # Creating Time Series Datasets In this notebook, we explain how to create a time series dataset for PyTorch using the moving slicing technique. The class `DataFrameDataset` is also included in our `ts_dl_utils` package. ``` from typing import Tuple import numpy as np import pandas as pd from loguru import logger from torch.utils.data import Dataset ``` ```` class DataFrameDataset(Dataset): """A dataset from a pandas dataframe. For a given pandas dataframe, this generates a pytorch compatible dataset by sliding in time dimension. ```python ds = DataFrameDataset( dataframe=df, history_length=10, horizon=2 ) ``` :param dataframe: input dataframe with a DatetimeIndex. :param history_length: length of input X in time dimension in the final Dataset class. :param horizon: number of steps to be forecasted. :param gap: gap between input history and prediction """ def __init__( self, dataframe: pd.DataFrame, history_length: int, horizon: int, gap: int = 0 ): super().__init__() self.dataframe = dataframe self.history_length = history_length self.horzion = horizon self.gap = gap self.dataframe_rows = len(self.dataframe) self.length = ( self.dataframe_rows - self.history_length - self.horzion - self.gap + 1 ) def moving_slicing(self, idx: int, gap: int = 0) -> Tuple[np.ndarray, np.ndarray]: x, y = ( self.dataframe[idx : self.history_length + idx].values, self.dataframe[ self.history_length + idx + gap : self.history_length + self.horzion + idx + gap ].values, ) return x, y def _validate_dataframe(self) -> None: """Validate the input dataframe. - We require the dataframe index to be DatetimeIndex. - This dataset is null aversion. - Dataframe index should be sorted. """ if not isinstance( self.dataframe.index, pd.core.indexes.datetimes.DatetimeIndex ): raise TypeError( "Type of the dataframe index is not DatetimeIndex" f": {type(self.dataframe.index)}" ) has_na = self.dataframe.isnull().values.any() if has_na: logger.warning("Dataframe has null") has_index_sorted = self.dataframe.index.equals( self.dataframe.index.sort_values() ) if not has_index_sorted: logger.warning("Dataframe index is not sorted") def __getitem__(self, idx: int) -> Tuple[np.ndarray, np.ndarray]: if isinstance(idx, slice): if (idx.start < 0) or (idx.stop >= self.length): raise IndexError(f"Slice out of range: {idx}") step = idx.step if idx.step is not None else 1 return [ self.moving_slicing(i, self.gap) for i in range(idx.start, idx.stop, step) ] else: if idx >= self.length: raise IndexError("End of dataset") return self.moving_slicing(idx, self.gap) def __len__(self) -> int: return self.length ```` ## Examples We create a sample dataframe with one single variable "y" ``` df = pd.DataFrame(np.arange(15), columns=["y"]) df ``` ### history\_length=10, horizon=1 ``` ds_1 = DataFrameDataset(dataframe=df, history_length=10, horizon=1) ``` ``` list(ds_1) ``` ### history\_length=10, horizon=2 ``` ds_2 = DataFrameDataset(dataframe=df, history_length=10, horizon=2) ``` ``` list(ds_2) ``` ### history\_length=10, horizon=1, gap=1 ``` ds_1_gap_1 = DataFrameDataset(dataframe=df, history_length=10, horizon=1, gap=1) ``` ``` list(ds_1_gap_1) ``` ### history\_length=10, horizon=1, gap=2 ``` ds_1_gap_2 = DataFrameDataset(dataframe=df, history_length=10, horizon=1, gap=2) ``` ``` list(ds_1_gap_2) ``` ### history\_length=10, horizon=2, gap=1 ``` ds_2_gap_1 = DataFrameDataset(dataframe=df, history_length=10, horizon=2, gap=1) ``` ``` list(ds_2_gap_1) ``` ### history\_length=10, horizon=2, gap=2 ``` ds_2_gap_2 = DataFrameDataset(dataframe=df, history_length=10, horizon=2, gap=2) ``` ``` list(ds_2_gap_2) ``` # Feedforward Neural Networks for Univariate Time Series Forecasting In this notebook, we build a feedforward neural network using pytorch to forecast \\(\\sin\\) function as a time series. ``` import dataclasses import math ``` ``` import os from functools import cached_property from typing import Dict, List, Tuple import lightning as L import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from lightning.pytorch.callbacks.early_stopping import EarlyStopping from loguru import logger from torch import nn from torch.utils.data import DataLoader, Dataset from ts_dl_utils.datasets.pendulum import Pendulum, PendulumDataModule from ts_dl_utils.evaluation.evaluator import Evaluator from ts_dl_utils.naive_forecasters.last_observation import LastObservationForecaster ``` ## Data We create a dataset that models a damped pendulum. The pendulum is modelled as a damped harmonic oscillator, i.e., \\\[ \\theta(t) = \\theta(0) \\cos(2 \\pi t / p)\\exp(-\\beta t), \\\] where \\(\\theta(t)\\) is the angle of the pendulum at time \\(t\\). The period \\(p\\) is calculated using \\\[ p = 2 \\pi \\sqrt{L / g}, \\\] with \\(L\\) being the length of the pendulum and \\(g\\) being the surface gravity. ``` pen = Pendulum(length=100) ``` ``` df = pd.DataFrame(pen(10, 400, initial_angle=1, beta=0.001)) ``` ``` df["theta"] = df["theta"] + 2 ``` Since the damping constant is very small, the data generated is mostly a sin wave. ``` _, ax = plt.subplots(figsize=(10, 6.18)) df.plot(x="t", y="theta", ax=ax) ``` ## Model In this section, we create the FFN model. ``` @dataclasses.dataclass class TSFFNParams: """A dataclass to be served as our parameters for the model. :param hidden_widths: list of dimensions for the hidden layers """ hidden_widths: List[int] class TSFeedForward(nn.Module): """Feedforward networks for univaraite time series modeling. :param history_length: the length of the input history. :param horizon: the number of steps to be forecasted. :param ffn_params: the parameters for the FFN network. """ def __init__(self, history_length: int, horizon: int, ffn_params: TSFFNParams): super().__init__() self.ffn_params = ffn_params self.history_length = history_length self.horizon = horizon self.regulate_input = nn.Linear( self.history_length, self.ffn_params.hidden_widths[0] ) self.hidden_layers = nn.Sequential( *[ self._linear_block(dim_in, dim_out) for dim_in, dim_out in zip( self.ffn_params.hidden_widths[:-1], self.ffn_params.hidden_widths[1:], ) ] ) self.regulate_output = nn.Linear( self.ffn_params.hidden_widths[-1], self.horizon ) @property def ffn_config(self): return dataclasses.asdict(self.ffn_params) def _linear_block(self, dim_in, dim_out): return nn.Sequential(*[nn.Linear(dim_in, dim_out), nn.ReLU()]) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.regulate_input(x) x = self.hidden_layers(x) return self.regulate_output(x) ``` ## Forecasting (horizon=1) We use [lightning]() to train our model. ### Training Utilities ``` history_length_1_step = 100 horizon_1_step = 1 gap = 10 ``` We will build a few utilities 1. To be able to feed the data into our model, we build a class (`DataFrameDataset`) that converts the pandas dataframe into a Dataset for pytorch. 2. To make the lightning training code simpler, we will build a [LightningDataModule]() (`PendulumDataModule`) and a [LightningModule]() (`FFNForecaster`). ``` class FFNForecaster(L.LightningModule): def __init__(self, ffn: nn.Module): super().__init__() self.ffn = ffn def configure_optimizers(self): optimizer = torch.optim.SGD(self.parameters(), lr=1e-3) return optimizer def training_step(self, batch, batch_idx): x, y = batch x = x.squeeze().type(self.dtype) y = y.squeeze(-1).type(self.dtype) y_hat = self.ffn(x) loss = nn.functional.mse_loss(y_hat, y) self.log_dict({"train_loss": loss}, prog_bar=True) return loss def validation_step(self, batch, batch_idx): x, y = batch x = x.squeeze().type(self.dtype) y = y.squeeze(-1).type(self.dtype) y_hat = self.ffn(x) loss = nn.functional.mse_loss(y_hat, y) self.log_dict({"val_loss": loss}, prog_bar=True) return loss def predict_step(self, batch, batch_idx): x, y = batch x = x.squeeze().type(self.dtype) y = y.squeeze(-1).type(self.dtype) y_hat = self.ffn(x) return x, y_hat def forward(self, x): x = x.squeeze().type(self.dtype) return x, self.ffn(x) ``` ### Data, Model and Training #### DataModule ``` pdm_1_step = PendulumDataModule( history_length=history_length_1_step, horizon=horizon_1_step, gap=gap, dataframe=df[["theta"]], ) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) pdm_1_step_sample = list(pdm_1_step.train_dataloader())[0] pdm_1_step_sample_history = pdm_1_step_sample[0][0, ...].squeeze(-1).numpy() pdm_1_step_sample_target = pdm_1_step_sample[1][0, ...].squeeze(-1).numpy() pdm_1_step_sample_steps = np.arange( 0, len(pdm_1_step_sample_history) + gap + len(pdm_1_step_sample_target) ) ax.plot( pdm_1_step_sample_steps[: len(pdm_1_step_sample_history)], pdm_1_step_sample_history, marker=".", label="Input", ) ax.plot( pdm_1_step_sample_steps[len(pdm_1_step_sample_history) + gap :], pdm_1_step_sample_target, "r--", marker="x", label="Target", ) plt.legend() ``` #### LightningModule ``` ts_ffn_params_1_step = TSFFNParams(hidden_widths=[512, 256, 64, 256, 512]) ts_ffn_1_step = TSFeedForward( history_length=history_length_1_step, horizon=horizon_1_step, ffn_params=ts_ffn_params_1_step, ) ts_ffn_1_step ``` ``` ffn_forecaster_1_step = FFNForecaster(ffn=ts_ffn_1_step) ``` #### Trainer ``` logger_1_step = L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="ffn_ts_1_step" ) trainer_1_step = L.Trainer( precision="64", max_epochs=100, min_epochs=5, callbacks=[ EarlyStopping(monitor="val_loss", mode="min", min_delta=1e-4, patience=2) ], logger=logger_1_step, ) ``` #### Fitting ``` trainer_1_step.fit(model=ffn_forecaster_1_step, datamodule=pdm_1_step) ``` #### Retrieving Predictions ``` predictions_1_step = trainer_1_step.predict( model=ffn_forecaster_1_step, datamodule=pdm_1_step ) ``` ### Naive Forecasts To understand how good our forecasts are, we take the last observations in time and use them as forecasts. `ts_LastObservationForecaster` is a forecaster we have build for this purpose. ``` trainer_naive_1_step = L.Trainer(precision="64") lobs_forecaster_1_step = LastObservationForecaster(horizon=horizon_1_step) lobs_1_step_predictions = trainer_naive_1_step.predict( model=lobs_forecaster_1_step, datamodule=pdm_1_step ) ``` ### Evaluations ``` evaluator_1_step = Evaluator(step=0) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator_1_step.y_true(dataloader=pdm_1_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_1_step.y(predictions_1_step), "r--", label="predictions") ax.plot(evaluator_1_step.y(lobs_1_step_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` evaluator_1_step.metrics(predictions_1_step, pdm_1_step.predict_dataloader()) ``` ``` evaluator_1_step.metrics(lobs_1_step_predictions, pdm_1_step.predict_dataloader()) ``` ## Forecasting (horizon=3) ### Train a Model ``` history_length_m_step = 100 horizon_m_step = 3 ``` ``` pdm_m_step = PendulumDataModule( history_length=history_length_m_step, horizon=horizon_m_step, dataframe=df[["theta"]], gap=gap, ) ``` ``` ts_ffn_params_m_step = TSFFNParams(hidden_widths=[512, 256, 64, 256, 512]) ts_ffn_m_step = TSFeedForward( history_length=history_length_m_step, horizon=horizon_m_step, ffn_params=ts_ffn_params_m_step, ) ts_ffn_m_step ``` ``` ffn_forecaster_m_step = FFNForecaster(ffn=ts_ffn_m_step) ``` ``` logger_m_step = L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="ffn_ts_m_step" ) trainer_m_step = L.Trainer( precision="64", max_epochs=100, min_epochs=5, callbacks=[ EarlyStopping(monitor="val_loss", mode="min", min_delta=1e-4, patience=2) ], logger=logger_m_step, ) ``` ``` trainer_m_step.fit(model=ffn_forecaster_m_step, datamodule=pdm_m_step) ``` ``` predictions_m_step = trainer_m_step.predict( model=ffn_forecaster_m_step, datamodule=pdm_m_step ) ``` ### Naive Forecaster ``` trainer_naive_m_step = L.Trainer(precision="64") lobs_forecaster_m_step = LastObservationForecaster(horizon=horizon_m_step) lobs_m_step_predictions = trainer_naive_m_step.predict( model=lobs_forecaster_m_step, datamodule=pdm_m_step ) ``` ### Evaluation ``` evaluator_m_step = Evaluator(step=2, gap=gap) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator_m_step.y_true(dataloader=pdm_m_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_m_step.y(predictions_m_step), "r--", label="predictions") ax.plot(evaluator_m_step.y(lobs_m_step_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) for i in np.arange(0, 1000, 120): evaluator_m_step.plot_one_sample(ax=ax, predictions=predictions_m_step, idx=i) ``` ``` evaluator_m_step.metrics(predictions_m_step, pdm_m_step.predict_dataloader()) ``` ``` evaluator_m_step.metrics(lobs_m_step_predictions, pdm_m_step.predict_dataloader()) ``` # RNN for Univariate Time Series Forecasting In this notebook, we build a RNN using pytorch to forecast \\(\\sin\\) function as a time series. ``` import dataclasses ``` ``` from functools import cached_property from typing import Dict, List, Tuple import lightning as L import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from lightning.pytorch.callbacks.early_stopping import EarlyStopping from loguru import logger from torch import nn from torch.utils.data import DataLoader, Dataset from ts_dl_utils.datasets.pendulum import Pendulum, PendulumDataModule from ts_dl_utils.evaluation.evaluator import Evaluator from ts_dl_utils.naive_forecasters.last_observation import LastObservationForecaster ``` ## Data We create a dataset that models a damped pendulum. The pendulum is modelled as a damped harmonic oscillator, i.e., \\\[ \\theta(t) = \\theta(0) \\cos(2 \\pi t / p)\\exp(-\\beta t), \\\] where \\(\\theta(t)\\) is the angle of the pendulum at time \\(t\\). The period \\(p\\) is calculated using \\\[ p = 2 \\pi \\sqrt{L / g}, \\\] with \\(L\\) being the length of the pendulum and \\(g\\) being the surface gravity. ``` pen = Pendulum(length=100) ``` ``` df = pd.DataFrame(pen(10, 400, initial_angle=1, beta=0.001)) ``` Since the damping constant is very small, the data generated is mostly a sin wave. ``` _, ax = plt.subplots(figsize=(10, 6.18)) df.plot(x="t", y="theta", ax=ax) ``` ## Model In this section, we create the RNN model. ``` @dataclasses.dataclass class TSRNNParams: """A dataclass to be served as our parameters for the model. :param hidden_size: number of dimensions in the hidden state :param input_size: input dim :param num_layers: number of units stacked """ input_size: int hidden_size: int num_layers: int = 1 class TSRNN(nn.Module): """RNN for univaraite time series modeling. :param history_length: the length of the input history. :param horizon: the number of steps to be forecasted. :param rnn_params: the parameters for the RNN network. """ def __init__(self, history_length: int, horizon: int, rnn_params: TSRNNParams): super().__init__() self.rnn_params = rnn_params self.history_length = history_length self.horizon = horizon self.regulate_input = nn.Linear(self.history_length, self.rnn_params.input_size) self.rnn = nn.RNN( input_size=self.rnn_params.input_size, hidden_size=self.rnn_params.hidden_size, num_layers=self.rnn_params.num_layers, batch_first=True, ) self.regulate_output = nn.Linear(self.rnn_params.hidden_size, self.horizon) @property def rnn_config(self): return dataclasses.asdict(self.rnn_params) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.regulate_input(x) x, _ = self.rnn(x) return self.regulate_output(x) ``` ## Training We use [lightning]() to train our model. ### Training Utilities ``` history_length_1_step = 100 horizon_1_step = 1 gap = 10 ``` We will build a few utilities 1. To be able to feed the data into our model, we build a class (`DataFrameDataset`) that converts the pandas dataframe into a Dataset for pytorch. 2. To make the lightning training code simpler, we will build a [LightningDataModule]() (`PendulumDataModule`) and a [LightningModule]() (`RNNForecaster`). ``` class RNNForecaster(L.LightningModule): def __init__(self, rnn: nn.Module): super().__init__() self.rnn = rnn def configure_optimizers(self): optimizer = torch.optim.SGD(self.parameters(), lr=1e-3) return optimizer def training_step(self, batch, batch_idx): x, y = batch x = x.squeeze().type(self.dtype) y = y.squeeze(-1).type(self.dtype) y_hat = self.rnn(x) loss = nn.functional.l1_loss(y_hat, y) self.log_dict({"train_loss": loss}, prog_bar=True) return loss def validation_step(self, batch, batch_idx): x, y = batch x = x.squeeze().type(self.dtype) y = y.squeeze(-1).type(self.dtype) y_hat = self.rnn(x) loss = nn.functional.l1_loss(y_hat, y) self.log_dict({"val_loss": loss}, prog_bar=True) return loss def predict_step(self, batch, batch_idx): x, y = batch x = x.squeeze().type(self.dtype) y = y.squeeze(-1).type(self.dtype) y_hat = self.rnn(x) return x, y_hat def forward(self, x): x = x.squeeze().type(self.dtype) return x, self.rnn(x) ``` ### Data, Model and Training #### DataModule ``` pdm_1_step = PendulumDataModule( history_length=history_length_1_step, horizon=horizon_1_step, gap=gap, dataframe=df[["theta"]], ) ``` #### LightningModule ``` ts_rnn_params_1_step = TSRNNParams(input_size=96, hidden_size=64, num_layers=1) ts_rnn_1_step = TSRNN( history_length=history_length_1_step, horizon=horizon_1_step, rnn_params=ts_rnn_params_1_step, ) ts_rnn_1_step ``` ``` rnn_forecaster_1_step = RNNForecaster(rnn=ts_rnn_1_step) ``` #### Trainer ``` logger_1_step = L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="rnn_ts_1_step" ) trainer_1_step = L.Trainer( precision="64", max_epochs=100, min_epochs=5, callbacks=[ EarlyStopping(monitor="val_loss", mode="min", min_delta=1e-5, patience=2) ], logger=logger_1_step, ) ``` #### Fitting ``` trainer_1_step.fit(model=rnn_forecaster_1_step, datamodule=pdm_1_step) ``` #### Retrieving Predictions ``` predictions_1_step = trainer_1_step.predict( model=rnn_forecaster_1_step, datamodule=pdm_1_step ) ``` ### Naive Forecaster ``` trainer_naive_1_step = L.Trainer(precision="64") lobs_forecaster_1_step = LastObservationForecaster(horizon=horizon_1_step) lobs_1_step_predictions = trainer_naive_1_step.predict( model=lobs_forecaster_1_step, datamodule=pdm_1_step ) ``` ### Evaluations ``` evaluator_1_step = Evaluator(step=0) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator_1_step.y_true(dataloader=pdm_1_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_1_step.y(predictions_1_step), "r--", label="predictions") ax.plot(evaluator_1_step.y(lobs_1_step_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` evaluator_1_step.metrics(predictions_1_step, pdm_1_step.predict_dataloader()) ``` ``` evaluator_1_step.metrics(lobs_1_step_predictions, pdm_1_step.predict_dataloader()) ``` ## Multi-horizon Forecast (h=3) ### Train a Model ``` history_length_m_step = 100 horizon_m_step = 3 ``` ``` pdm_m_step = PendulumDataModule( history_length=history_length_m_step, horizon=horizon_m_step, dataframe=df[["theta"]], gap=gap, ) ``` ``` ts_rnn_params_m_step = TSRNNParams(input_size=96, hidden_size=64, num_layers=1) ts_rnn_m_step = TSRNN( history_length=history_length_m_step, horizon=horizon_m_step, rnn_params=ts_rnn_params_m_step, ) ts_rnn_m_step ``` ``` rnn_forecaster_m_step = RNNForecaster(rnn=ts_rnn_m_step) ``` ``` logger_m_step = L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="rnn_ts_m_step" ) trainer_m_step = L.Trainer( precision="64", max_epochs=100, min_epochs=5, callbacks=[ EarlyStopping(monitor="val_loss", mode="min", min_delta=1e-5, patience=2) ], logger=logger_m_step, ) ``` ``` trainer_m_step.fit(model=rnn_forecaster_m_step, datamodule=pdm_m_step) ``` ``` predictions_m_step = trainer_m_step.predict( model=rnn_forecaster_m_step, datamodule=pdm_m_step ) ``` ### Naive Forecaster ``` trainer_naive_m_step = L.Trainer(precision="64") lobs_forecaster_m_step = LastObservationForecaster(horizon=horizon_m_step) lobs_m_step_predictions = trainer_naive_m_step.predict( model=lobs_forecaster_m_step, datamodule=pdm_m_step ) ``` ### Evaluations ``` evaluator_m_step = Evaluator(step=2, gap=gap) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator_m_step.y_true(dataloader=pdm_m_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_m_step.y(predictions_m_step), "r--", label="predictions") ax.plot(evaluator_m_step.y(lobs_m_step_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) for i in np.arange(0, 1000, 120): evaluator_m_step.plot_one_sample(ax=ax, predictions=predictions_m_step, idx=i) ``` ``` evaluator_m_step.metrics(predictions_m_step, pdm_m_step.predict_dataloader()) ``` ``` evaluator_m_step.metrics(lobs_m_step_predictions, pdm_m_step.predict_dataloader()) ``` # Transformer for Univariate Time Series Forecasting In this notebook, we build a transformer using pytorch to forecast \\(\\sin\\) function as a time series. ``` import dataclasses ``` ``` import math import lightning as L import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from lightning.pytorch.callbacks.early_stopping import EarlyStopping from torch import nn from ts_dl_utils.datasets.pendulum import Pendulum, PendulumDataModule from ts_dl_utils.evaluation.evaluator import Evaluator from ts_dl_utils.naive_forecasters.last_observation import LastObservationForecaster ``` ## Data We create a dataset that models a damped pendulum. The pendulum is modelled as a damped harmonic oscillator, i.e., \\\[ \\theta(t) = \\theta(0) \\cos(2 \\pi t / p)\\exp(-\\beta t), \\\] where \\(\\theta(t)\\) is the angle of the pendulum at time \\(t\\). The period \\(p\\) is calculated using \\\[ p = 2 \\pi \\sqrt{L / g}, \\\] with \\(L\\) being the length of the pendulum and \\(g\\) being the surface gravity. ``` pen = Pendulum(length=10000) ``` ``` df = pd.DataFrame(pen(100, 400, initial_angle=1, beta=0.000001)) ``` Since the damping constant is very small, the data generated is mostly a sin wave. ``` _, ax = plt.subplots(figsize=(10, 6.18)) df.plot(x="t", y="theta", ax=ax) ``` ``` ``` ![output]() ## Model In this section, we create the transformer model. Since we do not deal with future covariates, we do not need a decoder. In this example, we build a simple transformer that only contains attention in encoder. ``` @dataclasses.dataclass class TSTransformerParams: """A dataclass that contains all the parameters for the transformer model. """ d_model: int = 512 nhead: int = 8 num_encoder_layers: int = 6 dropout: int = 0.1 class PositionalEncoding(nn.Module): """Positional encoding to be added to input embedding. :param d_model: hidden dimension of the encoder :param dropout: rate of dropout :param max_len: maximum length of our positional encoder. The encoder can not encode sequence length longer than max_len. """ def __init__( self, d_model: int, dropout: float = 0.1, max_len: int = 5000, ): super().__init__() self.max_len = max_len self.dropout = nn.Dropout(p=dropout) position = torch.arange(max_len).unsqueeze(1) div_term = torch.exp( torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model) ) pe = torch.zeros(max_len, d_model) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) self.register_buffer("pe", pe) def forward(self, x: torch.Tensor) -> torch.Tensor: """ :param x: input embedded time series, shape `[batch_size, seq_len, embedding_dim]` """ history_length = x.size(1) x = x + self.pe[:history_length] return self.dropout(x) class TSTransformer(nn.Module): """Transformer for univaraite time series modeling. :param history_length: the length of the input history. :param horizon: the number of steps to be forecasted. :param transformer_params: all the parameters. """ def __init__( self, history_length: int, horizon: int, transformer_params: TSTransformerParams, ): super().__init__() self.transformer_params = transformer_params self.history_length = history_length self.horizon = horizon self.embedding = nn.Linear(1, self.transformer_params.d_model) self.positional_encoding = PositionalEncoding( d_model=self.transformer_params.d_model ) encoder_layer = nn.TransformerEncoderLayer( d_model=self.transformer_params.d_model, nhead=self.transformer_params.nhead, batch_first=True, ) self.encoder = nn.TransformerEncoder( encoder_layer, num_layers=self.transformer_params.num_encoder_layers ) self.reverse_embedding = nn.Linear(self.transformer_params.d_model, 1) self.decoder = nn.Linear(self.history_length, self.horizon) @property def transformer_config(self) -> dict: """all the param in dict format""" return dataclasses.asdict(self.transformer_params) def forward(self, x: torch.Tensor) -> torch.Tensor: """ :param x: input historical time series, shape `[batch_size, seq_len, n_var]` """ x = self.embedding(x) x = self.positional_encoding(x) encoder_state = self.encoder(x) decoder_in = self.reverse_embedding(encoder_state).squeeze(-1) return self.decoder(decoder_in) ``` ## Training We use [lightning]() to train our model. ### Training Utilities ``` history_length_1_step = 100 horizon_1_step = 1 gap = 0 ``` We will build a few utilities 1. To be able to feed the data into our model, we build a class (`DataFrameDataset`) that converts the pandas dataframe into a Dataset for pytorch. 2. To make the lightning training code simpler, we will build a [LightningDataModule]() (`PendulumDataModule`) and a [LightningModule]() (`TransformerForecaster`). ``` class TransformerForecaster(L.LightningModule): """Transformer forecasting training, validation, and prediction all collected in one class. :param transformer: pre-defined transformer model """ def __init__(self, transformer: nn.Module): super().__init__() self.transformer = transformer self.save_hyperparameters() def configure_optimizers(self) -> torch.optim.Optimizer: optimizer = torch.optim.SGD(self.parameters(), lr=1e-3) return optimizer def training_step(self, batch: tuple[torch.Tensor], batch_idx: int) -> torch.Tensor: x, y = batch y = y.squeeze(-1).type(self.dtype) y_hat = self.transformer(x) loss = nn.functional.mse_loss(y_hat, y) self.log_dict({"train_loss": loss}, prog_bar=True) return loss def validation_step( self, batch: tuple[torch.Tensor], batch_idx: int ) -> torch.Tensor: x, y = batch y = y.squeeze(-1).type(self.dtype) y_hat = self.transformer(x) loss = nn.functional.mse_loss(y_hat, y) self.log_dict({"val_loss": loss}, prog_bar=True) return loss def predict_step( self, batch: list[torch.Tensor], batch_idx: int ) -> tuple[torch.Tensor]: x, y = batch y = y.squeeze(-1).type(self.dtype) y_hat = self.transformer(x) return x, y_hat def forward(self, x: torch.Tensor) -> tuple[torch.Tensor]: return x, self.transformer(x) ``` ### Data, Model and Training #### DataModule ``` pdm_1_step = PendulumDataModule( history_length=history_length_1_step, horizon=horizon_1_step, dataframe=df[["theta"]], gap=gap, ) ``` #### LightningModule ``` ts_transformer_params_1_step = TSTransformerParams( d_model=192, nhead=6, num_encoder_layers=1 ) ts_transformer_1_step = TSTransformer( history_length=history_length_1_step, horizon=horizon_1_step, transformer_params=ts_transformer_params_1_step, ) ts_transformer_1_step ``` ``` TSTransformer( (embedding): Linear(in_features=1, out_features=192, bias=True) (positional_encoding): PositionalEncoding( (dropout): Dropout(p=0.1, inplace=False) ) (encoder): TransformerEncoder( (layers): ModuleList( (0): TransformerEncoderLayer( (self_attn): MultiheadAttention( (out_proj): NonDynamicallyQuantizableLinear(in_features=192, out_features=192, bias=True) ) (linear1): Linear(in_features=192, out_features=2048, bias=True) (dropout): Dropout(p=0.1, inplace=False) (linear2): Linear(in_features=2048, out_features=192, bias=True) (norm1): LayerNorm((192,), eps=1e-05, elementwise_affine=True) (norm2): LayerNorm((192,), eps=1e-05, elementwise_affine=True) (dropout1): Dropout(p=0.1, inplace=False) (dropout2): Dropout(p=0.1, inplace=False) ) ) ) (reverse_embedding): Linear(in_features=192, out_features=1, bias=True) (decoder): Linear(in_features=100, out_features=1, bias=True) ) ``` ``` transformer_forecaster_1_step = TransformerForecaster(transformer=ts_transformer_1_step) transformer_forecaster_1_step ``` ``` TransformerForecaster( (transformer): TSTransformer( (embedding): Linear(in_features=1, out_features=192, bias=True) (positional_encoding): PositionalEncoding( (dropout): Dropout(p=0.1, inplace=False) ) (encoder): TransformerEncoder( (layers): ModuleList( (0): TransformerEncoderLayer( (self_attn): MultiheadAttention( (out_proj): NonDynamicallyQuantizableLinear(in_features=192, out_features=192, bias=True) ) (linear1): Linear(in_features=192, out_features=2048, bias=True) (dropout): Dropout(p=0.1, inplace=False) (linear2): Linear(in_features=2048, out_features=192, bias=True) (norm1): LayerNorm((192,), eps=1e-05, elementwise_affine=True) (norm2): LayerNorm((192,), eps=1e-05, elementwise_affine=True) (dropout1): Dropout(p=0.1, inplace=False) (dropout2): Dropout(p=0.1, inplace=False) ) ) ) (reverse_embedding): Linear(in_features=192, out_features=1, bias=True) (decoder): Linear(in_features=100, out_features=1, bias=True) ) ) ``` #### Trainer ``` logger_1_step = L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="transformer_ts_1_step" ) trainer_1_step = L.Trainer( precision="64", max_epochs=100, min_epochs=5, callbacks=[ EarlyStopping(monitor="val_loss", mode="min", min_delta=1e-7, patience=3) ], logger=logger_1_step, ) ``` ``` GPU available: True (mps), used: True TPU available: False, using: 0 TPU cores IPU available: False, using: 0 IPUs HPU available: False, using: 0 HPUs ``` #### Fitting ``` demo_x = list(pdm_1_step.train_dataloader())[0][0].type( transformer_forecaster_1_step.dtype ) demo_x.shape ``` ``` torch.Size([32, 100, 1]) ``` ``` nn.Linear( 1, ts_transformer_1_step.transformer_params.d_model, dtype=transformer_forecaster_1_step.dtype, )(demo_x).shape ``` ``` torch.Size([32, 100, 192]) ``` ``` ts_transformer_1_step.encoder(ts_transformer_1_step.embedding(demo_x)).shape ``` ``` torch.Size([32, 100, 192]) ``` ``` trainer_1_step.fit(model=transformer_forecaster_1_step, datamodule=pdm_1_step) ``` #### Retrieving Predictions ``` predictions_1_step = trainer_1_step.predict( model=transformer_forecaster_1_step, datamodule=pdm_1_step ) ``` ### Naive Forecaster ``` trainer_naive_1_step = L.Trainer(precision="64") lobs_forecaster_1_step = LastObservationForecaster(horizon=horizon_1_step) lobs_1_step_predictions = trainer_naive_1_step.predict( model=lobs_forecaster_1_step, datamodule=pdm_1_step ) ``` ## Evaluations ``` evaluator_1_step = Evaluator(step=0) ``` ``` fig, ax = plt.subplots(figsize=(50, 6.18)) ax.plot( evaluator_1_step.y_true(dataloader=pdm_1_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_1_step.y(predictions_1_step), "r--", label="predictions") ax.plot(evaluator_1_step.y(lobs_1_step_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) inspection_slice_length = 200 ax.plot( evaluator_1_step.y_true(dataloader=pdm_1_step.predict_dataloader())[ :inspection_slice_length ], "g-", label="truth", ) ax.plot( evaluator_1_step.y(predictions_1_step)[:inspection_slice_length], "r--", label="predictions", ) ax.plot( evaluator_1_step.y(lobs_1_step_predictions)[:inspection_slice_length], "b-.", label="naive predictions", ) plt.legend() ``` To quantify the results, we compute a few metrics. ``` pd.merge( evaluator_1_step.metrics(predictions_1_step, pdm_1_step.predict_dataloader()), evaluator_1_step.metrics(lobs_1_step_predictions, pdm_1_step.predict_dataloader()), how="left", left_index=True, right_index=True, suffixes=["_transformer", "_naive"], ) ``` Here SMAPE is better because of better forecasts for larger values ## Forecasting (horizon=3) ### Train a Model ``` history_length_m_step = 100 horizon_m_step = 3 ``` ``` pdm_m_step = PendulumDataModule( history_length=history_length_m_step, horizon=horizon_m_step, dataframe=df[["theta"]], gap=gap, ) ``` ``` ts_transformer_params_m_step = TSTransformerParams( d_model=192, nhead=6, num_encoder_layers=1 ) ts_transformer_m_step = TSTransformer( history_length=history_length_m_step, horizon=horizon_m_step, transformer_params=ts_transformer_params_m_step, ) ts_transformer_m_step ``` ``` transformer_forecaster_m_step = TransformerForecaster(transformer=ts_transformer_m_step) ``` ``` logger_m_step = L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="transformer_ts_m_step" ) trainer_m_step = L.Trainer( precision="64", max_epochs=100, min_epochs=5, callbacks=[ EarlyStopping(monitor="val_loss", mode="min", min_delta=1e-7, patience=3) ], logger=logger_m_step, ) ``` ``` trainer_m_step.fit(model=transformer_forecaster_m_step, datamodule=pdm_m_step) ``` ``` predictions_m_step = trainer_m_step.predict( model=transformer_forecaster_m_step, datamodule=pdm_m_step ) ``` ### Naive Forecaster ``` trainer_naive_m_step = L.Trainer(precision="64") lobs_forecaster_m_step = LastObservationForecaster(horizon=horizon_m_step) lobs_m_step_predictions = trainer_naive_m_step.predict( model=lobs_forecaster_m_step, datamodule=pdm_m_step ) ``` ### Evaluations ``` evaluator_m_step = Evaluator(step=2, gap=gap) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator_m_step.y_true(dataloader=pdm_m_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_m_step.y(predictions_m_step), "r--", label="predictions") ax.plot(evaluator_m_step.y(lobs_m_step_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) for i in np.arange(0, 1000, 120): evaluator_m_step.plot_one_sample(ax=ax, predictions=predictions_m_step, idx=i) ``` ``` evaluator_m_step.metrics(predictions_m_step, pdm_m_step.predict_dataloader()) ``` ``` evaluator_m_step.metrics(lobs_m_step_predictions, pdm_m_step.predict_dataloader()) ``` # Investigations We dive deeper into the intermediate results of the model. ``` from pathlib import Path import pandas as pd import plotly.express as px from torch.utils.data import DataLoader from ts_dl_utils.datasets.dataset import DataFrameDataset ``` ``` load_from_checkpoint = ( Path( # "lightning_logs/transformer_ts_1_step/version_9" "lightning_logs/transformer_ts_1_step/version_7" ) / "checkpoints" ) # load_from_checkpoint = Path(logger_1_step.log_dir) / "checkpoints" load_from_checkpoint, logger_1_step.log_dir ``` ``` list(load_from_checkpoint.iterdir())[0] ``` ``` transformer_forecaster_1_step_re = TransformerForecaster.load_from_checkpoint( # load_from_checkpoint / "checkpoints/epoch=11-step=5495.ckpt" list(load_from_checkpoint.iterdir())[0] ) transformer_forecaster_1_step_re ``` ## Visualize Embeddings of Intermediate Layers ``` def embedding_extractor( forecaster: TransformerForecaster, x: torch.Tensor ) -> tuple[torch.Tensor]: """compute the embeddings based on the input :param forecaster: the trained forecaster :param x: input historical time series, """ forecaster.transformer.to(x.device) x_embedding = forecaster.transformer.embedding( x.type_as(forecaster.transformer.embedding.weight) ) x_positional = forecaster.transformer.positional_encoding(x_embedding) encoder_state = forecaster.transformer.encoder(x_positional) reversed = forecaster.transformer.reverse_embedding(encoder_state).squeeze(-1) return x_embedding, x_positional, encoder_state, reversed ``` ``` def create_embedding_dataframe( dr_result: torch.Tensor, n_batches: int, input_example: torch.Tensor, n_components: int, ) -> pd.DataFrame: dr_df = pd.DataFrame( dr_result.detach().numpy(), columns=[f"DR_{i+1}" for i in range(n_components)] ) dr_df["batch"] = sum( [[i] * (len(dr_df) // n_batches) for i in range(n_batches)], [] ) dr_df["sample_idx"] = list(range(len(dr_df) // n_batches)) * n_batches dr_df["input"] = np.concatenate( input_example[:n_batches].detach().numpy().astype("float32") ) dr_df = dr_df.merge( pd.DataFrame( input_example[:n_batches].detach()[:, 0, 0].numpy(), columns=["batch_first_value"], ) .reset_index() .rename(columns={"index": "batch"}), how="left", on="batch", ) return dr_df ``` Prepare input data for embedding visualization. ``` investigation_dl = DataLoader( dataset=DataFrameDataset( dataframe=df[["theta"]], history_length=history_length_1_step, horizon=horizon_1_step, gap=gap, ), batch_size=400, shuffle=False, ) investigation_dl ``` ``` input_example = list(investigation_dl)[0][0] input_example.shape ``` ``` (embedding_example, positional_example, encoder_example, reversed_example) = ( embedding_extractor(transformer_forecaster_1_step, input_example) ) ``` ``` ( input_example.shape, embedding_example.shape, positional_example.shape, encoder_example.shape, reversed_example.shape, ) ``` ``` n_batches, seq_len, _ = input_example.shape df_example = pd.DataFrame( { "input": input_example.squeeze(-1).detach().cpu().numpy().reshape(-1), "reversed": reversed_example.detach().cpu().numpy().reshape(-1), "sample": np.repeat(np.arange(n_batches), seq_len), } ) df_example ``` ``` px.scatter( df_example, x="input", y="reversed", color="sample", height=600, width=600 ).update_layout(yaxis_scaleanchor="x") ``` ``` import numpy as np from torchdr import PCA, TSNE, UMAP ``` Latent space visualization ``` n_components = 2 dr_reversed_result = TSNE( # dr_reversed_result = UMAP( # dr_reversed_result = PCA( # n_neighbors=30, # backend='torch', perplexity=30, n_components=n_components, ).fit_transform( np.concatenate( [ input_example.squeeze(-1).numpy().astype("float32"), reversed_example.detach().numpy().astype("float32"), ], axis=0, ) ) ``` ``` dr_reversed_df = pd.DataFrame( dr_reversed_result, columns=[f"DR_{i+1}" for i in range(n_components)] ) dr_reversed_df["type"] = ["input"] * (len(dr_reversed_df) // 2) + ["embedded"] * ( len(dr_reversed_df) - len(dr_reversed_df) // 2 ) dr_reversed_df["sample_idx"] = list(range(len(dr_reversed_df) // 2)) + list( range(len(dr_reversed_df) // 2) ) ``` ``` px.scatter( dr_reversed_df, x="DR_1", y="DR_2", # z="DR_3", color="sample_idx", # color="DR_4", symbol="type", title="Embedding of Input and Encoded Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.scatter_3d( dr_reversed_df, x="DR_1", y="DR_2", z="DR_3", color="sample_idx", # color="DR_4", symbol="type", title="Embedding of Input and Encoded Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.scatter_3d( dr_reversed_df.loc[dr_reversed_df["type"] == "embedded"], x="DR_1", y="DR_2", z="DR_3", color="sample_idx", # color="DR_4", symbol="type", title="Embedding of Input Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` Embedding outout ``` embedding_example.detach()[0].shape, input_example.detach()[0].shape ``` ``` embedding_result = UMAP( # embedding_result = TSNE( n_neighbors=30, backend="torch", # perplexity=30, n_components=n_components, ).fit_transform( # np.concatenate( # embedding_example.detach().numpy().astype("float32") # ) embedding_example.detach().reshape(-1, embedding_example.shape[-1]) ) embedding_result.shape ``` ``` dr_embedding_df = create_embedding_dataframe( dr_result=embedding_result, n_batches=embedding_example.shape[0], input_example=input_example, n_components=n_components, ) ``` ``` dr_embedding_df ``` ``` px.scatter( dr_embedding_df, x="input", y="DR_1", # x='DR_1', # y='DR_2', # z='DR_3', # color='sample_idx', # symbol='type', # color="batch_first_value", # color="input", title="Dimension Reduction for Embedding of Input Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.scatter_3d( dr_embedding_df, x="DR_1", y="DR_2", # z='DR_3', z="input", # color='sample_idx', # symbol='type', # color="batch", # color="batch_first_value", color="input", title="UMAP Embedding of Input Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.scatter( pd.DataFrame(input_example.detach()[:, 0, :].numpy()).reset_index(), x="index", y=0, height=600, width=800, ) ``` Positional encoding output ``` positional_example_sample_size = 100 ``` ``` # positional_result = UMAP( positional_result = TSNE( # n_neighbors=30, backend='torch', perplexity=30, n_components=n_components, ).fit_transform( positional_example.detach()[:positional_example_sample_size].reshape( -1, positional_example.shape[-1] ) ) positional_result.shape ``` ``` dr_positional_df = create_embedding_dataframe( dr_result=positional_result, n_batches=positional_example_sample_size, input_example=input_example, n_components=n_components, ) ``` ``` dr_positional_df = pd.DataFrame( positional_result.detach().numpy(), columns=[f"DR_{i+1}" for i in range(n_components)], ) dr_positional_df["batch"] = sum( [ [i] * (len(dr_positional_df) // positional_example_sample_size) for i in range(positional_example_sample_size) ], [], ) dr_positional_df["sample_idx"] = ( list(range(len(dr_positional_df) // positional_example_sample_size)) * positional_example_sample_size ) dr_positional_df["input"] = np.concatenate( input_example[:positional_example_sample_size].detach().numpy().astype("float32") ) dr_positional_df = dr_positional_df.merge( pd.DataFrame( input_example[:positional_example_sample_size].detach()[:, 0, 0].numpy(), columns=["batch_first_value"], ) .reset_index() .rename(columns={"index": "batch"}), how="left", on="batch", ) ``` ``` dr_positional_df ``` ``` px.scatter_3d( dr_positional_df, x="DR_1", y="DR_2", z="input", # color='sample_idx', # symbol='type', # color="batch", color="batch_first_value", title="UMAP Embedding of Positional Encoded Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.scatter( dr_positional_df, x="DR_1", y="DR_2", # z='input', # symbol='type', color="batch", # color="input", # color="batch_first_value", title="UMAP Embedding of Positional Encoded Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.scatter( dr_positional_df, x="input", y="DR_1", color="batch_first_value", ) ``` Encoder output ``` # encoder_result = TSNE( encoder_result = PCA( # n_neighbors=30, backend='torch', # perplexity=30, n_components=n_components ).fit_transform( encoder_example.detach()[:positional_example_sample_size].reshape( -1, encoder_example.shape[-1] ) ) encoder_result.shape ``` ``` dr_encoder_df = create_embedding_dataframe( dr_result=encoder_result, # n_batches=encoder_example.shape[0], n_batches=positional_example_sample_size, input_example=input_example, n_components=n_components, ) ``` ``` px.scatter_3d( dr_encoder_df, x="DR_1", y="DR_2", z="input", # color='sample_idx', # symbol='type', # color="batch", color="batch_first_value", title="UMAP Embedding of Encoder Encoded Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.scatter( dr_encoder_df, x="input", y="DR_1", color="batch_first_value", ) ``` # NeuralODE for Univariate Time Series Forecasting In this notebook, we build a NeuralODE using pytorch to forecast \\(\\sin\\) function as a time series. ``` import dataclasses ``` ``` import math from functools import cached_property from typing import Dict, List, Tuple import lightning as L import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from lightning.pytorch.callbacks.early_stopping import EarlyStopping from loguru import logger from torch import nn from torch.utils.data import DataLoader, Dataset from torchdyn.core import NeuralODE from ts_dl_utils.datasets.pendulum import Pendulum, PendulumDataModule from ts_dl_utils.evaluation.evaluator import Evaluator from ts_dl_utils.naive_forecasters.last_observation import LastObservationForecaster ``` ## Data We create a dataset that models a damped pendulum. The pendulum is modelled as a damped harmonic oscillator, i.e., \\\[ \\theta(t) = \\theta(0) \\cos(2 \\pi t / p)\\exp(-\\beta t), \\\] where \\(\\theta(t)\\) is the angle of the pendulum at time \\(t\\). The period \\(p\\) is calculated using \\\[ p = 2 \\pi \\sqrt{L / g}, \\\] with \\(L\\) being the length of the pendulum and \\(g\\) being the surface gravity. ``` pen = Pendulum(length=100) ``` ``` df = pd.DataFrame(pen(10, 400, initial_angle=1, beta=0.001)) ``` Since the damping constant is very small, the data generated is mostly a sin wave. ``` _, ax = plt.subplots(figsize=(10, 6.18)) df.plot(x="t", y="theta", ax=ax) ``` ## Model In this section, we create the NeuralODE model. ``` @dataclasses.dataclass class TSNODEParams: """A dataclass to be served as our parameters for the model. :param hidden_widths: list of dimensions for the hidden layers """ hidden_widths: List[int] time_span: torch.Tensor class TSNODE(nn.Module): """NeuralODE for univaraite time series modeling. :param history_length: the length of the input history. :param horizon: the number of steps to be forecasted. :param ffn_params: the parameters for the NODE network. """ def __init__(self, history_length: int, horizon: int, model_params: TSNODEParams): super().__init__() self.model_params = model_params self.history_length = history_length self.horizon = horizon self.time_span = model_params.time_span self.regulate_input = nn.Linear( self.history_length, self.model_params.hidden_widths[0] ) self.hidden_layers = nn.Sequential( *[ self._linear_block(dim_in, dim_out) for dim_in, dim_out in zip( self.model_params.hidden_widths[:-1], self.model_params.hidden_widths[1:], ) ] ) self.regulate_output = nn.Linear( self.model_params.hidden_widths[-1], self.history_length ) self.network = nn.Sequential( *[self.regulate_input, self.hidden_layers, self.regulate_output] ) @property def node_config(self): return dataclasses.asdict(self.ffn_params) def _linear_block(self, dim_in, dim_out): return nn.Sequential(*[nn.Linear(dim_in, dim_out), nn.ReLU()]) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.network(x) ``` ## Training We use [lightning]() to train our model. ### Training Utilities ``` history_length_1_step = 100 horizon_1_step = 1 gap = 10 ``` We will build a few utilities 1. To be able to feed the data into our model, we build a class (`DataFrameDataset`) that converts the pandas dataframe into a Dataset for pytorch. 2. To make the lightning training code simpler, we will build a [LightningDataModule]() (`PendulumDataModule`) and a [LightningModule]() (`FFNForecaster`). ``` class NODEForecaster(L.LightningModule): def __init__(self, model: nn.Module): super().__init__() self.model = model self.neural_ode = NeuralODE( self.model.network, sensitivity="adjoint", solver="dopri5", atol_adjoint=1e-4, rtol_adjoint=1e-4, ) self.time_span = self.model.time_span self.horizon = self.model.horizon def configure_optimizers(self): optimizer = torch.optim.SGD(self.parameters(), lr=1e-3) return optimizer def training_step(self, batch, batch_idx): x, y = batch x = x.squeeze(-1).type(self.dtype) y = y.squeeze(-1).type(self.dtype) t_, y_hat = self.neural_ode(x, self.time_span) y_hat = y_hat[-1, ..., -self.horizon :] loss = nn.functional.mse_loss(y_hat, y) self.log_dict({"train_loss": loss}, prog_bar=True) return loss def validation_step(self, batch, batch_idx): x, y = batch x = x.squeeze(-1).type(self.dtype) y = y.squeeze(-1).type(self.dtype) t_, y_hat = self.neural_ode(x, self.time_span) y_hat = y_hat[-1, ..., -self.horizon :] loss = nn.functional.mse_loss(y_hat, y) self.log_dict({"val_loss": loss}, prog_bar=True) return loss def predict_step(self, batch, batch_idx): x, y = batch x = x.squeeze(-1).type(self.dtype) y = y.squeeze(-1).type(self.dtype) t_, y_hat = self.neural_ode(x, self.time_span) y_hat = y_hat[-1, ..., -self.horizon :] return x, y_hat def forward(self, x): x = x.squeeze(-1).type(self.dtype) t_, y_hat = self.neural_ode(x, self.time_span) y_hat = y_hat[-1, ..., -self.horizon :] return x, y_hat ``` ### Data, Model and Training #### DataModule ``` pdm_1_step = PendulumDataModule( history_length=history_length_1_step, horizon=horizon_1_step, dataframe=df[["theta"]], gap=gap, ) ``` #### LightningModule ``` ts_model_params_1_step = TSNODEParams( hidden_widths=[256], time_span=torch.linspace(0, 1, 101) ) ts_node_1_step = TSNODE( history_length=history_length_1_step, horizon=horizon_1_step, model_params=ts_model_params_1_step, ) ts_node_1_step ``` ``` node_forecaster_1_step = NODEForecaster(model=ts_node_1_step) ``` #### Trainer ``` logger_1_step = L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="neuralode_ts_1_step" ) trainer_1_step = L.Trainer( precision="32", max_epochs=10, min_epochs=5, callbacks=[ EarlyStopping(monitor="val_loss", mode="min", min_delta=1e-4, patience=2) ], logger=logger_1_step, ) ``` #### Fitting ``` trainer_1_step.fit(model=node_forecaster_1_step, datamodule=pdm_1_step) ``` #### Retrieving Predictions ``` predictions_1_step = trainer_1_step.predict( model=node_forecaster_1_step, datamodule=pdm_1_step ) ``` ### Naive Forecasters ``` trainer_naive_1_step = L.Trainer(precision="64") lobs_forecaster_1_step = LastObservationForecaster(horizon=horizon_1_step) lobs_1_step_predictions = trainer_naive_1_step.predict( model=lobs_forecaster_1_step, datamodule=pdm_1_step ) ``` ## Evaluations ``` evaluator_1_step = Evaluator(step=0) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator_1_step.y_true(dataloader=pdm_1_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_1_step.y(predictions_1_step), "r--", label="predictions") ax.plot(evaluator_1_step.y(lobs_1_step_predictions), "b-.", label="naive predictions") plt.legend() ``` To quantify the results, we compute a few metrics. ``` evaluator_1_step.metrics(predictions_1_step, pdm_1_step.predict_dataloader()) ``` ``` evaluator_1_step.metrics(lobs_1_step_predictions, pdm_1_step.predict_dataloader()) ``` ## Forecasting (horizon=3) ### Train a Model ``` history_length_m_step = 100 horizon_m_step = 3 ``` ``` pdm_m_step = PendulumDataModule( history_length=history_length_m_step, horizon=horizon_m_step, dataframe=df[["theta"]], gap=gap, ) ``` ``` ts_model_params_m_step = TSNODEParams( hidden_widths=[256], time_span=torch.linspace(0, 1, 101) ) ts_node_m_step = TSNODE( history_length=history_length_m_step, horizon=horizon_m_step, model_params=ts_model_params_m_step, ) ts_node_m_step ``` ``` node_forecaster_m_step = NODEForecaster(model=ts_node_m_step) ``` ``` logger_m_step = L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="neuralode_ts_m_step" ) trainer_m_step = L.Trainer( precision="32", max_epochs=10, min_epochs=5, callbacks=[ EarlyStopping(monitor="val_loss", mode="min", min_delta=1e-4, patience=2) ], logger=logger_m_step, ) ``` ``` trainer_m_step.fit(model=node_forecaster_m_step, datamodule=pdm_m_step) ``` ``` predictions_m_step = trainer_m_step.predict( model=node_forecaster_m_step, datamodule=pdm_m_step ) ``` ### Naive Forecaster ``` trainer_naive_m_step = L.Trainer(precision="64") lobs_forecaster_m_step = LastObservationForecaster(horizon=horizon_m_step) lobs_m_step_predictions = trainer_naive_m_step.predict( model=lobs_forecaster_m_step, datamodule=pdm_m_step ) ``` ### Evaluations ``` evaluator_m_step = Evaluator(step=2, gap=gap) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator_m_step.y_true(dataloader=pdm_m_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_m_step.y(predictions_m_step), "r--", label="predictions") ax.plot(evaluator_m_step.y(lobs_m_step_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) for i in np.arange(0, 1000, 120): evaluator_m_step.plot_one_sample(ax=ax, predictions=predictions_m_step, idx=i) ``` ``` evaluator_m_step.metrics(predictions_m_step, pdm_m_step.predict_dataloader()) ``` ``` evaluator_m_step.metrics(lobs_m_step_predictions, pdm_m_step.predict_dataloader()) ``` # Time Series Data Generation ``` import numpy as np import pandas as pd import plotly.express as px ``` ``` def profile_sin(t: np.ndarray, lambda_min: float, lambda_max: float) -> np.ndarray: """generate a sin wave profile for the expected number of visitors in every 10min for each hour during a day :param t: time in minutes :param lambda_min: minimum number of visitors :param lambda_max: maximum number of visitors """ amplitude = lambda_max - lambda_min t_rescaled = (t - t.min()) / t.max() * np.pi return amplitude * np.sin(t_rescaled) + lambda_min class KioskVisitors: """generate number of visitors for a kiosk store :param daily_profile: expectations of visitors in every 10min for each hour during a day """ def __init__(self, daily_profile: np.ndarray): self.daily_profile = daily_profile self.daily_segments = len(daily_profile) def __call__(self, n_days: int) -> pd.DataFrame: """generate number of visitors for n_days :param n_days: number of days to generate visitors """ visitors = np.concatenate( [np.random.poisson(self.daily_profile) for _ in range(n_days)] ) df = pd.DataFrame( { "visitors": visitors, "time": np.arange(len(visitors)), "expectation": np.tile(self.daily_profile, n_days), } ) return df ``` Create a sin profile ``` t = np.arange(0, 12 * 60 / 5, 1) daily_profile = profile_sin(t, lambda_min=0.5, lambda_max=10) ``` Generate a time series data representing the number of visitors to a Kiosk. ``` kiosk_visitors = KioskVisitors(daily_profile=daily_profile) ``` ``` df_visitors = kiosk_visitors(n_days=10) ``` ``` px.line( df_visitors, x="time", y=["visitors", "expectation"], ) ``` *Interactive Plotly figure: enable JavaScript to view it.* # TimeVAE Use VAE to generate time series data. In this example, we will train a VAE model to sinusoidal time series data. The overall structure of the model is shown below: ``` graph TD data["Time Series Chunks"] --> E[Encoder] E --> L[Latent Space] L --> D[Decoder] D --> gen["Generated Time Series Chunks"] ``` Reference: [https://github.com/wangyz1999/timeVAE-pytorch]() ``` import dataclasses ``` ``` from functools import cached_property from typing import Dict, List, Tuple import lightning as L import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from lightning.pytorch.callbacks.early_stopping import EarlyStopping from loguru import logger from torch import nn from torch.utils.data import DataLoader, Dataset from ts_dl_utils.datasets.pendulum import Pendulum ``` ## Data We will reuse our classic pendulum dataset. ``` pen = Pendulum(length=100) ``` ``` df = pd.DataFrame(pen(300, 30, initial_angle=1, beta=0.00001)) ``` ``` df["theta"] = df["theta"] + 2 ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) df.head(100).plot(x="t", y="theta", ax=ax) ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) df.plot(x="t", y="theta", ax=ax) ``` ``` ``` ![output]() ``` df ``` | | t | theta | | --- | --- | --- | | 0 | 0.000000 | 3.000000 | | 1 | 0.200607 | 2.998007 | | 2 | 0.401213 | 2.992075 | | 3 | 0.601820 | 2.982228 | | 4 | 0.802427 | 2.968505 | | ... | ... | ... | | 9995 | 2005.063647 | 2.778265 | | 9996 | 2005.264254 | 2.792591 | | 9997 | 2005.464861 | 2.803789 | | 9998 | 2005.665467 | 2.811815 | | 9999 | 2005.866074 | 2.816636 | 10000 rows × 2 columns ``` def time_delay_embed(df: pd.DataFrame, window_size: int) -> pd.DataFrame: """embed time series into a time delay embedding space Time column `t` is required in the input data frame. :param df: original time series data frame :param window_size: window size for the time delay embedding """ dfs_embedded = [] for i in df.rolling(window_size): i_t = i.t.iloc[0] dfs_embedded.append( pd.DataFrame(i.reset_index(drop=True)) .drop(columns=["t"]) .T.reset_index(drop=True) # .rename(columns={"index": "name"}) # .assign(t=i_t) ) df_embedded = pd.concat(dfs_embedded[window_size - 1 :]) return df_embedded ``` ``` time_delay_embed(df, 3) ``` | | 0 | 1 | 2 | | --- | --- | --- | --- | | 0 | 3.000000 | 2.998007 | 2.992075 | | 0 | 2.998007 | 2.992075 | 2.982228 | | 0 | 2.992075 | 2.982228 | 2.968505 | | 0 | 2.982228 | 2.968505 | 2.950961 | | 0 | 2.968505 | 2.950961 | 2.929665 | | ... | ... | ... | ... | | 0 | 2.740464 | 2.760867 | 2.778265 | | 0 | 2.760867 | 2.778265 | 2.792591 | | 0 | 2.778265 | 2.792591 | 2.803789 | | 0 | 2.792591 | 2.803789 | 2.811815 | | 0 | 2.803789 | 2.811815 | 2.816636 | 9998 rows × 3 columns ```` class TimeVAEDataset(Dataset): """A dataset from a pandas dataframe. For a given pandas dataframe, this generates a pytorch compatible dataset by sliding in time dimension. ```python ds = DataFrameDataset( dataframe=df, history_length=10, horizon=2 ) ``` :param dataframe: input dataframe with a DatetimeIndex. :param window_size: length of time series slicing chunks """ def __init__( self, dataframe: pd.DataFrame, window_size: int, ): super().__init__() self.dataframe = dataframe self.window_size = window_size self.dataframe_rows = len(self.dataframe) self.length = self.dataframe_rows - self.window_size + 1 def moving_slicing(self, idx: int) -> np.ndarray: return self.dataframe[idx : self.window_size + idx].values def _validate_dataframe(self) -> None: """Validate the input dataframe. - We require the dataframe index to be DatetimeIndex. - This dataset is null aversion. - Dataframe index should be sorted. """ if not isinstance( self.dataframe.index, pd.core.indexes.datetimes.DatetimeIndex ): raise TypeError( "Type of the dataframe index is not DatetimeIndex" f": {type(self.dataframe.index)}" ) has_na = self.dataframe.isnull().values.any() if has_na: logger.warning("Dataframe has null") has_index_sorted = self.dataframe.index.equals( self.dataframe.index.sort_values() ) if not has_index_sorted: logger.warning("Dataframe index is not sorted") def __getitem__(self, idx: int) -> Tuple[np.ndarray, np.ndarray]: if isinstance(idx, slice): if (idx.start < 0) or (idx.stop >= self.length): raise IndexError(f"Slice out of range: {idx}") step = idx.step if idx.step is not None else 1 return [self.moving_slicing(i) for i in range(idx.start, idx.stop, step)] else: if idx >= self.length: raise IndexError("End of dataset") return self.moving_slicing(idx) def __len__(self) -> int: return self.length ```` ```` class TimeVAEDataModule(L.LightningDataModule): """Lightning DataModule for Time Series VAE. This data module takes a pandas dataframe and generates the corresponding dataloaders for training, validation and testing. ```python time_vae_dm_example = TimeVAEDataModule( window_size=30, dataframe=df[["theta"]], batch_size=32 ) ``` """ def __init__( self, window_size: int, dataframe: pd.DataFrame, test_fraction: float = 0.3, val_fraction: float = 0.1, batch_size: int = 32, num_workers: int = 0, ): super().__init__() self.window_size = window_size self.batch_size = batch_size self.dataframe = dataframe self.test_fraction = test_fraction self.val_fraction = val_fraction self.num_workers = num_workers self.train_dataset, self.val_dataset = self.split_train_val( self.train_val_dataset ) @cached_property def df_length(self): return len(self.dataframe) @cached_property def df_test_length(self): return int(self.df_length * self.test_fraction) @cached_property def df_train_val_length(self): return self.df_length - self.df_test_length @cached_property def train_val_dataframe(self): return self.dataframe.iloc[: self.df_train_val_length] @cached_property def test_dataframe(self): return self.dataframe.iloc[self.df_train_val_length :] @cached_property def train_val_dataset(self): return TimeVAEDataset( dataframe=self.train_val_dataframe, window_size=self.window_size, ) @cached_property def test_dataset(self): return TimeVAEDataset( dataframe=self.test_dataframe, window_size=self.window_size, ) def split_train_val(self, dataset: Dataset): return torch.utils.data.random_split( dataset, [1 - self.val_fraction, self.val_fraction] ) def train_dataloader(self): return DataLoader( dataset=self.train_dataset, batch_size=self.batch_size, shuffle=True, num_workers=self.num_workers, persistent_workers=(True if self.num_workers > 0 else False), ) def test_dataloader(self): return DataLoader( dataset=self.test_dataset, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers, ) def val_dataloader(self): return DataLoader( dataset=self.val_dataset, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers, persistent_workers=(True if self.num_workers > 0 else False), ) def predict_dataloader(self): return DataLoader( dataset=self.test_dataset, batch_size=len(self.test_dataset), shuffle=False ) ```` ``` time_vae_dm_example = TimeVAEDataModule( window_size=30, dataframe=df[["theta"]], batch_size=32 ) ``` ``` len(list(time_vae_dm_example.train_dataloader())) ``` ``` list(time_vae_dm_example.train_dataloader())[0].shape ``` ``` 197 ``` ## Model ``` @dataclasses.dataclass class VAEParams: """Parameters for VAEEncoder and VAEDecoder :param hidden_layer_sizes: list of hidden layer sizes :param latent_size: latent space dimension :param sequence_length: input sequence length :param n_features: number of features """ hidden_layer_sizes: List[int] latent_size: int sequence_length: int n_features: int = 1 @cached_property def data_size(self) -> int: """The dimension of the input data when flattened. """ return self.sequence_length * self.n_features def asdict(self) -> dict: return dataclasses.asdict(self) ``` ``` class VAEMLPEncoder(nn.Module): """MLP Encoder of TimeVAE""" def __init__(self, params: VAEParams): super().__init__() self.params = params encode_layer_sizes = [self.params.data_size] + self.params.hidden_layer_sizes self.layers_used_to_encode = [ self._linear_block(size_in, size_out) for size_in, size_out in zip( encode_layer_sizes[:-1], encode_layer_sizes[1:] ) ] self.encode = nn.Sequential(*self.layers_used_to_encode) encoded_size = self.params.hidden_layer_sizes[-1] self.z_mean_layer = nn.Linear(encoded_size, self.params.latent_size) self.z_log_var_layer = nn.Linear(encoded_size, self.params.latent_size) def forward( self, x: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: batch_size, _, _ = x.size() x = x.transpose(1, 2) x = self.encode(x) z_mean = self.z_mean_layer(x) z_log_var = self.z_log_var_layer(x) epsilon = torch.randn( batch_size, self.params.n_features, self.params.latent_size ).type_as(x) z = z_mean + torch.exp(0.5 * z_log_var) * epsilon return z_mean, z_log_var, z def _linear_block(self, size_in: int, size_out: int) -> nn.Module: return nn.Sequential(*[nn.Linear(size_in, size_out), nn.ReLU()]) ``` ```` class VAEEncoder(nn.Module): """Encoder of TimeVAE ```python encoder = VAEEncoder( VAEParams( hidden_layer_sizes=[40, 30], latent_size=10, sequence_length=50 ) ) ``` :param params: parameters for the encoder """ def __init__(self, params: VAEParams): super().__init__() self.params = params self.hparams = params.asdict() encode_layer_sizes = [self.params.n_features] + self.params.hidden_layer_sizes self.layers_used_to_encode = [ self._conv_block(size_in, size_out) for size_in, size_out in zip( encode_layer_sizes[:-1], encode_layer_sizes[1:] ) ] + [nn.Flatten()] self.encode = nn.Sequential(*self.layers_used_to_encode) encoded_size = self.cal_conv1d_output_dim() * self.params.hidden_layer_sizes[-1] self.z_mean_layer = nn.Linear(encoded_size, self.params.latent_size) self.z_log_var_layer = nn.Linear(encoded_size, self.params.latent_size) def forward( self, x: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: batch_size, _, _ = x.size() x = x.transpose(1, 2) x = self.encode(x) z_mean = self.z_mean_layer(x).view( batch_size, self.params.n_features, self.params.latent_size ) z_log_var = self.z_log_var_layer(x).view( batch_size, self.params.n_features, self.params.latent_size ) epsilon = torch.randn( batch_size, self.params.n_features, self.params.latent_size ).type_as(x) z = z_mean + torch.exp(0.5 * z_log_var) * epsilon return z_mean, z_log_var, z def _linear_block(self, size_in: int, size_out: int) -> nn.Module: return nn.Sequential(*[nn.Linear(size_in, size_out), nn.ReLU()]) def _conv_block(self, size_in: int, size_out: int) -> nn.Module: return nn.Sequential( *[ nn.Conv1d(size_in, size_out, kernel_size=3, stride=2, padding=1), nn.ReLU(), ] ) def cal_conv1d_output_dim(self) -> int: """the output dimension of all the Conv1d layers""" output_size = self.params.sequence_length * self.params.n_features for l in self.layers_used_to_encode: if l._get_name() == "Conv1d": output_size = self._conv1d_output_dim(l, output_size) elif l._get_name() == "Sequential": for l2 in l: if l2._get_name() == "Conv1d": output_size = self._conv1d_output_dim(l2, output_size) return output_size def _conv1d_output_dim(self, layer: nn.Module, input_size: int) -> int: """Formula to calculate the output size of Conv1d layer """ return ( (input_size + 2 * layer.padding[0] - layer.kernel_size[0]) // layer.stride[0] ) + 1 ```` ``` mlp_encoder = VAEMLPEncoder( VAEParams(hidden_layer_sizes=[40, 30], latent_size=10, sequence_length=50) ) [i.size() for i in mlp_encoder(torch.ones(32, 50, 1))], mlp_encoder( torch.ones(32, 50, 1) )[-1] ``` ``` encoder = VAEEncoder( VAEParams(hidden_layer_sizes=[40, 30], latent_size=10, sequence_length=50) ) [i.size() for i in encoder(torch.ones(32, 50, 1))], encoder(torch.ones(32, 50, 1))[-1] ``` ``` ([torch.Size([32, 1, 10]), torch.Size([32, 1, 10]), torch.Size([32, 1, 10])], tensor([[[ 0.7512, -0.2464, -1.5799, -0.3591, 0.3991, 0.8255, -0.6925, -0.2539, 0.1998, -0.1732]], [[-0.1898, 0.6519, 1.3573, 0.4369, -0.7016, -0.2748, -0.3117, 1.2254, 1.2868, -1.4186]], [[-0.7966, -0.9899, -0.9354, 1.0457, -1.8151, 0.9798, -0.4217, 0.4817, 0.6745, -1.1424]], [[ 0.7722, 1.0069, -0.1242, -0.1579, 3.1850, 0.3993, 1.6327, -2.2345, 0.8184, -1.8291]], [[ 0.6430, -0.5761, 0.9650, 1.1978, -0.0064, -1.2288, 0.2022, 1.5347, -1.2524, 1.2249]], [[-0.2916, 0.6617, -2.6156, -0.4596, 0.4995, 0.2771, -1.0398, 1.6406, -0.5922, -0.8694]], [[-0.7358, -0.6580, 0.4102, 1.0043, -1.1620, 1.7000, 0.6870, -2.5108, 1.3517, -1.2280]], [[-2.0802, -0.0234, -0.7984, 0.7578, 0.8384, -0.6166, 1.0604, -0.2086, 0.3403, -0.2937]], [[ 1.5776, 0.2911, -0.3327, -0.5813, -2.0566, 1.2946, -0.4778, -1.2812, -0.9236, 0.4816]], [[ 0.3073, 0.1833, -1.0332, -0.9702, -0.1414, -0.3407, -0.4733, 0.0359, -0.9915, 0.6481]], [[ 0.8189, 0.8177, -1.5599, 0.8721, -0.0073, -0.3176, 0.9012, 0.9449, 0.5305, 0.8372]], [[-1.2151, -0.1610, -0.7059, 0.9138, 1.2397, 1.2807, -0.5464, -0.9129, 1.5476, -1.7536]], [[ 1.4121, -1.0689, -2.2029, 0.1702, 2.0124, 0.1258, -0.2963, -1.5757, 0.9311, -0.3869]], [[-1.7114, 0.0985, 1.3061, -0.3364, 0.9112, 1.3963, 0.7253, 1.1977, -0.2153, -0.2129]], [[-0.0213, -1.7831, 0.0819, -1.6534, -0.0161, 0.6107, -0.1698, 1.0649, -2.1362, 0.1544]], [[-1.6537, 0.3799, 0.6110, -0.2150, 1.5642, -1.3898, -0.6645, 0.1034, -1.9392, -0.7975]], [[-2.3527, -0.9559, -0.0141, 0.0087, -0.6443, -1.2371, 0.3701, 0.3806, -0.3413, -0.1965]], [[ 0.3955, 1.0094, -0.0092, -1.3375, 1.2194, -0.2048, -0.0285, -0.6014, -0.4264, 0.7233]], [[-0.7148, 1.4312, 0.1843, -0.5086, -0.6581, -0.3653, -0.7701, -0.5338, -0.1859, -0.7277]], [[-0.0872, 0.5067, -1.7811, -1.2165, 0.7887, 0.9671, -0.8803, -0.8274, 0.5897, 0.9491]], [[ 1.4125, 1.0227, -1.7007, 0.2469, 0.8499, 0.5016, 0.1287, -1.9992, -1.1804, 0.1232]], [[-0.8195, 0.3970, -0.1237, 0.3717, -0.2569, -1.0386, 0.3947, 0.0796, -0.6385, -1.2369]], [[-0.8912, 0.0222, 0.1747, -0.0088, -1.7169, -1.2536, -0.7857, 0.1664, 0.4925, -0.2927]], [[ 0.0163, 0.4311, -0.4547, 0.3656, -0.1896, -0.0171, 0.3149, 0.7186, 0.1870, -1.0573]], [[-0.5779, -1.1715, -0.1330, 0.6739, -1.2915, -2.6458, 0.5481, -1.4053, 0.2551, -1.8555]], [[-0.5961, -0.2198, -0.6367, -1.1569, 0.3316, -0.2596, -0.1730, 0.0328, 1.1898, 0.9066]], [[ 0.2193, -0.2441, 1.6414, -1.4026, -0.5100, -0.5528, -3.2889, -1.3575, 0.1371, 0.1426]], [[-0.8817, 0.4769, -0.5507, 0.6523, 1.1832, -1.3601, -1.2146, -0.8998, 0.4066, -1.2781]], [[-1.7669, -0.5484, -0.5710, -1.3032, -0.6533, -0.1837, 0.1647, 0.0847, 0.6987, -1.9335]], [[ 0.9263, 0.4973, 0.2373, -0.4195, -1.3269, -0.6560, 0.1802, 0.5625, -0.2468, -1.2317]], [[-0.1505, -0.5553, 0.7748, 0.6992, 1.1973, -0.6109, 0.6687, -0.6004, -0.1196, -0.6409]], [[ 0.2727, 0.3247, -1.4497, 0.1855, 1.1862, 0.3328, -0.6967, 1.2210, -0.7328, -0.1885]]], grad_fn=)) ``` ```` class VAEDecoder(nn.Module): """Decoder of TimeVAE ```python decoder = VAEDecoder( VAEParams( hidden_layer_sizes=[30, 40], latent_size=10, sequence_length=50, ) ) ``` :param params: parameters for the decoder """ def __init__(self, params: VAEParams): super().__init__() self.params = params self.hparams = params.asdict() decode_layer_sizes = ( [self.params.latent_size] + self.params.hidden_layer_sizes + [self.params.data_size] ) self.decode = nn.Sequential( *[ self._linear_block(size_in, size_out) for size_in, size_out in zip( decode_layer_sizes[:-1], decode_layer_sizes[1:] ) ] ) def forward(self, z: torch.Tensor) -> torch.Tensor: output = self.decode(z) return output.view(-1, self.params.sequence_length, self.params.n_features) def _linear_block(self, size_in: int, size_out: int) -> nn.Module: """create linear block based on the specified sizes""" return nn.Sequential(*[nn.Linear(size_in, size_out), nn.Softplus()]) ```` ``` decoder = VAEDecoder( VAEParams(hidden_layer_sizes=[30, 40], latent_size=10, sequence_length=50) ) decoder(torch.ones(32, 1, 10)).size() ``` ``` torch.Size([32, 50, 1]) ``` ``` class VAE(nn.Module): """VAE model with encoder and decoder :param encoder: encoder module :param decoder: decoder module """ def __init__(self, encoder: nn.Module, decoder: nn.Module): super().__init__() self.encoder = encoder self.decoder = decoder self.hparams = { **{f"encoder_{k}": v for k, v in self.encoder.hparams.items()}, **{f"decoder_{k}": v for k, v in self.decoder.hparams.items()}, } def forward( self, x: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: z_mean, z_log_var, z = self.encoder(x) x_reconstructed = self.decoder(z) return x_reconstructed, z_mean, z_log_var ``` ``` class VAEModel(L.LightningModule): """VAE model using VAEEncoder, VAEDecoder, and VAE :param model: VAE model :param reconstruction_weight: weight for the reconstruction loss :param learning_rate: learning rate for the optimizer :param scheduler_max_epochs: maximum epochs for the scheduler """ def __init__( self, model: VAE, reconstruction_weight: float = 1.0, learning_rate: float = 1e-3, scheduler_max_epochs: int = 10000, ): super().__init__() self.model = model self.reconstruction_weight = reconstruction_weight self.learning_rate = learning_rate self.scheduler_max_epochs = scheduler_max_epochs self.hparams.update( { **model.hparams, **{ "reconstruction_weight": reconstruction_weight, "learning_rate": learning_rate, "scheduler_max_epochs": scheduler_max_epochs, }, } ) self.save_hyperparameters(self.hparams) def forward(self, x): return self.model(x) def training_step(self, batch: torch.Tensor, batch_idx: int) -> torch.Tensor: batch_reconstructed, z_mean, z_log_var = self.model(batch) loss_total, loss_reconstruction, loss_kl = self.loss( x=batch, x_reconstructed=batch_reconstructed, z_mean=z_mean, z_log_var=z_log_var, ) self.log_dict( { "train_loss_total": loss_total, "train_loss_reconstruction": loss_reconstruction, "train_loss_kl": loss_kl, } ) return loss_total def validation_step(self, batch: torch.Tensor, batch_idx: int) -> torch.Tensor: batch_reconstructed, z_mean, z_log_var = self.model(batch) loss_total, loss_reconstruction, loss_kl = self.loss( x=batch, x_reconstructed=batch_reconstructed, z_mean=z_mean, z_log_var=z_log_var, ) self.log_dict( { "val_loss_total": loss_total, "val_loss_reconstruction": loss_reconstruction, "val_loss_kl": loss_kl, } ) return loss_total def test_step(self, batch: torch.Tensor, batch_idx: int) -> torch.Tensor: batch_reconstructed, z_mean, z_log_var = self.model(batch) loss_total, loss_reconstruction, loss_kl = self.loss( x=batch, x_reconstructed=batch_reconstructed, z_mean=z_mean, z_log_var=z_log_var, ) self.log_dict( { "test_loss_total": loss_total, "test_loss_reconstruction": loss_reconstruction, "test_loss_kl": loss_kl, } ) return loss_total def loss( self, x: torch.Tensor, x_reconstructed: torch.Tensor, z_log_var: torch.Tensor, z_mean: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: loss_reconstruction = self.reconstruction_loss(x, x_reconstructed) loss_kl = -0.5 * torch.sum(1 + z_log_var - z_mean**2 - z_log_var.exp()) loss_total = self.reconstruction_weight * loss_reconstruction + loss_kl return ( loss_total / x.size(0), loss_reconstruction / x.size(0), loss_kl / x.size(0), ) def reconstruction_loss( self, x: torch.Tensor, x_reconstructed: torch.Tensor ) -> torch.Tensor: r"""Reconstruction loss for VAE. $$ \sum_{i=1}^{N} (x_i - x_{reconstructed_i})^2 + \sum_{i=1}^{N} (\mu_i - \mu_{reconstructed_i})^2 $$ """ loss = torch.sum((x - x_reconstructed) ** 2) + torch.sum( (torch.mean(x, dim=1) - torch.mean(x_reconstructed, dim=1)) ** 2 ) return loss def configure_optimizers(self) -> dict: optimizer = torch.optim.SGD(self.parameters(), lr=self.learning_rate) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( optimizer, T_max=self.scheduler_max_epochs ) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": scheduler, "monitor": "train_loss", "interval": "step", "frequency": 1, }, } ``` # Training ``` window_size = 24 max_epochs = 2000 time_vae_dm = TimeVAEDataModule( window_size=window_size, dataframe=df[["theta"]], batch_size=32 ) ``` ``` vae = VAE( encoder=VAEEncoder( VAEParams( hidden_layer_sizes=[200, 100, 50], latent_size=8, sequence_length=window_size, ) ), decoder=VAEDecoder( VAEParams( hidden_layer_sizes=[30, 50, 100], latent_size=8, sequence_length=window_size ) ), ) vae_model = VAEModel( vae, reconstruction_weight=3, scheduler_max_epochs=max_epochs * len(time_vae_dm.train_dataloader()), ) ``` ``` trainer = L.Trainer( precision="64", max_epochs=max_epochs, min_epochs=5, callbacks=[ EarlyStopping( monitor="val_loss_total", mode="min", min_delta=1e-10, patience=10 ) ], logger=L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="time_vae_naive" ), ) ``` ``` GPU available: True (mps), used: True TPU available: False, using: 0 TPU cores IPU available: False, using: 0 IPUs HPU available: False, using: 0 HPUs ``` ``` trainer.fit(model=vae_model, datamodule=time_vae_dm) ``` ## Fitted Model ``` IS_RELOAD = True ``` ``` if IS_RELOAD: checkpoint_path = "lightning_logs/time_vae_naive/version_29/checkpoints/epoch=1999-step=354000.ckpt" vae_model_reloaded = VAEModel.load_from_checkpoint(checkpoint_path, model=vae) else: vae_model_reloaded = vae_model ``` ``` for pred_batch in time_vae_dm.predict_dataloader(): print(pred_batch.size()) i_pred = vae_model_reloaded.model(pred_batch.float().cuda()) break ``` ``` i_pred[0].size() ``` ``` import matplotlib.pyplot as plt ``` ``` _, ax = plt.subplots() element = 4 ax.plot(pred_batch.detach().numpy()[element, :, 0]) ax.plot(i_pred[0].cpu().detach().numpy()[element, :, 0], "x-") ``` Data generation using the decoder. ``` sampling_z = torch.randn( pred_batch.size(0), vae_model_reloaded.model.encoder.params.latent_size ).type_as(vae_model_reloaded.model.encoder.z_mean_layer.weight) generated_samples_x = ( vae_model_reloaded.model.decoder(sampling_z).cpu().detach().numpy().squeeze() ) ``` ``` generated_samples_x.shape ``` ``` _, ax = plt.subplots() for i in range(min(len(generated_samples_x), 4)): ax.plot(generated_samples_x[i, :], "x-") ``` ``` from openTSNE import TSNE ``` ``` n_tsne_samples = 100 ``` ``` original_samples = pred_batch.cpu().detach().numpy().squeeze()[:n_tsne_samples] original_samples.shape ``` ``` tsne = TSNE( perplexity=30, metric="euclidean", n_jobs=8, random_state=42, verbose=True, ) ``` ``` original_samples_embedding = tsne.fit(original_samples) ``` ``` generated_samples_x[:n_tsne_samples] ``` ``` generated_samples_embedding = original_samples_embedding.transform( generated_samples_x[:n_tsne_samples] ) ``` ``` fig, ax = plt.subplots(figsize=(7, 7)) ax.scatter( original_samples_embedding[:, 0], original_samples_embedding[:, 1], color="black", marker=".", label="original", ) ax.scatter( generated_samples_embedding[:, 0], generated_samples_embedding[:, 1], color="red", marker="x", label="generated", ) ax.set_title("t-SNE of original and generated samples") ax.set_xlabel("t-SNE 1") ax.set_ylabel("t-SNE 2") ``` ## Investigation of Embeddings ``` from pathlib import Path import numpy as np import pandas as pd import plotly.express as px from torch.utils.data import DataLoader from torchdr import PCA, TSNE, UMAP from ts_dl_utils.datasets.dataset import DataFrameDataset ``` ``` vae_model_reloaded ``` ``` def embedding_extractor(forecaster: VAEModel, x: torch.Tensor) -> tuple[torch.Tensor]: """compute the embeddings based on the input :param forecaster: the trained forecaster :param x: input historical time series, """ forecaster.model.to(x.device) z_mean, z_log_var, z = forecaster.model.encoder( x.type_as(forecaster.model.encoder.z_mean_layer.weight) ) return z_mean, z_log_var, z ``` ``` investigation_dl = DataLoader( dataset=DataFrameDataset( dataframe=df[["theta"]], history_length=window_size, horizon=1, gap=0 ), batch_size=400, shuffle=False, ) investigation_dl ``` ``` input_example = list(investigation_dl)[0][0] input_example.shape ``` ``` z_mean_example, z_log_var_example, z_example = embedding_extractor( vae_model_reloaded, input_example ) z_example.shape ``` ``` (z_example.shape, z_mean_example.shape, z_log_var_example.shape) ``` ``` n_components = 3 dr_input_result = TSNE( # dr_input_result = PCA( # n_neighbors=30, backend='torch', perplexity=30, n_components=n_components, ).fit_transform(input_example.detach().squeeze()) dr_input_result.shape ``` ``` dr_z_mean_result = TSNE( # dr_z_result = PCA( # n_neighbors=30, backend='torch', # perplexity=30, n_components=n_components ).fit_transform( # z_example.detach().squeeze() z_mean_example.detach().squeeze() ) dr_z_mean_result.shape ``` ``` input_example.detach().shape ``` ``` def create_embedding_dataframe( dr_result: torch.Tensor, n_batches: int, input_example: torch.Tensor, n_components: int, ) -> pd.DataFrame: dr_df = pd.DataFrame( dr_result.detach().numpy(), columns=[f"DR_{i+1}" for i in range(n_components)] ) dr_df["batch"] = sum( [[i] * (len(dr_df) // n_batches) for i in range(n_batches)], [] ) dr_df["sample_idx"] = list(range(len(dr_df) // n_batches)) * n_batches # dr_df["input"] = np.concatenate( # input_example[:n_batches].detach().numpy().astype("float32") # ) dr_df = dr_df.merge( pd.DataFrame( input_example[:n_batches].detach()[:, 0, 0].numpy(), columns=["batch_first_value"], ) .reset_index() .rename(columns={"index": "batch"}), how="left", on="batch", ) return dr_df ``` ``` dr_input_df = create_embedding_dataframe( dr_result=dr_input_result, n_batches=input_example.shape[0], input_example=input_example, n_components=n_components, ) ``` ``` px.scatter( dr_input_df, x="DR_1", y="DR_2", # z='DR_3', # z='batch_first_value', # color='sample_idx', # symbol='type', # color="batch", # color="DR_3", color="batch_first_value", title="Embedding of Input Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` dr_z_df = create_embedding_dataframe( dr_result=dr_z_mean_result, n_batches=z_example.shape[0], input_example=input_example, n_components=n_components, ) ``` ``` dr_z_df ``` ``` px.scatter( dr_z_df, x="DR_1", # y="batch_first_value", y="DR_2", # z='DR_3', # z='batch_first_value', # color='sample_idx', # symbol='type', # color="batch", # color="DR_2", color="batch_first_value", title="UMAP Embedding of Encoder Encoded Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.scatter( dr_z_df, x="DR_1", y="DR_2", # z='DR_3', # z='batch_first_value', # color='sample_idx', # symbol='type', # color="batch", # color="DR_3", color="batch_first_value", title="UMAP Embedding of Encoder Encoded Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.scatter_3d( dr_z_df, x="DR_1", y="DR_2", z="DR_3", # z='batch_first_value', # color='sample_idx', # symbol='type', # color="batch", color="batch_first_value", title="UMAP Embedding of Encoder Encoded Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.imshow(input_example.squeeze().T, aspect="auto") ``` ``` px.imshow(dr_input_result.T.detach().numpy(), aspect="auto") ``` ``` px.imshow(dr_z_mean_result.T.detach().numpy(), aspect="auto") ``` ``` px.imshow(dr_z_df[["DR_1", "DR_2", "DR_3"]].T, aspect="auto") ``` # Comparing Time Series with Each Other Time series data involves a time dimension, and it is not that intuitive to see the difference between two time series. In this notebook, We will show you how to compare time series with each other. ``` import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns ``` ``` from dtaidistance import dtw from dtaidistance import dtw_visualisation as dtwvis sns.set_theme() plt.rcParams.update( { "font.size": 18, # General font size "axes.titlesize": 20, # Title font size "axes.labelsize": 16, # Axis label font size "xtick.labelsize": 14, # X-axis tick label font size "ytick.labelsize": 14, # Y-axis tick label font size "legend.fontsize": 14, # Legend font size "figure.titlesize": 20, # Figure title font size } ) ``` # DTW To illustrate how DTW can be used to compare time series, we will use the following datasets: ``` t = np.arange(0, 20, 0.1) ts_original = np.sin(t) ``` We apply different transformations to the original time series. ``` ts_shifted = np.roll(ts_original, 10) ts_jitter = ts_original + np.random.normal(0, 0.1, len(ts_original)) ts_flipped = ts_original[::-1] ts_shortened = ts_original[::2] ts_raise_level = ts_original + 0.5 ts_outlier = ts_original + np.append(np.zeros(len(ts_original) - 1), [10]) ``` ``` df = pd.DataFrame( { "t": t, "original": ts_original, "shifted": ts_shifted, "jitter": ts_jitter, "flipped": ts_flipped, "shortened": np.pad( ts_shortened, (0, len(ts_original) - len(ts_shortened)), constant_values=0 ), "raise_level": ts_raise_level, "outlier": ts_outlier, } ) ``` ``` _, ax = plt.subplots() for s in df.columns[1:]: sns.lineplot(df, x="t", y=s, ax=ax, label=s) ``` ``` distances = { "series": df.columns[1:], } for s in df.columns[1:]: distances["dtw"] = distances.get("dtw", []) + [dtw.distance(df.original, df[s])] distances["euclidean"] = distances.get("euclidean", []) + [ np.linalg.norm(df.original - df[s]) ] _, ax = plt.subplots(figsize=(10, 6.18 * 2), nrows=2) pd.DataFrame(distances).set_index("series").plot.bar(ax=ax[0]) colors = sns.color_palette("husl", len(distances["series"])) pd.DataFrame(distances).plot.scatter(x="dtw", y="euclidean", ax=ax[1], c=colors, s=100) for i, txt in enumerate(distances["series"]): ax[1].annotate(txt, (distances["dtw"][i], distances["euclidean"][i]), fontsize=12) ax[1].legend(distances["series"], loc="best") ``` ``` def dtw_map(s1, s2, window=None): if window is None: window = len(s1) d, paths = dtw.warping_paths(s1, s2, window=window, psi=2) best_path = dtw.best_path(paths) return dtwvis.plot_warpingpaths(s1, s2, paths, best_path) ``` ``` dtw_map(df.original, df.jitter) ``` ``` for s in df.columns[1:]: fig, ax = dtw_map(df.original, df[s]) fig.suptitle(s, y=1.05) ``` # Dimension Reduction We embed the original time series into a time-delayed embedding space, then reduce the dimensionality of the embedded time series for visualizations. ``` def time_delay_embed(df: pd.DataFrame, window_size: int) -> pd.DataFrame: """embed time series into a time delay embedding space Time column `t` is required in the input data frame. :param df: original time series data frame :param window_size: window size for the time delay embedding """ dfs_embedded = [] for i in df.rolling(window_size): i_t = i.t.iloc[0] dfs_embedded.append( pd.DataFrame(i.reset_index(drop=True)) .drop(columns=["t"]) .T.reset_index() .rename(columns={"index": "name"}) .assign(t=i_t) ) df_embedded = pd.concat(dfs_embedded[window_size - 1 :]) return df_embedded ``` ``` df_embedded_2 = time_delay_embed(df, window_size=2) ``` ``` _, ax = plt.subplots() ( df_embedded_2.loc[df_embedded_2.name == "original"].plot.line( x=0, y=1, ax=ax, legend=False ) ) ( df_embedded_2.loc[df_embedded_2.name == "original"].plot.scatter( x=0, y=1, c="t", colormap="viridis", ax=ax ) ) ``` We choose a higher window size to track longer time dependency and for the dimension reduction methods to function properly. ``` df_embedded = time_delay_embed(df, window_size=5) ``` ## PCA ``` from sklearn.decomposition import PCA ``` ``` pca = PCA(n_components=2) ``` ``` df_embedded_pca = pd.concat( [ pd.DataFrame( pca.fit_transform( df_embedded.loc[df_embedded.name == n].drop(columns=["name", "t"]) ), columns=["pca_0", "pca_1"], ).assign(name=n) for n in df_embedded.name.unique() ] ) ``` ``` sns.scatterplot(data=df_embedded_pca, x="pca_0", y="pca_1", hue="name") ``` ``` _, ax = plt.subplots() sns.scatterplot( data=df_embedded_pca.loc[ df_embedded_pca.name.isin( ["original", "jitter", "flipped", "raise_level", "shifted", "shortened"] ) ], x="pca_0", y="pca_1", hue="name", style="name", ax=ax, ) ax.legend(loc="lower center", bbox_to_anchor=(0.5, -0.4), ncol=3) ``` ## t-SNE ``` from sklearn.manifold import TSNE ``` ``` t_sne = TSNE(n_components=2, learning_rate="auto", init="random", perplexity=3) ``` ``` df_embedded.name.unique() ``` ``` df_embedded_tsne = pd.concat( [ pd.DataFrame( t_sne.fit_transform( df_embedded.loc[df_embedded.name == n].drop(columns=["name", "t"]) ), columns=["tsne_0", "tsne_1"], ).assign(name=n) for n in df_embedded.name.unique() ] ) ``` ``` df_embedded_tsne.loc[df_embedded_tsne.name == "original"] ``` ``` sns.scatterplot(data=df_embedded_tsne, x="tsne_0", y="tsne_1", hue="name") ``` ``` sns.scatterplot( data=df_embedded_tsne.loc[ df_embedded_tsne.name.isin(["original", "jitter", "outlier"]) ], x="tsne_0", y="tsne_1", hue="name", ) ``` # TabPFN as Forecaster ``` import pandas as pd from ts_dl_utils.datasets.pendulum import Pendulum ``` ``` pen = Pendulum(length=100) ``` ``` df = pd.DataFrame(pen(300, 30, initial_angle=1, beta=0.00001)) ``` ``` def time_delay_embed(df: pd.DataFrame, window_size: int) -> pd.DataFrame: """embed time series into a time delay embedding space Time column `t` is required in the input data frame. :param df: original time series data frame :param window_size: window size for the time delay embedding """ dfs_embedded = [] for i in df.rolling(window_size): i_t = i.t.iloc[0] dfs_embedded.append( pd.DataFrame(i.reset_index(drop=True)) .drop(columns=["t"]) .T.reset_index(drop=True) # .rename(columns={"index": "name"}) # .assign(t=i_t) ) df_embedded = pd.concat(dfs_embedded[window_size - 1 :]) return df_embedded ``` ``` df = time_delay_embed(df, 11) ``` | | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 0 | 1.000000 | 0.978141 | 0.913533 | 0.809001 | 0.669113 | 0.499983 | 0.309005 | 0.104524 | \-0.104523 | \-0.308998 | \-0.499967 | | 0 | 0.978141 | 0.913533 | 0.809001 | 0.669113 | 0.499983 | 0.309005 | 0.104524 | \-0.104523 | \-0.308998 | \-0.499967 | \-0.669081 | | 0 | 0.913533 | 0.809001 | 0.669113 | 0.499983 | 0.309005 | 0.104524 | \-0.104523 | \-0.308998 | \-0.499967 | \-0.669081 | \-0.808952 | | 0 | 0.809001 | 0.669113 | 0.499983 | 0.309005 | 0.104524 | \-0.104523 | \-0.308998 | \-0.499967 | \-0.669081 | \-0.808952 | \-0.913466 | | 0 | 0.669113 | 0.499983 | 0.309005 | 0.104524 | \-0.104523 | \-0.308998 | \-0.499967 | \-0.669081 | \-0.808952 | \-0.913466 | \-0.978056 | | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | | 0 | \-0.941688 | \-0.921103 | \-0.860263 | \-0.761826 | \-0.630095 | \-0.470828 | \-0.290986 | \-0.098429 | 0.098428 | 0.290980 | 0.470812 | | 0 | \-0.921103 | \-0.860263 | \-0.761826 | \-0.630095 | \-0.470828 | \-0.290986 | \-0.098429 | 0.098428 | 0.290980 | 0.470812 | 0.630066 | | 0 | \-0.860263 | \-0.761826 | \-0.630095 | \-0.470828 | \-0.290986 | \-0.098429 | 0.098428 | 0.290980 | 0.470812 | 0.630066 | 0.761780 | | 0 | \-0.761826 | \-0.630095 | \-0.470828 | \-0.290986 | \-0.098429 | 0.098428 | 0.290980 | 0.470812 | 0.630066 | 0.761780 | 0.860200 | | 0 | \-0.630095 | \-0.470828 | \-0.290986 | \-0.098429 | 0.098428 | 0.290980 | 0.470812 | 0.630066 | 0.761780 | 0.860200 | 0.921023 | 8990 rows × 11 columns # Diffusion Model References: 1. [`pts/model/time_grad/time_grad_network.py`]() ``` import dataclasses from functools import cached_property import numpy as np import pandas as pd import plotly.express as px import torch import torch.nn as nn from loguru import logger ``` ``` @dataclasses.dataclass class DiffusionPocessParams: """Parameter that defines a diffusion process. :param steps: Number of steps in the diffusion process. :param beta: Beta parameter for the diffusion process. """ steps: int beta: float @cached_property def alpha(self) -> float: r"""$\alpha = 1 - \beta$""" return 1.0 - self.beta @cached_property def beta_by_step(self) -> np.ndarray: """the beta parameter for each step in the diffusion process. """ return np.array([self.beta] * self.steps) @cached_property def alpha_by_step(self) -> np.ndarray: """the alpha parameter for each step in the diffusion process.""" return np.array([self.alpha] * self.steps) class DiffusionProcess: """ Diffusion process. :param params: DiffusionParams that defines how the diffusion process works :param noise: noise tensor, shape is (batch_size, params.steps) """ def __init__( self, params: DiffusionPocessParams, noise: torch.Tensor, dtype: torch.dtype = torch.float32, ): self.params = params self.noise = noise self.dtype = dtype @cached_property def alpha_by_step(self) -> torch.Tensor: """The alpha parameter for each step in the diffusion process. """ return torch.tensor(self.params.alpha_by_step, dtype=self.dtype) def _forward_process_by_step(self, state: torch.Tensor, step: int) -> torch.Tensor: r"""Assuming that we know the noise at step $t$, $$ x(t) = \sqrt{\alpha(t)}x(t-1) + \sqrt{1 - \alpha(t)}\epsilon(t) $$ :param state: The state at step $t-1$. :param step: The current step $t$. :return: The state at step $t$. """ return ( torch.sqrt(self.alpha_by_step[step]) * state + torch.sqrt(1 - self.alpha_by_step[step]) * self.noise[:, step] ) def _inverse_process_by_step(self, state: torch.Tensor, step: int) -> torch.Tensor: r"""Assuming that we know the noise at step $t$, $$ x(t-1) = \frac{1}{\sqrt{\alpha(t)}} (x(t) - \sqrt{1 - \alpha(t)}\epsilon(t)) $$ """ return ( state - torch.sqrt(1 - self.alpha_by_step[step]) * self.noise[:, step] ) / torch.sqrt(self.alpha_by_step[step]) def gaussian_noise(n_var: int, length: int) -> torch.Tensor: """Generate a Gaussian noise tensor. :param n_var: Number of variables. :param length: Length of the tensor. """ return torch.normal(mean=0, std=1, size=(n_var, length)) ``` ``` diffusion_process_params = DiffusionPocessParams( steps=100, beta=0.005, # beta=0, ) diffusion_batch_size = 1000 # diffusion_batch_size = 2 noise = gaussian_noise(diffusion_batch_size, diffusion_process_params.steps) diffusion_process = DiffusionProcess(diffusion_process_params, noise=noise) ``` ``` # diffusion_initial_x = torch.sin( # torch.linspace(0, 1, diffusion_batch_size) # .reshape(diffusion_batch_size) # ) diffusion_initial_x = torch.rand(diffusion_batch_size) # diffusion_initial_x = ( # torch.distributions.Beta(torch.tensor([0.5]), torch.tensor([0.5])) # .sample((diffusion_batch_size, 1)) # .reshape(diffusion_batch_size) # ) diffusion_initial_x ``` ``` tensor([0.7536, 0.4834, 0.2725, 0.4402, 0.3182, 0.6672, 0.1673, 0.5404, 0.4067, 0.7054, 0.8827, 0.8709, 0.7129, 0.1326, 0.8437, 0.0955, 0.4977, 0.3243, 0.8288, 0.8126, 0.0969, 0.1552, 0.0496, 0.9418, 0.8736, 0.3177, 0.8175, 0.1994, 0.9418, 0.2020, 0.5799, 0.2483, 0.2041, 0.6654, 0.1592, 0.3804, 0.5947, 0.6441, 0.6036, 0.3260, 0.9430, 0.9195, 0.8601, 0.8360, 0.2365, 0.9118, 0.9763, 0.4900, 0.0756, 0.9563, 0.6160, 0.8516, 0.3618, 0.9157, 0.2769, 0.4257, 0.8229, 0.5218, 0.8965, 0.8164, 0.5145, 0.6978, 0.6188, 0.4195, 0.0356, 0.0889, 0.8554, 0.9192, 0.5285, 0.8589, 0.1101, 0.5923, 0.1385, 0.3004, 0.8923, 0.0815, 0.2056, 0.8347, 0.3738, 0.5608, 0.1239, 0.6954, 0.5872, 0.5123, 0.3754, 0.8145, 0.8538, 0.0713, 0.5971, 0.5287, 0.0624, 0.6684, 0.3870, 0.0232, 0.9381, 0.8042, 0.0024, 0.3759, 0.9874, 0.6877, 0.4573, 0.4705, 0.7036, 0.1097, 0.9186, 0.1192, 0.6941, 0.1958, 0.2448, 0.8155, 0.1737, 0.3155, 0.7732, 0.6115, 0.9586, 0.5085, 0.6261, 0.0438, 0.5883, 0.4588, 0.6946, 0.7486, 0.6464, 0.3928, 0.4213, 0.0606, 0.8127, 0.4440, 0.5071, 0.3382, 0.3160, 0.2012, 0.2459, 0.2496, 0.4612, 0.4446, 0.4209, 0.5457, 0.5051, 0.3283, 0.2671, 0.0124, 0.8184, 0.7729, 0.5773, 0.7450, 0.5006, 0.3567, 0.9014, 0.9247, 0.6198, 0.2146, 0.9892, 0.6337, 0.6458, 0.8652, 0.8936, 0.3417, 0.2023, 0.3670, 0.0434, 0.5316, 0.0500, 0.4267, 0.5302, 0.2976, 0.4130, 0.8654, 0.9823, 0.1026, 0.0530, 0.8817, 0.0374, 0.7322, 0.4900, 0.3551, 0.5620, 0.0782, 0.1717, 0.0239, 0.9409, 0.8226, 0.7411, 0.3194, 0.7940, 0.9687, 0.0305, 0.7016, 0.8890, 0.9251, 0.1848, 0.7994, 0.0170, 0.6316, 0.3225, 0.5723, 0.8267, 0.5019, 0.3198, 0.8215, 0.0337, 0.5008, 0.4958, 0.7470, 0.4909, 0.3167, 0.7920, 0.5701, 0.7806, 0.9546, 0.0487, 0.1813, 0.8509, 0.1086, 0.3642, 0.7095, 0.3045, 0.1956, 0.3918, 0.7228, 0.9352, 0.7958, 0.9975, 0.4344, 0.6057, 0.0816, 0.0443, 0.3103, 0.9619, 0.8549, 0.5220, 0.4791, 0.4700, 0.9056, 0.7867, 0.8700, 0.2858, 0.2602, 0.0282, 0.2518, 0.8653, 0.8875, 0.0959, 0.6682, 0.1124, 0.4574, 0.9996, 0.3322, 0.3931, 0.3487, 0.7859, 0.8433, 0.9569, 0.2757, 0.4772, 0.4649, 0.9852, 0.9583, 0.3092, 0.6877, 0.1214, 0.6203, 0.0752, 0.2042, 0.8638, 0.8602, 0.9755, 0.7772, 0.9566, 0.0891, 0.5076, 0.0258, 0.0139, 0.4874, 0.9799, 0.1189, 0.3678, 0.1556, 0.8836, 0.6997, 0.3204, 0.3730, 0.6267, 0.3077, 0.4801, 0.4581, 0.9421, 0.0842, 0.5335, 0.2302, 0.3325, 0.4903, 0.9428, 0.5619, 0.3496, 0.3679, 0.9995, 0.8568, 0.6528, 0.1565, 0.9848, 0.5568, 0.5691, 0.4950, 0.3927, 0.2281, 0.8991, 0.1647, 0.9562, 0.0798, 0.5997, 0.6985, 0.5622, 0.0132, 0.6827, 0.5300, 0.2692, 0.1643, 0.7261, 0.0379, 0.9980, 0.8012, 0.3453, 0.1507, 0.7441, 0.8861, 0.0742, 0.0168, 0.3470, 0.9566, 0.8102, 0.6357, 0.3327, 0.2776, 0.0795, 0.4942, 0.2863, 0.8840, 0.3729, 0.7207, 0.7621, 0.5595, 0.9594, 0.8560, 0.7084, 0.5003, 0.5694, 0.1013, 0.1138, 0.8116, 0.5994, 0.6108, 0.7928, 0.1270, 0.8380, 0.0703, 0.4886, 0.0367, 0.5597, 0.7508, 0.8121, 0.9413, 0.1954, 0.2135, 0.2518, 0.6269, 0.2142, 0.2945, 0.9089, 0.4660, 0.5189, 0.5268, 0.4324, 0.5898, 0.4311, 0.9745, 0.0329, 0.9623, 0.6344, 0.1826, 0.5811, 0.8672, 0.8200, 0.5668, 0.1688, 0.4302, 0.3826, 0.3359, 0.3025, 0.3504, 0.1921, 0.6246, 0.3486, 0.1785, 0.4811, 0.7434, 0.0558, 0.7108, 0.4147, 0.0507, 0.9207, 0.8845, 0.6140, 0.9616, 0.3362, 0.9684, 0.2572, 0.6240, 0.0916, 0.9795, 0.9427, 0.9679, 0.5308, 0.2262, 0.1101, 0.9380, 0.6164, 0.3556, 0.6628, 0.1159, 0.5128, 0.8538, 0.8104, 0.8094, 0.9814, 0.2217, 0.2853, 0.4712, 0.3195, 0.4851, 0.7147, 0.9655, 0.0893, 0.6000, 0.1114, 0.0551, 0.0052, 0.1006, 0.7330, 0.6732, 0.1298, 0.5724, 0.1562, 0.2453, 0.6039, 0.3385, 0.2932, 0.4384, 0.5299, 0.2081, 0.3525, 0.0829, 0.5762, 0.1200, 0.3875, 0.1217, 0.4433, 0.9419, 0.0383, 0.7981, 0.3716, 0.6886, 0.8513, 0.3691, 0.4192, 0.9425, 0.8899, 0.7040, 0.8022, 0.9326, 0.3105, 0.6288, 0.8834, 0.8331, 0.0120, 0.7035, 0.2927, 0.5725, 0.2115, 0.8342, 0.8126, 0.1226, 0.6824, 0.6779, 0.3980, 0.3593, 0.9737, 0.3040, 0.4713, 0.9109, 0.2343, 0.7385, 0.1809, 0.6612, 0.4121, 0.8644, 0.3596, 0.2745, 0.8517, 0.2816, 0.6212, 0.0944, 0.5489, 0.8383, 0.5986, 0.0235, 0.3884, 0.7555, 0.5689, 0.5210, 0.1662, 0.1520, 0.0614, 0.8416, 0.8402, 0.7078, 0.7201, 0.3578, 0.4410, 0.7259, 0.3709, 0.6305, 0.1448, 0.7542, 0.5934, 0.5828, 0.0705, 0.9386, 0.3758, 0.9017, 0.6706, 0.9367, 0.3203, 0.2718, 0.1526, 0.6501, 0.7947, 0.8928, 0.7012, 0.6307, 0.0319, 0.8314, 0.5148, 0.7734, 0.9511, 0.6231, 0.9352, 0.7125, 0.8649, 0.2530, 0.8865, 0.3526, 0.2248, 0.5213, 0.2566, 0.9589, 0.4104, 0.9293, 0.8581, 0.6148, 0.5094, 0.6389, 0.1481, 0.6687, 0.1251, 0.4445, 0.1234, 0.7877, 0.4810, 0.4036, 0.4687, 0.1786, 0.7034, 0.0685, 0.0455, 0.6618, 0.7716, 0.3464, 0.0030, 0.6898, 0.7348, 0.0406, 0.0724, 0.5815, 0.6061, 0.0085, 0.0046, 0.5402, 0.8789, 0.8594, 0.5769, 0.6630, 0.5956, 0.6396, 0.3848, 0.9568, 0.9629, 0.5021, 0.4377, 0.3914, 0.2121, 0.1134, 0.5525, 0.5040, 0.0954, 0.1688, 0.0460, 0.1934, 0.0825, 0.9675, 0.9240, 0.9395, 0.4294, 0.0163, 0.4429, 0.6879, 0.3180, 0.1544, 0.2139, 0.9927, 0.1030, 0.5049, 0.7499, 0.1990, 0.1086, 0.3293, 0.7779, 0.1641, 0.8838, 0.2883, 0.6641, 0.3507, 0.8780, 0.3299, 0.4161, 0.5902, 0.3217, 0.8701, 0.3461, 0.8941, 0.7915, 0.3228, 0.0041, 0.2842, 0.8235, 0.7769, 0.7291, 0.4020, 0.5166, 0.5852, 0.3286, 0.3989, 0.4018, 0.6776, 0.4310, 0.9864, 0.3931, 0.5190, 0.9566, 0.0380, 0.6076, 0.0917, 0.7251, 0.3655, 0.8015, 0.2181, 0.1679, 0.7674, 0.8878, 0.7956, 0.0478, 0.9883, 0.5244, 0.1151, 0.2866, 0.1940, 0.8358, 0.5085, 0.4416, 0.4401, 0.3130, 0.3635, 0.0862, 0.5520, 0.4258, 0.3292, 0.5430, 0.6098, 0.6241, 0.1857, 0.2064, 0.3411, 0.4398, 0.3613, 0.7945, 0.3707, 0.3429, 0.3646, 0.6793, 0.7016, 0.5864, 0.5508, 0.6977, 0.8368, 0.4179, 0.4651, 0.6798, 0.2080, 0.6929, 0.8651, 0.3249, 0.4109, 0.0362, 0.3898, 0.0333, 0.8294, 0.1051, 0.1601, 0.3477, 0.2342, 0.4063, 0.2863, 0.2275, 0.6926, 0.4330, 0.8808, 0.2934, 0.6231, 0.7156, 0.3053, 0.3558, 0.3603, 0.3705, 0.5056, 0.3209, 0.9509, 0.0439, 0.4579, 0.9369, 0.7425, 0.0894, 0.9678, 0.0609, 0.5145, 0.8526, 0.9461, 0.0372, 0.6112, 0.1966, 0.7074, 0.1111, 0.9575, 0.3743, 0.5655, 0.8483, 0.1346, 0.9173, 0.7396, 0.5688, 0.1121, 0.5051, 0.7729, 0.2625, 0.3863, 0.6609, 0.3803, 0.8356, 0.2427, 0.0158, 0.9816, 0.1572, 0.3020, 0.6765, 0.4510, 0.8699, 0.4699, 0.1707, 0.8354, 0.5973, 0.7797, 0.8662, 0.9724, 0.2569, 0.5795, 0.5448, 0.2486, 0.6990, 0.6143, 0.2464, 0.1365, 0.5206, 0.5761, 0.4834, 0.4133, 0.2306, 0.1325, 0.2312, 0.7655, 0.8327, 0.6559, 0.8485, 0.4644, 0.7085, 0.7376, 0.8297, 0.8117, 0.3835, 0.0960, 0.6035, 0.1222, 0.0584, 0.5351, 0.3877, 0.0170, 0.6698, 0.4382, 0.1681, 0.8570, 0.2045, 0.7563, 0.8983, 0.6200, 0.2103, 0.1738, 0.3167, 0.6492, 0.3741, 0.8185, 0.8998, 0.9518, 0.7957, 0.5217, 0.9041, 0.0116, 0.3445, 0.0111, 0.0897, 0.7373, 0.1621, 0.7205, 0.8048, 0.9386, 0.0194, 0.7830, 0.5620, 0.9068, 0.5320, 0.4034, 0.5624, 0.6649, 0.6688, 0.4081, 0.0133, 0.0074, 0.3938, 0.5309, 0.1618, 0.3107, 0.1994, 0.4485, 0.9937, 0.6936, 0.6005, 0.2499, 0.7247, 0.1267, 0.1053, 0.8252, 0.2525, 0.8579, 0.8210, 0.0271, 0.5072, 0.7891, 0.4660, 0.6999, 0.4972, 0.4240, 0.9083, 0.2635, 0.9579, 0.9603, 0.8706, 0.0737, 0.5034, 0.3621, 0.5719, 0.4653, 0.8957, 0.4518, 0.0633, 0.8474, 0.9854, 0.5861, 0.5396, 0.9708, 0.9414, 0.2176, 0.1320, 0.8603, 0.5981, 0.9059, 0.6002, 0.7034, 0.0027, 0.9135, 0.3048, 0.5421, 0.4822, 0.4145, 0.7112, 0.9924, 0.4943, 0.0727, 0.0933, 0.3809, 0.4957, 0.3482, 0.0645, 0.4314, 0.0621, 0.5265, 0.5011, 0.2208, 0.7377, 0.1252, 0.1005, 0.9528, 0.6010, 0.5324, 0.3054, 0.5611, 0.5873, 0.1508, 0.8871, 0.7257, 0.3487, 0.5772, 0.0358, 0.8324, 0.6195, 0.5114, 0.2814, 0.5313, 0.1116, 0.7075, 0.0117, 0.5739, 0.2206, 0.2997, 0.9826, 0.8856, 0.9444, 0.4696, 0.0698, 0.2634, 0.5139, 0.8261, 0.9214, 0.8207, 0.0948, 0.0316, 0.0720, 0.3445, 0.5992, 0.5615, 0.8757, 0.9545, 0.3936, 0.5483, 0.6356, 0.9710, 0.8348, 0.1497, 0.0631, 0.2378, 0.3414, 0.2341, 0.1854, 0.7043, 0.0623, 0.4871, 0.2675, 0.3109, 0.5685, 0.4475, 0.7261, 0.9365, 0.8181, 0.4494, 0.1333, 0.2316, 0.7906, 0.7714, 0.1546, 0.7626, 0.0610, 0.3414, 0.3653, 0.1841]) ``` ## Forward process step by step ``` diffusion_steps_step_by_step = [diffusion_initial_x.detach().numpy()] for i in range(0, diffusion_process_params.steps): logger.info(f"step {i}") i_state = ( diffusion_process._forward_process_by_step( torch.from_numpy(diffusion_steps_step_by_step[-1]), step=i ) .detach() .numpy() ) logger.info(f"i_state {i_state[:2]}") diffusion_steps_step_by_step.append(i_state) ``` > [!NOTE] > > **Output (61 lines)** > > ``` > ... (80 earlier lines) > 2025-05-23 23:28:27.322 | INFO  | __main__::4 - step 40 > 2025-05-23 23:28:27.323 | INFO  | __main__::12 - i_state [ 1.029287 -0.42594546] > 2025-05-23 23:28:27.323 | INFO  | __main__::4 - step 41 > 2025-05-23 23:28:27.324 | INFO  | __main__::12 - i_state [ 0.92436755 -0.5229795 ] > ... (66 lines omitted) ... > 2025-05-23 23:28:27.354 | INFO  | __main__::12 - i_state [0.16661346 0.10516387] > 2025-05-23 23:28:27.354 | INFO  | __main__::4 - step 73 > 2025-05-23 23:28:27.355 | INFO  | __main__::12 - i_state [0.21610051 0.1195906 ] > 2025-05-23 23:28:27.355 | INFO  | __main__::4 - step 74 > 2025-05-23 23:28:27.356 | INFO  | __main__::12 - i_state [0.2297513 0.20118043] > 2025-05-23 23:28:27.356 | INFO  | __main__::4 - step 75 > 2025-05-23 23:28:27.356 | INFO  | __main__::12 - i_state [0.3925485 0.18007368] > 2025-05-23 23:28:27.357 | INFO  | __main__::4 - step 76 > 2025-05-23 23:28:27.358 | INFO  | __main__::12 - i_state [0.33611664 0.2712456 ] > 2025-05-23 23:28:27.358 | INFO  | __main__::4 - step 77 > 2025-05-23 23:28:27.358 | INFO  | __main__::12 - i_state [0.282507 0.1722632] > 2025-05-23 23:28:27.359 | INFO  | __main__::4 - step 78 > 2025-05-23 23:28:27.359 | INFO  | __main__::12 - i_state [0.24798693 0.26566544] > 2025-05-23 23:28:27.360 | INFO  | __main__::4 - step 79 > 2025-05-23 23:28:27.361 | INFO  | __main__::12 - i_state [0.2687943 0.17412242] > 2025-05-23 23:28:27.361 | INFO  | __main__::4 - step 80 > 2025-05-23 23:28:27.362 | INFO  | __main__::12 - i_state [0.3032606 0.10849762] > 2025-05-23 23:28:27.362 | INFO  | __main__::4 - step 81 > 2025-05-23 23:28:27.362 | INFO  | __main__::12 - i_state [ 0.3244555 -0.01832873] > 2025-05-23 23:28:27.363 | INFO  | __main__::4 - step 82 > 2025-05-23 23:28:27.363 | INFO  | __main__::12 - i_state [ 0.30285174 -0.07579676] > 2025-05-23 23:28:27.364 | INFO  | __main__::4 - step 83 > 2025-05-23 23:28:27.364 | INFO  | __main__::12 - i_state [ 0.38575527 -0.02965767] > 2025-05-23 23:28:27.365 | INFO  | __main__::4 - step 84 > 2025-05-23 23:28:27.365 | INFO  | __main__::12 - i_state [ 0.4670586 -0.14904383] > 2025-05-23 23:28:27.366 | INFO  | __main__::4 - step 85 > 2025-05-23 23:28:27.366 | INFO  | __main__::12 - i_state [ 0.62384367 -0.10881869] > 2025-05-23 23:28:27.367 | INFO  | __main__::4 - step 86 > 2025-05-23 23:28:27.367 | INFO  | __main__::12 - i_state [ 0.6041603 -0.11048407] > 2025-05-23 23:28:27.368 | INFO  | __main__::4 - step 87 > 2025-05-23 23:28:27.368 | INFO  | __main__::12 - i_state [ 0.5557305 -0.05675536] > 2025-05-23 23:28:27.369 | INFO  | __main__::4 - step 88 > 2025-05-23 23:28:27.369 | INFO  | __main__::12 - i_state [0.52949405 0.05057308] > 2025-05-23 23:28:27.370 | INFO  | __main__::4 - step 89 > 2025-05-23 23:28:27.370 | INFO  | __main__::12 - i_state [0.4567793 0.08728948] > 2025-05-23 23:28:27.370 | INFO  | __main__::4 - step 90 > 2025-05-23 23:28:27.371 | INFO  | __main__::12 - i_state [0.44138882 0.22891158] > 2025-05-23 23:28:27.371 | INFO  | __main__::4 - step 91 > 2025-05-23 23:28:27.372 | INFO  | __main__::12 - i_state [0.4815395 0.17549463] > 2025-05-23 23:28:27.373 | INFO  | __main__::4 - step 92 > 2025-05-23 23:28:27.373 | INFO  | __main__::12 - i_state [0.48461568 0.26058674] > 2025-05-23 23:28:27.373 | INFO  | __main__::4 - step 93 > 2025-05-23 23:28:27.374 | INFO  | __main__::12 - i_state [0.50137323 0.22013015] > 2025-05-23 23:28:27.378 | INFO  | __main__::4 - step 94 > 2025-05-23 23:28:27.394 | INFO  | __main__::12 - i_state [0.5260309 0.23809095] > 2025-05-23 23:28:27.402 | INFO  | __main__::4 - step 95 > 2025-05-23 23:28:27.407 | INFO  | __main__::12 - i_state [0.61677593 0.19635743] > 2025-05-23 23:28:27.407 | INFO  | __main__::4 - step 96 > 2025-05-23 23:28:27.408 | INFO  | __main__::12 - i_state [0.7224949 0.3069121] > 2025-05-23 23:28:27.409 | INFO  | __main__::4 - step 97 > 2025-05-23 23:28:27.409 | INFO  | __main__::12 - i_state [0.7774506 0.35429615] > 2025-05-23 23:28:27.410 | INFO  | __main__::4 - step 98 > 2025-05-23 23:28:27.410 | INFO  | __main__::12 - i_state [0.7941074 0.46556577] > 2025-05-23 23:28:27.411 | INFO  | __main__::4 - step 99 > 2025-05-23 23:28:27.411 | INFO  | __main__::12 - i_state [0.7216253 0.4826566] > ``` ``` px.histogram(diffusion_initial_x) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` px.histogram(diffusion_steps_step_by_step[0]) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` px.histogram(diffusion_steps_step_by_step[-1]) ``` *Interactive Plotly figure: enable JavaScript to view it.* ## Reverse step by step ``` diffusion_steps_reverse = [diffusion_steps_step_by_step[-1]] for i in range(diffusion_process_params.steps - 1, -1, -1): logger.info(f"step {i}") i_state = ( diffusion_process._inverse_process_by_step( torch.from_numpy(diffusion_steps_reverse[-1]), step=i ) .detach() .numpy() ) logger.info(f"i_state {i_state[:2]}") diffusion_steps_reverse.append(i_state) ``` > [!NOTE] > > **Output (61 lines)** > > ``` > ... (80 earlier lines) > 2025-05-23 23:28:27.846 | INFO  | __main__::4 - step 59 > 2025-05-23 23:28:27.847 | INFO  | __main__::12 - i_state [ 0.6670361 -0.16091785] > 2025-05-23 23:28:27.847 | INFO  | __main__::4 - step 58 > 2025-05-23 23:28:27.848 | INFO  | __main__::12 - i_state [ 0.69881296 -0.20470417] > ... (66 lines omitted) ... > 2025-05-23 23:28:27.880 | INFO  | __main__::12 - i_state [ 1.0571339 -0.18551737] > 2025-05-23 23:28:27.880 | INFO  | __main__::4 - step 26 > 2025-05-23 23:28:27.880 | INFO  | __main__::12 - i_state [ 0.98225445 -0.1815267 ] > 2025-05-23 23:28:27.881 | INFO  | __main__::4 - step 25 > 2025-05-23 23:28:27.881 | INFO  | __main__::12 - i_state [ 0.96144617 -0.24437277] > 2025-05-23 23:28:27.882 | INFO  | __main__::4 - step 24 > 2025-05-23 23:28:27.882 | INFO  | __main__::12 - i_state [ 0.94608957 -0.34820145] > 2025-05-23 23:28:27.882 | INFO  | __main__::4 - step 23 > 2025-05-23 23:28:27.883 | INFO  | __main__::12 - i_state [ 0.983971 -0.40669158] > 2025-05-23 23:28:27.883 | INFO  | __main__::4 - step 22 > 2025-05-23 23:28:27.894 | INFO  | __main__::12 - i_state [ 1.0061729 -0.4193306] > 2025-05-23 23:28:27.903 | INFO  | __main__::4 - step 21 > 2025-05-23 23:28:27.924 | INFO  | __main__::12 - i_state [ 1.0477937 -0.42483225] > 2025-05-23 23:28:27.924 | INFO  | __main__::4 - step 20 > 2025-05-23 23:28:27.925 | INFO  | __main__::12 - i_state [ 0.9093716 -0.32010102] > 2025-05-23 23:28:27.925 | INFO  | __main__::4 - step 19 > 2025-05-23 23:28:27.927 | INFO  | __main__::12 - i_state [ 0.8553466 -0.2648673] > 2025-05-23 23:28:27.928 | INFO  | __main__::4 - step 18 > 2025-05-23 23:28:27.936 | INFO  | __main__::12 - i_state [ 0.7316307 -0.32261997] > 2025-05-23 23:28:27.936 | INFO  | __main__::4 - step 17 > 2025-05-23 23:28:27.939 | INFO  | __main__::12 - i_state [ 0.7916906 -0.34114 ] > 2025-05-23 23:28:27.939 | INFO  | __main__::4 - step 16 > 2025-05-23 23:28:28.031 | INFO  | __main__::12 - i_state [ 0.6571835 -0.3395394] > 2025-05-23 23:28:28.032 | INFO  | __main__::4 - step 15 > 2025-05-23 23:28:28.034 | INFO  | __main__::12 - i_state [ 0.61165714 -0.27974993] > 2025-05-23 23:28:28.034 | INFO  | __main__::4 - step 14 > 2025-05-23 23:28:28.035 | INFO  | __main__::12 - i_state [ 0.5916003 -0.2851991] > 2025-05-23 23:28:28.036 | INFO  | __main__::4 - step 13 > 2025-05-23 23:28:28.041 | INFO  | __main__::12 - i_state [ 0.5109828 -0.21567155] > 2025-05-23 23:28:28.042 | INFO  | __main__::4 - step 12 > 2025-05-23 23:28:28.048 | INFO  | __main__::12 - i_state [ 0.5143276 -0.13229491] > 2025-05-23 23:28:28.049 | INFO  | __main__::4 - step 11 > 2025-05-23 23:28:28.051 | INFO  | __main__::12 - i_state [0.4948143 0.02763292] > 2025-05-23 23:28:28.052 | INFO  | __main__::4 - step 10 > 2025-05-23 23:28:28.057 | INFO  | __main__::12 - i_state [0.59509116 0.01449161] > 2025-05-23 23:28:28.057 | INFO  | __main__::4 - step 9 > 2025-05-23 23:28:28.061 | INFO  | __main__::12 - i_state [0.64988494 0.02659337] > 2025-05-23 23:28:28.062 | INFO  | __main__::4 - step 8 > 2025-05-23 23:28:28.067 | INFO  | __main__::12 - i_state [0.71278304 0.08999424] > 2025-05-23 23:28:28.068 | INFO  | __main__::4 - step 7 > 2025-05-23 23:28:28.071 | INFO  | __main__::12 - i_state [0.6505187 0.09535722] > 2025-05-23 23:28:28.073 | INFO  | __main__::4 - step 6 > 2025-05-23 23:28:28.077 | INFO  | __main__::12 - i_state [0.6169241 0.11197081] > 2025-05-23 23:28:28.078 | INFO  | __main__::4 - step 5 > 2025-05-23 23:28:28.083 | INFO  | __main__::12 - i_state [0.6403337 0.21329312] > 2025-05-23 23:28:28.085 | INFO  | __main__::4 - step 4 > 2025-05-23 23:28:28.088 | INFO  | __main__::12 - i_state [0.6899371 0.30957478] > 2025-05-23 23:28:28.088 | INFO  | __main__::4 - step 3 > 2025-05-23 23:28:28.089 | INFO  | __main__::12 - i_state [0.7610123 0.3232835] > 2025-05-23 23:28:28.090 | INFO  | __main__::4 - step 2 > 2025-05-23 23:28:28.091 | INFO  | __main__::12 - i_state [0.7597022 0.40743342] > 2025-05-23 23:28:28.092 | INFO  | __main__::4 - step 1 > 2025-05-23 23:28:28.093 | INFO  | __main__::12 - i_state [0.75221276 0.53379536] > 2025-05-23 23:28:28.093 | INFO  | __main__::4 - step 0 > 2025-05-23 23:28:28.094 | INFO  | __main__::12 - i_state [0.7535973 0.48336253] > ``` ``` px.histogram(diffusion_steps_reverse[0]) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` px.histogram(diffusion_steps_reverse[-1]) ``` *Interactive Plotly figure: enable JavaScript to view it.* ## Diffusion Distributions ``` df_diffusion_example = pd.DataFrame( {i: v for i, v in enumerate(diffusion_steps_step_by_step)} ).T df_diffusion_example["step"] = df_diffusion_example.index df_diffusion_example_melted = df_diffusion_example.melt( id_vars=["step"], var_name="variable", value_name="value" ) df_diffusion_example_melted.tail() ``` | | step | variable | value | | --- | --- | --- | --- | | 100995 | 96 | 999 | \-0.522642 | | 100996 | 97 | 999 | \-0.535914 | | 100997 | 98 | 999 | \-0.525615 | | 100998 | 99 | 999 | \-0.621378 | | 100999 | 100 | 999 | \-0.549157 | ``` px.histogram( df_diffusion_example_melted, x="value", histnorm="probability density", animation_frame="step", ) ``` ``` /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/plotly/express/_core.py:1985: FutureWarning: When grouping with a length-1 list-like, you will need to pass a length-1 tuple to get_group in a future version of pandas. Pass `(name,)` instead of `name` to silence this warning. ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` px.violin( df_diffusion_example_melted.loc[ df_diffusion_example_melted["step"].isin( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] ) ], x="step", y="value", ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` px.line( df_diffusion_example_melted, x="step", y="value", color="variable", ) ``` ``` /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/plotly/express/_core.py:1985: FutureWarning: When grouping with a length-1 list-like, you will need to pass a length-1 tuple to get_group in a future version of pandas. Pass `(name,)` instead of `name` to silence this warning. ``` *Interactive Plotly figure: enable JavaScript to view it.* ## Create Visuals ``` import matplotlib.pyplot as plt import seaborn as sns ``` ``` _, ax = plt.subplots(figsize=(10, 6)) sns.histplot( df_diffusion_example_melted.loc[df_diffusion_example_melted["step"] == 0], x="value", stat="probability", color="k", label="Initial Distribution", ax=ax, ) ax.set_title("Initial Distribution") ax.set_xlabel("Position") ``` ``` Text(0.5, 0, 'Position') ``` ![output]() ``` _, ax = plt.subplots(figsize=(10, 6)) sns.histplot( df_diffusion_example_melted.loc[ df_diffusion_example_melted["step"] == max(df_diffusion_example_melted["step"]) ], x="value", stat="probability", color="k", ax=ax, ) ax.set_title("Final Distribution") ax.set_xlabel("Position") ``` ``` Text(0.5, 0, 'Position') ``` ![output]() ``` df_diffusion_example_melted ``` | | step | variable | value | | --- | --- | --- | --- | | 0 | 0 | 0 | 0.753597 | | 1 | 1 | 0 | 0.752213 | | 2 | 2 | 0 | 0.759702 | | 3 | 3 | 0 | 0.761012 | | 4 | 4 | 0 | 0.689937 | | ... | ... | ... | ... | | 100995 | 96 | 999 | \-0.522642 | | 100996 | 97 | 999 | \-0.535914 | | 100997 | 98 | 999 | \-0.525615 | | 100998 | 99 | 999 | \-0.621378 | | 100999 | 100 | 999 | \-0.549157 | 101000 rows × 3 columns ``` _, ax = plt.subplots(figsize=(15, 6)) sns.lineplot( df_diffusion_example_melted.loc[ df_diffusion_example_melted["variable"].isin( [0, 100, 200, 300, 400, 500, 600, 700, 800, 900] ) ].rename(columns={"variable": "particle id"}), x="step", y="value", style="particle id", ) ax.set_xlabel("Time Step") ax.set_ylabel("Particle Position") ``` ``` Text(0, 0.5, 'Particle Position') ``` ![output]() ``` ridge_steps = 10 fig, ax = plt.subplots(figsize=(8, 6)) colors = plt.cm.viridis(np.linspace(0, 1, ridge_steps)) bin_edges = np.histogram_bin_edges(df_diffusion_example_melted["value"], bins="auto") for i, step in enumerate([0, 10, 20, 30, 40, 50, 60, 70, 80, 90]): values = df_diffusion_example_melted[df_diffusion_example_melted["step"] == step][ "value" ] counts, _ = np.histogram(values, bins=bin_edges) counts = counts / counts.max() offset = i * 1.2 ax.fill_between( bin_edges[:-1], offset, counts + offset, step="mid", color=colors[i], alpha=0.7 ) ax.text(bin_edges[-1] + 0.2, offset, step, va="center") ax.axes.get_yaxis().set_visible(False) plt.axis("off") ax.set_xlabel("Position") plt.tight_layout() ``` ![output]() # Model We create a naive model based on the idea of diffusion. 1. Connect the real data to the latent space through diffusion process. 2. We forecast in the latent space. ``` import lightning.pytorch as pl from lightning import LightningModule ``` ``` @dataclasses.dataclass class LatentRNNParams: """Parameters for Diffusion process. :param latent_size: latent space dimension :param history_length: input sequence length :param n_features: number of features """ history_length: int latent_size: int = 100 num_layers: int = 2 n_features: int = 1 initial_state: torch.Tensor = None @cached_property def data_size(self) -> int: """The dimension of the input data when flattened. """ return self.sequence_length * self.n_features def asdict(self) -> dict: return dataclasses.asdict(self) class LatentRNN(nn.Module): """Forecasting the next step in latent space.""" def __init__(self, params: LatentRNNParams): super().__init__() self.params = params self.hparams = params.asdict() self.rnn = nn.GRU( input_size=self.params.history_length, hidden_size=self.params.latent_size, num_layers=self.params.num_layers, batch_first=True, ) def forward( self, x: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ :param x: input data, shape (batch_size, history_length * n_features) """ outputs, _ = self.rnn(x, self.params.initial_state) return outputs class DiffusionEncoder(nn.Module): """Encode the time series into the latent space.""" def __init__( self, params: DiffusionPocessParams, noise: torch.Tensor, ): super().__init__() self.params = params self.noise = noise @staticmethod def _forward_process_by_step( state: torch.Tensor, alpha_by_step: torch.Tensor, noise: torch.Tensor, step: int ) -> torch.Tensor: r"""Assuming that we know the noise at step $t$, $$ x(t) = \sqrt{\alpha(t)}x(t-1) + \sqrt{1 - \alpha(t)}\epsilon(t) $$ """ batch_size = state.shape[0] return torch.sqrt(alpha_by_step[step]) * state + ( torch.sqrt(1 - alpha_by_step[step]) * noise[:batch_size, step] ).reshape(batch_size, 1) def forward(self, x: torch.Tensor) -> torch.Tensor: """Encoding the latent space into a distribution. :param x: input data, shape (batch_size, history_length, n_features) """ alpha_by_step = torch.tensor(self.params.alpha_by_step).to(x) self.noise = self.noise.to(x) # logger.debug( # f"alpha_by_step: {alpha_by_step.shape}" # f"noise: {self.noise.shape}" # f"x: {x.shape}" # ) diffusion_steps_step_by_step = [x] for i in range(0, self.params.steps): i_state = self._forward_process_by_step( diffusion_steps_step_by_step[-1], alpha_by_step=alpha_by_step, noise=self.noise, step=i, ) diffusion_steps_step_by_step.append(i_state) return diffusion_steps_step_by_step[-1] class DiffusionDecoder(nn.Module): """Decode the latent space into a distribution.""" def __init__( self, params: DiffusionPocessParams, noise: torch.Tensor, ): super().__init__() self.params = params self.noise = noise @staticmethod def _inverse_process_by_step( state: torch.Tensor, alpha_by_step: torch.Tensor, noise: torch.Tensor, step: int ) -> torch.Tensor: r"""Assuming that we know the noise at step $t$, $$ x(t-1) = \frac{1}{\sqrt{\alpha(t)}} (x(t) - \sqrt{1 - \alpha(t)}\epsilon(t)) $$ """ batch_size = state.shape[0] return ( state - (torch.sqrt(1 - alpha_by_step[step]) * noise[:batch_size, step]).reshape( batch_size, 1 ) ) / torch.sqrt(alpha_by_step[step]) def forward(self, x: torch.Tensor) -> torch.Tensor: """Encoding the latent space into a distribution. :param x: input data, shape (batch_size, history_length, n_features) """ alpha_by_step = torch.tensor(self.params.alpha_by_step).to(x) self.noise = self.noise.to(x) diffusion_steps_reverse = [x] for i in range(self.params.steps - 1, -1, -1): i_state = self._inverse_process_by_step( state=diffusion_steps_reverse[-1], alpha_by_step=alpha_by_step, noise=self.noise, step=i, ) diffusion_steps_reverse.append(i_state) return diffusion_steps_reverse[-1] class NaiveDiffusionModel(nn.Module): """A naive diffusion model that explicitly calculates the diffusion process. """ def __init__( self, rnn: LatentRNN, diffusion_decoder: DiffusionDecoder, diffusion_encoder: DiffusionEncoder, horizon: int = 1, ): super().__init__() self.rnn = rnn self.diffusion_decoder = diffusion_decoder self.diffusion_encoder = diffusion_encoder self.horizon = horizon self.scale = nn.Linear( in_features=self.rnn.params.latent_size, out_features=self.horizon, ) def forward(self, x: torch.Tensor) -> torch.Tensor: # logger.debug(f"x.squeeze(-1): {x.squeeze(-1).shape=}") x_latent = self.diffusion_encoder(x.squeeze(-1)) # logger.debug(f"x_latent: {x_latent.shape=}") y_latent = self.rnn(x_latent) # logger.debug(f"y_latent: {y_latent.shape=}") y_hat = self.diffusion_decoder(y_latent) # logger.debug(f"y_hat: {y_hat.shape=}") y_hat = self.scale(y_hat) # logger.debug(f"scaled y_hat: {y_hat.shape=}") return y_hat class NaiveDiffusionForecaster(LightningModule): """A assembled lightning module for the naive diffusion model.""" def __init__( self, model: NaiveDiffusionModel, loss: nn.Module = nn.MSELoss(), ): super().__init__() self.model = model self.loss = loss def configure_optimizers(self): optimizer = torch.optim.SGD(self.parameters(), lr=1e-3) return optimizer def training_step(self, batch, batch_idx): x, y = batch x = x.type(self.dtype) y = y.type(self.dtype) batch_size = x.shape[0] y_hat = self.model(x)[:batch_size, :].reshape_as(y) loss = self.loss(y_hat, y).mean() self.log_dict({"train_loss": loss}, prog_bar=True) return loss def validation_step(self, batch, batch_idx): x, y = batch x = x.type(self.dtype) y = y.type(self.dtype) batch_size = x.shape[0] y_hat = self.model(x)[:batch_size, :].reshape_as(y) loss = self.loss(y_hat, y).mean() self.log_dict({"val_loss": loss}, prog_bar=True) return loss def predict_step(self, batch, batch_idx): x, y = batch x = x.type(self.dtype) y = y.type(self.dtype) batch_size = x.shape[0] y_hat = self.model(x)[:batch_size, :].reshape_as(y) return x, y_hat def forward(self, x: torch.Tensor) -> torch.Tensor: x = x.to(self.model.rnn.rnn.weight_ih_l0) return self.model(x) ``` ``` df = pd.DataFrame( {"t": np.linspace(0, 100, 501), "y": np.sin(np.linspace(0, 100, 501))} ) _, ax = plt.subplots(figsize=(10, 6.18)) df.plot(x="t", y="y", ax=ax) ``` ``` ``` ![output]() ## Traning ``` from ts_dl_utils.datasets.dataset import DataFrameDataModule ``` ``` history_length_1_step = 100 horizon_1_step = 1 training_batch_size = 64 training_noise = gaussian_noise(training_batch_size, diffusion_process_params.steps) ``` ``` diffusion_process_params.alpha_by_step.shape, training_noise.shape ``` ``` ((100,), torch.Size([64, 100])) ``` ``` test_state = torch.rand(training_batch_size, diffusion_process_params.steps) test_state.shape ``` ``` torch.Size([64, 100]) ``` ``` torch.sqrt(torch.from_numpy(diffusion_process_params.alpha_by_step)[0]) ``` ``` tensor(0.9975, dtype=torch.float64) ``` ``` ( test_state - torch.sqrt(torch.from_numpy(diffusion_process_params.alpha_by_step)[0]) * training_noise[:, 0].reshape(training_batch_size, 1) ).shape ``` ``` torch.Size([64, 100]) ``` ``` pdm_1_step = DataFrameDataModule( history_length=history_length_1_step, horizon=horizon_1_step, dataframe=df[["y"]].astype(np.float32), batch_size=training_batch_size, ) ``` ``` diffusion_decoder = DiffusionDecoder(diffusion_process_params, training_noise) diffusion_encoder = DiffusionEncoder(diffusion_process_params, training_noise) ``` ``` latent_rnn_params = LatentRNNParams( history_length=history_length_1_step, latent_size=diffusion_process_params.steps, ) latent_rnn = LatentRNN(latent_rnn_params) ``` ``` naive_diffusion_model = NaiveDiffusionModel( rnn=latent_rnn, diffusion_decoder=diffusion_decoder, diffusion_encoder=diffusion_encoder, ) naive_diffusion_forecaster = NaiveDiffusionForecaster( model=naive_diffusion_model.float(), ) ``` ``` naive_diffusion_forecaster ``` ``` NaiveDiffusionForecaster( (model): NaiveDiffusionModel( (rnn): LatentRNN( (rnn): GRU(100, 100, num_layers=2, batch_first=True) ) (diffusion_decoder): DiffusionDecoder() (diffusion_encoder): DiffusionEncoder() (scale): Linear(in_features=100, out_features=1, bias=True) ) (loss): MSELoss() ) ``` ``` logger_1_step = pl.loggers.TensorBoardLogger( save_dir="lightning_logs", name="naive_diffusion_ts_1_step" ) precision = "64" trainer_1_step = pl.Trainer( # precision="32", precision=precision, # max_epochs=5000, max_epochs=10000, min_epochs=5, # callbacks=[ # pl.callbacks.early_stopping.EarlyStopping(monitor="val_loss", mode="min", min_delta=1e-8, patience=4) # ], logger=logger_1_step, # accelerator="mps", accelerator="cuda", ) ``` ``` GPU available: True (mps), used: True TPU available: False, using: 0 TPU cores IPU available: False, using: 0 IPUs HPU available: False, using: 0 HPUs ``` ``` trainer_1_step.fit(model=naive_diffusion_forecaster, datamodule=pdm_1_step) ``` ``` | Name | Type | Params ---------------------------------------------- 0 | model | NaiveDiffusionModel | 121 K 1 | loss | MSELoss | 0 ---------------------------------------------- 121 K Trainable params 0 Non-trainable params 121 K Total params 0.485 Total estimated model params size (MB) /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'val_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'train_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/loops/fit_loop.py:293: The number of training batches (4) is smaller than the logging interval Trainer(log_every_n_steps=50). Set a lower value for log_every_n_steps if you want to see logs for the training epoch. ``` # Evaluation ``` from typing import Dict, List, Sequence, Tuple import matplotlib as mpl import numpy as np import pandas as pd import torch from torch.utils.data import DataLoader from torchmetrics import MetricCollection from torchmetrics.regression import ( MeanAbsoluteError, MeanAbsolutePercentageError, MeanSquaredError, SymmetricMeanAbsolutePercentageError, ) from ts_dl_utils.evaluation.evaluator import Evaluator from ts_dl_utils.naive_forecasters.last_observation import LastObservationForecaster class Evaluator: """Evaluate the predictions :param step: which prediction step to be evaluated. :param gap: gap between input history and target/prediction. """ def __init__(self, step: int = 0, gap: int = 0): self.step = step self.gap = gap @staticmethod def get_one_history( predictions: Sequence[Sequence], idx: int, batch_idx: int = 0 ) -> torch.Tensor: return predictions[batch_idx][0][idx, ...] @staticmethod def get_one_pred(predictions: List, idx: int, batch_idx: int = 0) -> torch.Tensor: return predictions[batch_idx][1][idx, ...] @staticmethod def get_y(predictions: List, step: int) -> List[torch.Tensor]: return [i[1][..., step] for i in predictions] def y(self, predictions: List, batch_idx: int = 0) -> torch.Tensor: return self.get_y(predictions, self.step)[batch_idx].detach() @staticmethod def get_y_true(dataloader: DataLoader, step: int) -> list[torch.Tensor]: return [i[1][..., step] for i in dataloader] def y_true(self, dataloader: DataLoader, batch_idx: int = 0) -> torch.Tensor: return self.get_y_true(dataloader, step=self.step)[batch_idx].detach() def get_one_sample( self, predictions: List, idx: int, batch_idx: int = 0 ) -> Tuple[torch.Tensor, torch.Tensor]: return ( self.get_one_history(predictions, idx, batch_idx), self.get_one_pred(predictions, idx, batch_idx), ) def plot_one_sample( self, ax: mpl.axes.Axes, predictions: List, idx: int, batch_idx: int = 0 ) -> None: history, pred = self.get_one_sample(predictions, idx, batch_idx) x_raw = np.arange(len(history) + len(pred) + self.gap) x_history = x_raw[: len(history)] x_pred = x_raw[len(history) + self.gap :] x = np.concatenate([x_history, x_pred]) y = np.concatenate([history, pred]) ax.plot(x, y, marker=".", label=f"input ({idx})") ax.axvspan(x_pred[0], x_pred[-1], color="orange", alpha=0.1) @property def metric_collection(self) -> MetricCollection: return MetricCollection( MeanAbsoluteError(), MeanAbsolutePercentageError(), MeanSquaredError(), SymmetricMeanAbsolutePercentageError(), ) @staticmethod def metric_dataframe(metrics: Dict) -> pd.DataFrame: return pd.DataFrame( [{k: float(v) for k, v in metrics.items()}], index=["values"] ).T def metrics( self, predictions: List, dataloader: DataLoader, batch_idx: int = 0 ) -> pd.DataFrame: truths = self.y_true(dataloader) preds = self.y(predictions, batch_idx=batch_idx) return self.metric_dataframe(self.metric_collection(preds, truths)) ``` ``` evaluator_1_step = Evaluator(step=0) ``` ``` predictions_1_step = trainer_1_step.predict( model=naive_diffusion_forecaster, datamodule=pdm_1_step ) ``` ``` /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'predict_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator_1_step.y_true(dataloader=pdm_1_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_1_step.y(predictions_1_step), "r--", label="predictions") # ax.plot(evaluator_1_step.y(lobs_1_step_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` ``` ![output]() ``` trainer_naive_1_step = pl.Trainer(precision=precision) lobs_forecaster_1_step = LastObservationForecaster(horizon=horizon_1_step) lobs_1_step_predictions = trainer_naive_1_step.predict( model=lobs_forecaster_1_step, datamodule=pdm_1_step ) ``` ``` GPU available: True (mps), used: True TPU available: False, using: 0 TPU cores IPU available: False, using: 0 IPUs HPU available: False, using: 0 HPUs ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator_1_step.y_true(dataloader=pdm_1_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_1_step.y(predictions_1_step), "r--", label="predictions") ax.plot(evaluator_1_step.y(lobs_1_step_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` evaluator_1_step.metrics(predictions_1_step, pdm_1_step.predict_dataloader()) ``` ``` evaluator_1_step.metrics( [[i.unsqueeze(-1) for i in lobs_1_step_predictions[0]]], pdm_1_step.predict_dataloader(), ) ``` # Time Series Data and Embeddings ``` import matplotlib.pyplot as plt import numpy as np import pandas as pd import plotly.express as px ``` ``` def plot_arrow_chart( dataframe: pd.DataFrame, x_col: str, y_col: str, ax: plt.Axes, color: str = "k", alpha: float = 0.7, marker: str = ".", linestyle: str = "-", arrow_head_width: int = 4000, ) -> plt.Axes: """ Plot an arrow chart for the 'Total' and its lagged values within a specified date range. """ x = dataframe[x_col].values y = dataframe[y_col].values ax.plot(x, y, marker=marker, linestyle=linestyle, color=color, alpha=alpha) step = max(1, len(x) // 100) for i in range(0, len(x) - 1, step): ax.arrow( x[i], y[i], x[i + 1] - x[i], y[i + 1] - y[i], shape="full", lw=0, length_includes_head=True, head_width=arrow_head_width, color=color, alpha=alpha, ) return ax ``` ## Pendulum ``` from ts_dl_utils.datasets.pendulum import Pendulum ``` ``` pen = Pendulum(length=20) df_pen = pd.DataFrame(pen(3, 100, initial_angle=1, beta=0.01)) df_pen["theta_1"] = df_pen["theta"].shift() df_pen["theta_diff"] = df_pen["theta"].diff() df_pen ``` | | t | theta | theta\_1 | theta\_diff | | --- | --- | --- | --- | --- | | 0 | 0.000000 | 1.000000 | NaN | NaN | | 1 | 0.089714 | 0.997132 | 1.000000 | \-0.002868 | | 2 | 0.179428 | 0.990336 | 0.997132 | \-0.006796 | | 3 | 0.269142 | 0.979647 | 0.990336 | \-0.010689 | | 4 | 0.358856 | 0.965114 | 0.979647 | \-0.014533 | | ... | ... | ... | ... | ... | | 295 | 26.465639 | 0.729907 | 0.714216 | 0.015691 | | 296 | 26.555353 | 0.742692 | 0.729907 | 0.012785 | | 297 | 26.645067 | 0.752524 | 0.742692 | 0.009833 | | 298 | 26.734781 | 0.759371 | 0.752524 | 0.006847 | | 299 | 26.824495 | 0.763211 | 0.759371 | 0.003840 | 300 rows × 4 columns ``` fig = plt.figure(figsize=(10, 8), layout="constrained") spec = fig.add_gridspec(2, 2) ax0 = fig.add_subplot(spec[0, :]) ax10 = fig.add_subplot(spec[1, 0]) ax11 = fig.add_subplot(spec[1, 1]) ax0.plot( df_pen.t, df_pen.theta, marker=".", linestyle="-", color="k", ) # Make x-ticks readable ax0.xaxis.set_major_locator(plt.MaxNLocator(8)) # fig.autofmt_xdate(rotation=30) ax0.set_title("Swing Angle") ax10 = plot_arrow_chart( df_pen, x_col="theta", y_col="theta_1", ax=ax10, arrow_head_width=0.00001 ) ax10.set_xlabel("Swing Angle") ax10.set_ylabel("Swing Angle 0.05 seconds ago") ax10.set_title("Swing Angle and Angle 0.05 seconds ago") ax11 = plot_arrow_chart( df_pen, x_col="theta", y_col="theta_diff", ax=ax11, arrow_head_width=0.00001 ) ax11.set_xlabel("Swing Angle") ax11.set_ylabel("Swing Angle Change Rate") ax11.set_title("Phase Portrait") plt.tight_layout() ``` ``` /var/folders/gk/cdkvr2rn1yn547mssh0ccq4c0000gp/T/ipykernel_55794/4179391181.py:45: UserWarning: The figure layout has changed to tight ``` ![output]() ## Covid ``` df_ecdc_covid = pd.read_csv( "https://gist.githubusercontent.com/emptymalei/" "90869e811b4aa118a7d28a5944587a64/raw" "/1534670c8a3859ab3a6ae8e9ead6795248a3e664" "/ecdc%2520covid%252019%2520data" ) ``` ``` px.line(df_ecdc_covid, x="datetime", y="Total") ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` df_ecdc_covid ``` | | datetime | AT | BE | BG | CY | CZ | DE | DK | EE | ES | ... | MT | NL | NO | PL | PT | RO | SE | SI | SK | Total | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 0 | 2020-03-20 | 550.0 | 309.0 | 13.0 | 0.0 | 172.0 | 5940.0 | 36.0 | 9.0 | 3431.0 | ... | 5.0 | 409.0 | 129.0 | 68.0 | 143.0 | 17.0 | 122.0 | 33.0 | 16.0 | 19780.0 | | 1 | 2020-03-21 | 453.0 | 462.0 | 22.0 | 9.0 | 210.0 | 4185.0 | 104.0 | 16.0 | 2833.0 | ... | 11.0 | 534.0 | 190.0 | 70.0 | 235.0 | 31.0 | 200.0 | 22.0 | 14.0 | 18412.0 | | 2 | 2020-03-22 | 375.0 | 558.0 | 36.0 | 17.0 | 91.0 | 3140.0 | 71.0 | 23.0 | 4946.0 | ... | 9.0 | 637.0 | 184.0 | 111.0 | 260.0 | 59.0 | 123.0 | 42.0 | 41.0 | 20797.0 | | 3 | 2020-03-23 | 607.0 | 586.0 | 22.0 | 11.0 | 170.0 | 3311.0 | 69.0 | 20.0 | 3646.0 | ... | 17.0 | 573.0 | 206.0 | 98.0 | 320.0 | 66.0 | 160.0 | 31.0 | 7.0 | 18375.0 | | 4 | 2020-03-24 | 855.0 | 342.0 | 16.0 | 21.0 | 71.0 | 4438.0 | 65.0 | 26.0 | 4517.0 | ... | 17.0 | 545.0 | 239.0 | 115.0 | 460.0 | 143.0 | 110.0 | 28.0 | 6.0 | 22237.0 | | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | | 265 | 2020-12-10 | 2913.0 | 3071.0 | 3328.0 | 363.0 | 6406.0 | 23679.0 | 2558.0 | 544.0 | 9773.0 | ... | 79.0 | 6524.0 | 459.0 | 12166.0 | 7002.0 | 7365.0 | 7061.0 | 2137.0 | 2564.0 | 158702.0 | | 266 | 2020-12-11 | 2466.0 | 2754.0 | 3075.0 | 403.0 | 5872.0 | 29875.0 | 3132.0 | 544.0 | 7955.0 | ... | 106.0 | 8709.0 | 362.0 | 13750.0 | 3134.0 | 7067.0 | 7935.0 | 1848.0 | 3125.0 | 172457.0 | | 267 | 2020-12-12 | 3026.0 | 2762.0 | 3097.0 | 424.0 | 6217.0 | 28438.0 | 3075.0 | 358.0 | 10519.0 | ... | 96.0 | 8827.0 | 498.0 | 13105.0 | 5080.0 | 6460.0 | 7370.0 | 1816.0 | 2166.0 | 172804.0 | | 268 | 2020-12-13 | 2938.0 | 0.0 | 1287.0 | 324.0 | 3657.0 | 20200.0 | 3552.0 | 757.0 | 0.0 | ... | 121.0 | 9071.0 | 0.0 | 11499.0 | 4413.0 | 6333.0 | 0.0 | 1744.0 | 0.0 | 135594.0 | | 269 | 2020-12-14 | 3005.0 | 8261.0 | 497.0 | 301.0 | 2000.0 | 16362.0 | 2642.0 | 342.0 | 21309.0 | ... | 153.0 | 9868.0 | 981.0 | 8976.0 | 4044.0 | 4435.0 | 20931.0 | 833.0 | 5897.0 | 170151.0 | 270 rows × 33 columns ``` df_ecdc_covid_arrow_chart = df_ecdc_covid.loc[ pd.to_datetime(df_ecdc_covid.datetime).between("2020-08-01", "2020-12-01") ].copy() df_ecdc_covid_arrow_chart["Total_1"] = df_ecdc_covid_arrow_chart["Total"].shift() df_ecdc_covid_arrow_chart["Total_diff"] = df_ecdc_covid_arrow_chart["Total"].diff() ``` ``` fig = plt.figure(figsize=(10, 8), layout="constrained") spec = fig.add_gridspec(2, 2) ax0 = fig.add_subplot(spec[0, :]) ax10 = fig.add_subplot(spec[1, 0]) ax11 = fig.add_subplot(spec[1, 1]) ax0.plot( df_ecdc_covid_arrow_chart.datetime, df_ecdc_covid_arrow_chart.Total, marker=".", linestyle="-", color="k", ) # Make x-ticks readable ax0.xaxis.set_major_locator(plt.MaxNLocator(8)) # fig.autofmt_xdate(rotation=30) ax0.set_title("Covid Cases in EU Over Time") ax10 = plot_arrow_chart( df_ecdc_covid_arrow_chart, x_col="Total", y_col="Total_1", ax=ax10 ) ax10.set_xlabel("Total Cases") ax10.set_ylabel("Total Cases Lagged by 1 Day") ax10.set_title("Covid Cases and Lagged Values") ax11 = plot_arrow_chart( df_ecdc_covid_arrow_chart, x_col="Total", y_col="Total_diff", ax=ax11 ) ax11.set_xlabel("Total Cases") ax11.set_ylabel("Total Cases Change") ax11.set_title("Covid Cases in EU Phase Portrait") ax11.set_ylim(-100_000, 100_000) plt.tight_layout() ``` ``` /var/folders/gk/cdkvr2rn1yn547mssh0ccq4c0000gp/T/ipykernel_55794/2305141229.py:44: UserWarning: The figure layout has changed to tight ``` ![output]() ## Walmart ``` df_walmart = pd.read_csv( "https://raw.githubusercontent.com/datumorphism/" "dataset-m5-simplified/refs/heads/main/dataset/" "m5_store_sales.csv" ) ``` ``` df_walmart ``` | | date | CA | TX | WI | ('CA', 'CA\_1') | ('CA', 'CA\_2') | ('CA', 'CA\_3') | ('CA', 'CA\_4') | ('TX', 'TX\_1') | ('TX', 'TX\_2') | ('TX', 'TX\_3') | ('WI', 'WI\_1') | ('WI', 'WI\_2') | ('WI', 'WI\_3') | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 0 | 2011-01-29 | 14195 | 9438 | 8998 | 4337 | 3494 | 4739 | 1625 | 2556 | 3852 | 3030 | 2704 | 2256 | 4038 | | 1 | 2011-01-30 | 13805 | 9630 | 8314 | 4155 | 3046 | 4827 | 1777 | 2687 | 3937 | 3006 | 2194 | 1922 | 4198 | | 2 | 2011-01-31 | 10108 | 6778 | 6897 | 2816 | 2121 | 3785 | 1386 | 1822 | 2731 | 2225 | 1562 | 2018 | 3317 | | 3 | 2011-02-01 | 11047 | 7381 | 6984 | 3051 | 2324 | 4232 | 1440 | 2258 | 2954 | 2169 | 1251 | 2522 | 3211 | | 4 | 2011-02-02 | 9925 | 5912 | 3309 | 2630 | 1942 | 3817 | 1536 | 1694 | 2492 | 1726 | 2 | 1175 | 2132 | | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | | 1908 | 2016-04-20 | 15148 | 9600 | 10595 | 3722 | 3691 | 5235 | 2500 | 2901 | 3384 | 3315 | 3242 | 4194 | 3159 | | 1909 | 2016-04-21 | 14488 | 9602 | 10943 | 3709 | 3303 | 5018 | 2458 | 2776 | 3446 | 3380 | 3324 | 4393 | 3226 | | 1910 | 2016-04-22 | 17095 | 10615 | 12807 | 4387 | 4457 | 5623 | 2628 | 3022 | 3902 | 3691 | 3991 | 4988 | 3828 | | 1911 | 2016-04-23 | 21834 | 12266 | 14862 | 5577 | 5884 | 7419 | 2954 | 3700 | 4483 | 4083 | 4772 | 5404 | 4686 | | 1912 | 2016-04-24 | 23187 | 12282 | 14326 | 6113 | 6082 | 7721 | 3271 | 4033 | 4292 | 3957 | 4874 | 5127 | 4325 | 1913 rows × 14 columns ``` px.line(df_walmart, x="date", y="CA") ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` df_walmart_total = df_walmart[["date", "CA", "TX", "WI"]].copy() ``` ``` df_walmart_total["total"] = ( df_walmart_total.CA + df_walmart_total.TX + df_walmart_total.WI ) df_walmart_total["datetime"] = pd.to_datetime(df_walmart_total.date, format="%Y-%m-%d") df_walmart_total["timestamp"] = df_walmart_total.datetime.astype(int) // 10**9 ``` ``` df_walmart_total["total_1"] = df_walmart_total.total.shift() df_walmart_total["total_diff"] = df_walmart_total.total.diff() ``` ``` px.scatter( df_walmart_total.loc[pd.to_datetime(df_walmart_total.date).dt.year == 2016], x="total", y="total_1", color="timestamp", ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` df_walmart_arrow_chart = df_walmart_total.loc[ pd.to_datetime(df_walmart_total.date).between("2016-01-01", "2016-03-01") ].copy() ``` ``` fig = plt.figure(figsize=(10, 8), layout="constrained") spec = fig.add_gridspec(2, 2) ax0 = fig.add_subplot(spec[0, :]) ax10 = fig.add_subplot(spec[1, 0]) ax11 = fig.add_subplot(spec[1, 1]) ax0.plot( df_walmart_arrow_chart.datetime, df_walmart_arrow_chart.total, marker=".", linestyle="-", color="k", ) # Make x-ticks readable ax0.xaxis.set_major_locator(plt.MaxNLocator(8)) # fig.autofmt_xdate(rotation=30) ax0.set_title("Walmart Sales Over Time") ax10 = plot_arrow_chart( df_walmart_arrow_chart, x_col="total", y_col="total_1", ax=ax10, arrow_head_width=500, ) ax10.set_xlabel("Total Sales") ax10.set_ylabel("Total Sales Lagged by 1 Day") ax10.set_title("Walmart Sales and Lagged Sales") ax11 = plot_arrow_chart( df_walmart_arrow_chart, x_col="total", y_col="total_diff", ax=ax11, arrow_head_width=500, ) ax11.set_xlabel("Total Sales") ax11.set_ylabel("Total Sales Change") ax11.set_title("Walmart Sales Phase Portrait") plt.tight_layout() ``` ``` /var/folders/gk/cdkvr2rn1yn547mssh0ccq4c0000gp/T/ipykernel_55794/2550651657.py:43: UserWarning: The figure layout has changed to tight ``` ![output]() ## Electricity Data ``` import io import zipfile ``` ``` import pandas as pd ``` ``` import requests # Download from remote URL data_uri = "https://archive.ics.uci.edu/ml/machine-learning-databases/00321/LD2011_2014.txt.zip" r = requests.get(data_uri) z = zipfile.ZipFile(io.BytesIO(r.content)) z.extractall("tmp/data/uci_electricity/") ``` ``` # Load as pandas dataframe df_electricity = ( pd.read_csv("tmp/data/uci_electricity/LD2011_2014.txt", delimiter=";", decimal=",") .rename(columns={"Unnamed: 0": "date"}) .set_index("date") ) df_electricity.index = pd.to_datetime(df_electricity.index) ``` ``` df_electricity ``` | | MT\_001 | MT\_002 | MT\_003 | MT\_004 | MT\_005 | MT\_006 | MT\_007 | MT\_008 | MT\_009 | MT\_010 | ... | MT\_361 | MT\_362 | MT\_363 | MT\_364 | MT\_365 | MT\_366 | MT\_367 | MT\_368 | MT\_369 | MT\_370 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | date | | | | | | | | | | | | | | | | | | | | | | | 2011-01-01 00:15:00 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | ... | 0.000000 | 0.0 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | | 2011-01-01 00:30:00 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | ... | 0.000000 | 0.0 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | | 2011-01-01 00:45:00 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | ... | 0.000000 | 0.0 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | | 2011-01-01 01:00:00 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | ... | 0.000000 | 0.0 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | | 2011-01-01 01:15:00 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | ... | 0.000000 | 0.0 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | | 2014-12-31 23:00:00 | 2.538071 | 22.048364 | 1.737619 | 150.406504 | 85.365854 | 303.571429 | 11.305822 | 282.828283 | 68.181818 | 72.043011 | ... | 276.945039 | 28200.0 | 1616.033755 | 1363.636364 | 29.986962 | 5.851375 | 697.102722 | 176.961603 | 651.026393 | 7621.621622 | | 2014-12-31 23:15:00 | 2.538071 | 21.337127 | 1.737619 | 166.666667 | 81.707317 | 324.404762 | 11.305822 | 252.525253 | 64.685315 | 72.043011 | ... | 279.800143 | 28300.0 | 1569.620253 | 1340.909091 | 29.986962 | 9.947338 | 671.641791 | 168.614357 | 669.354839 | 6702.702703 | | 2014-12-31 23:30:00 | 2.538071 | 20.625889 | 1.737619 | 162.601626 | 82.926829 | 318.452381 | 10.175240 | 242.424242 | 61.188811 | 74.193548 | ... | 284.796574 | 27800.0 | 1556.962025 | 1318.181818 | 27.379400 | 9.362200 | 670.763828 | 153.589316 | 670.087977 | 6864.864865 | | 2014-12-31 23:45:00 | 1.269036 | 21.337127 | 1.737619 | 166.666667 | 85.365854 | 285.714286 | 10.175240 | 225.589226 | 64.685315 | 72.043011 | ... | 246.252677 | 28000.0 | 1443.037975 | 909.090909 | 26.075619 | 4.095963 | 664.618086 | 146.911519 | 646.627566 | 6540.540541 | | 2015-01-01 00:00:00 | 2.538071 | 19.914651 | 1.737619 | 178.861789 | 84.146341 | 279.761905 | 10.175240 | 249.158249 | 62.937063 | 69.892473 | ... | 188.436831 | 27800.0 | 1409.282700 | 954.545455 | 27.379400 | 4.095963 | 628.621598 | 131.886477 | 673.020528 | 7135.135135 | 140256 rows × 370 columns ``` df_electricity.loc[ (df_electricity.index >= "2012-01-01") & (df_electricity.index < "2012-02-01") ][["MT_001"]].plot() ``` ``` ``` ![output]() # Appendices Many formulae and concepts are reused again and again in different models. In this chapter, we will provide support for such concepts. # Entropy > [!NOTE] > > **In one minute** > > Shannon entropy is the expected information content of a distribution. Cross entropy measures one distribution against another and splits into the entropy plus the KL divergence; it is widely used as the loss in classification. ## Shannon Entropy Shannon entropy \\(S\\) is the expectation of information content \\(I(X)=-\\log \\left(p\\right)\\)[^/concepts/entropy/#shannon_entropy_wiki], \\\[\\begin{equation} H(p) = \\mathbb E\_{p}\\left\[ -\\log \\left(p\\right) \\right\]. \\end{equation}\\\] ## Cross Entropy Cross entropy is[^/concepts/entropy/#cross_entropy_wiki] \\\[ H(p, q) = \\mathbb E\_{p} \\left\[ -\\log q \\right\]. \\\] Cross entropy \\(H(p, q)\\) can also be decomposed, \\\[ H(p, q) = H(p) + \\operatorname{D}\_{\\mathrm{KL}} \\left( p \\parallel q \\right), \\\] where \\(H(p)\\) is the [entropy of \\(P\\)](<#shannon-entropy>) and \\(\\operatorname{D}\_{\\mathrm{KL}}\\) is the [KL Divergence](). Cross entropy is widely used in classification problems, e.g., logistic regression. ## Try It: Entropy, Cross Entropy and KL Divergence Two distributions \\(p\\) and \\(q\\) over six classes. Move their peaks and sharpness, and watch the decomposition above: the cross entropy bar is the entropy of \\(p\\) plus the KL divergence. An interactive chart of two distributions over six classes, with sliders for the peak and sharpness of each. It shows the entropy of \\(p\\), the cross entropy \\(H(p, q)\\) and the KL divergence as bars, in nats. It needs JavaScript. In short: \\(H(p, q) = H(p) + \\operatorname{D}\_{\\mathrm{KL}}(p \\parallel q)\\), so the cross entropy is smallest when \\(q\\) equals \\(p\\). --- **Related:** [KL Divergence]() · [Information Gain]() [^/concepts/entropy/#shannon_entropy_wiki]: Contributors to Wikimedia projects. Entropy (information theory). In: Wikipedia \[Internet\]. 29 Aug 2021 \[cited 4 Sep 2021\]. Available: [https://en.wikipedia.org/wiki/Entropy\_(information\_theory)]() [^/concepts/entropy/#cross_entropy_wiki]: Contributors to Wikimedia projects. Cross entropy. In: Wikipedia \[Internet\]. 4 Jul 2021 \[cited 4 Sep 2021\]. Available: [https://en.wikipedia.org/wiki/Cross\_entropy]() # Mutual Information > [!NOTE] > > **In one minute** > > Mutual information of two random variables is the expected log ratio of their joint distribution to the product of their marginals. That makes it the KL divergence between the joint distribution and the product of the marginals. > > **Read first:** [KL Divergence]() Mutual information is \\\[ I(X;Y) = \\mathbb E\_{p\_{XY}} \\ln \\frac{P\_{XY}}{P\_X P\_Y}. \\\] Mutual information is closely related to [KL divergence](), \\\[ I(X;Y) = D\_{\\mathrm{KL}} \\left( P\_{XY}(x,y) \\parallel P\_X(x) P\_{Y}(y) \\right). \\\] --- **Related:** [InfoGAN]() · [Deep Infomax]() # KL Divergence > [!NOTE] > > **In one minute** > > The Kullback-Leibler divergence compares two probability distributions. It is not symmetric, so it is not a proper distance; the page shows this with a Gaussian and a bimodal Gaussian mixture. It is a special case of the f-divergence. The Kullback–Leibler (KL) divergence is defined as \\\[ \\begin{align} \\operatorname{D}\_\\mathrm{KL}(p \\parallel q ) =& \\mathbb E\_{p} \\left\[\\log\\left(\\frac{p}{q}\\right) \\right\] \\\\ =& \\int\_{-\\infty}^\\infty p \\log\\left(\\frac{p}{q}\\right)\\, dx . \\end{align} \\\] Suppose \\(p\\) is a Gaussian distribution and \\(q\\) is a bimodal Gaussian mixture, the KL divergence \\(\\operatorname{D}\_\\mathrm{KL}(p \\parallel q )\\) and \\(\\operatorname{D}\_\\mathrm{KL}(q \\parallel p )\\) are different as KL divergence is not necessarily symmetric. Thus the KL divergence is not a proper distance definition. ![KL Divergence of Gaussian Mixture]() KL divergence is a special case of [f-divergence](). ## Try It: The Two Directions of the KL Divergence As in the figure above, \\(p\\) is a Gaussian and \\(q\\) is a mixture with two modes. Move \\(p\\), or the modes of \\(q\\), and compare \\(\\operatorname{D}\_\\mathrm{KL}(p \\parallel q)\\) with \\(\\operatorname{D}\_\\mathrm{KL}(q \\parallel p)\\). The lower chart shows where each of the two integrals collects its value. An interactive chart of a Gaussian \\(p\\) and a two-mode mixture \\(q\\), with sliders for the mean and spread of \\(p\\) and for the modes of \\(q\\). It shows both densities, the integrands \\(p \\log(p/q)\\) and \\(q \\log(q/p)\\), and the two KL divergences. It needs JavaScript. In short: the two directions give different values, for example about 0.69 against 7.5 nats when \\(p\\) sits on one mode of \\(q\\). --- **Related:** [f-Divergence]() · [Entropy]() · [Mutual Information]() # f-Divergence > [!NOTE] > > **In one minute** > > The f-divergence compares two densities through a generating function f that is convex and satisfies f(1) = 0. Choosing f(x) = x log x gives the KL divergence. The f-divergence is defined as[^/concepts/f-divergence/#f-divergence_wiki] \\\[ \\operatorname{D}\_f = \\int f\\left(\\frac{p}{q}\\right) q\\mathrm d\\mu, \\\] where \\(p\\) and \\(q\\) are two densities and \\(\\mu\\) is a reference distribution. > [!WARNING] > > **Requirements on the generating function** > > The generating function \\(f\\) is required to > > - be convex, and > - \\(f(1) =0\\). For \\(f(x) = x \\log x\\) with \\(x=p/q\\), f-divergence is reduced to the KL divergence \\\[ \\begin{align} &\\int f\\left(\\frac{p}{q}\\right) q\\mathrm d\\mu \\\\ =& \\int \\frac{p}{q} \\log \\left( \\frac{p}{q} \\right) \\mathrm d\\mu \\\\ =& \\int p \\log \\left( \\frac{p}{q} \\right) \\mathrm d\\mu. \\end{align} \\\] For more special cases of f-divergence, please refer to wikipedia[^/concepts/f-divergence/#f-divergence_wiki]. Nowozin 2016 also provides a concise review of f-divergence[^/concepts/f-divergence/#Nowozin2016]. --- **Related:** [KL Divergence]() · [f-GAN]() [^/concepts/f-divergence/#f-divergence_wiki]: Contributors to Wikimedia projects. F-divergence. In: Wikipedia \[Internet\]. 17 Jul 2021 \[cited 4 Sep 2021\]. Available: [https://en.wikipedia.org/wiki/F-divergence]() [^/concepts/f-divergence/#Nowozin2016]: Nowozin S, Cseke B, Tomioka R. f-GAN: Training Generative Neural Samplers using Variational Divergence Minimization. arXiv \[stat.ML\]. 2016. Available: [http://arxiv.org/abs/1606.00709]() # ELBO > [!NOTE] > > **In one minute** > > The evidence lower bound (ELBO) is a lower bound on the log probability of the data in a latent variable model. The page derives it twice: with Jensen's inequality, and from the KL divergence between an approximate posterior and the true posterior, where that KL divergence is the gap between the bound and the log probability. > > **Read first:** [Entropy]() · [KL Divergence]() Given a probability distribution density \\(p(x)\\) and a latent variable \\(z\\), the marginalization of the joint probability is \\\[ \\int \\mathrm dz p(x, z) = p(x). \\\] ## Using Jensen's Inequality In many models, we are interested in the log probability density \\(\\log p(X)\\) which can be decomposed using an auxiliary density of the latent variable \\(q(Z)\\), \\\[ \\begin{align} \\log p(x) =& \\log \\int \\mathrm d z p(x, z) \\\\ =& \\log \\int \\mathrm d z p(x, z) \\frac{q(z)}{q(z)} \\\\ =& \\log \\int \\mathrm d z q(z) \\frac{p(x, z)}{q(z)} \\\\ =& \\log \\mathbb E\_q \\left\[ \\frac{p(x, z)}{q(z)} \\right\]. \\end{align} \\\] > [!NOTE] > > **Jensen's Inequality** > > Jensen's inequality shows that[^/concepts/elbo/#jensens-inequality-wiki] > > \\\[ \\log \\mathbb E\_q \\left\[ \\frac{p(x, z)}{q(Z)} \\right\] \\geq \\mathbb E\_q \\left\[ \\log\\left(\\frac{p(x, z)}{q(Z)}\\right) \\right\], \\\] > > as \\(\\log\\) is a concave function. Applying Jensen's inequality, \\\[ \\begin{align} \\log p(x) =& \\log \\mathbb E\_q \\left\[ \\frac{p(x, z)}{q(z)} \\right\] \\\\ \\geq& \\mathbb E\_q \\left\[ \\log\\left(\\frac{p(x, z)}{q(z)}\\right) \\right\] \\\\ =& \\mathbb E\_q \\left\[ \\log p(x, z)- \\log q(z) \\right\] \\\\ =& \\mathbb E\_q \\left\[ \\log p(x, z) \\right\] - \\mathbb E\_q \\left\[ \\log q(z) \\right\] . \\end{align} \\\] Using the definition of [entropy]() and [cross entropy](), we know that \\\[ H(q(z)) = - \\mathbb E\_q \\left\[ \\log q(z) \\right\] \\\] is the entropy of \\(q(z)\\), and \\\[ H(q(z);p(x,z)) = -\\mathbb E\_q \\left\[ \\log p(x, z) \\right\] \\\] is the cross entropy. We define \\\[ L = \\mathbb E\_q \\left\[ \\log p(x, z) \\right\] - \\mathbb E\_q \\left\[ \\log q(z) \\right\] = - H(q(z);p(x,z)) + H(q(z)), \\\] which is called the evidence lower bound (**ELBO**). It is a lower bound because \\\[ \\log p(x) \\geq L. \\\] ## Using KL Divergence In a latent variable model, we need the posterior \\(p(z|x)\\). When this is intractable, we find an approximation \\(q(z|\\theta)\\) where \\(\\theta\\) is the parametrization, e.g., neural network parameters. To make sure we have a good approximation of the posterior, we require the [KL divergence]() of \\(q(z|\\theta)\\) and \\(p(z|x)\\) to be small. The KL divergence in this situation is[^/concepts/elbo/#Yang2017] \\\[ \\begin{align} &\\operatorname{ D}\_\\text{KL}(q(z|\\theta)\\parallel p(z|x)) \\\\ =& -\\mathbb E\_q \\log\\frac{p(z|x)}{q(z|\\theta)} \\\\ =& -\\mathbb E\_q \\log\\frac{p(x, z)/p(x)}{q(z|\\theta)} \\\\ =& -\\mathbb E\_q \\log\\frac{p(x, z)}{q(z|\\theta)} - \\mathbb E\_q \\log\\frac{1}{p(x)} \\\\ =& - L + \\log p(x). \\end{align} \\\] Since \\(\\operatorname{D}\_{\\text{KL}}(q(z|\\theta)\\parallel p(z|x))\\geq 0\\), we have \\\[ \\log p(x) \\geq L, \\\] which also indicates that \\(L\\) is the lower bound of \\(\\log p(x)\\). > [!NOTE] > > **Jensen gap** > > The difference between \\(\\log p(x)\\) and \\(L\\) is the Jensen gap, i.e., > > \\\[ L - \\log p(x) = - \\operatorname{D}\_\\text{KL}(q(z|\\theta)\\parallel p(z|x)). \\\] --- **Related:** [Variational AutoEncoder]() · [Denoising Diffusion Probabilistic Models]() [^/concepts/elbo/#jensens-inequality-wiki]: Contributors to Wikimedia projects. Jensen’s inequality. In: Wikipedia \[Internet\]. 27 Aug 2021 \[cited 5 Sep 2021\]. Available: [https://en.wikipedia.org/wiki/Jensen%27s\_inequality]() [^/concepts/elbo/#Yang2017]: Yang X. Understanding the Variational Lower Bound. 14 Apr 2017 \[cited 5 Sep 2021\]. Available: [https://xyang35.github.io/2017/04/14/variational-lower-bound/]() # Alignment and Uniformity > [!NOTE] > > **In one minute** > > A good representation keeps similar instances close together and separates different ones. Wang and Isola (2020) call these two properties alignment and uniformity and describe both on a hypersphere. A good representation should be able to - separate different instances, and - cluster similar instances. Wang et al proposed two concepts that matches the above two ideas, alignment and uniformity, on a hypersphere[^/concepts/alignment-and-uniformity/#Wang2005]. ![From Wang et al]() > From Wang et al[^/concepts/alignment-and-uniformity/#Wang2005]. --- **Related:** [Contrastive Predictive Coding]() · [Deep Infomax]() [^/concepts/alignment-and-uniformity/#Wang2005]: Wang T, Isola P. Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere. arXiv \[cs.LG\]. 2020. Available: [http://arxiv.org/abs/2005.10242]() # Gini Impurity > [!NOTE] > > **In one minute** > > Gini impurity measures how mixed the classes in a dataset are: it is 0 when every record has the same class and largest when the classes are evenly mixed. The page defines it, works through two small examples and shows its values for two and for three classes. Suppose we have a dataset \\(\\{0,1\\}^{12}\\), which has 12 records and 2 possible classes of objects \\(\\{0,1\\}\\) in each record. The first example we investigate is a pure 0 dataset. | object | | :---: | | 0 | | 0 | | 0 | | 0 | | 0 | | 0 | | 0 | | 0 | | 0 | | 0 | | 0 | | 0 | For such an all-0 dataset, we would like to define its impurity as 0. Same with an all-1 dataset. For a dataset with 50% of 1 and 50% of 0, we would define its impurity as max due to the symmetries between 0 and 1. ## Definition Given a dataset \\(\\{0,1,...,d\\}^n\\), the Gini impurity is calculated as \\\[ G = \\sum\_{i \\in \\{0,1,...,d\\} } p(i)(1-p(i)), \\\] where \\(p(i)\\) is the probability of a randomly picked record being class \\(i\\). In the above example, we have two classes, \\(\\{0,1\\}\\). The probabilities are \\\[ \\begin{align} p(0) =& 1\\\\ p(1) =& 0 \\end{align}. \\\] The Gini impurity is \\\[ G = p(0)(1-p(0)) + p(1)(1-p(1)) = 0+0 = 0. \\\] ## Examples Suppose we have another dataset with 50% of the values being 1. | object | | :---: | | 0 | | 0 | | 1 | | 0 | | 0 | | 1 | | 1 | | 1 | | 0 | | 0 | | 1 | | 1 | The Gini impurity is \\\[ G = p(0)(1-p(0)) + p(1)(1-p(1)) = 0.5 \* 0.5+ 0.5\*0.5 = 0.5. \\\] For data with two possible values \\(\\{0,1\\}\\), the maximum Gini impurity is 0.5. The following chart shows all the possible values of the Gini impurity for a two-value dataset. The following heatmap shows the Gini impurity for data with two possible values. The color indicates the Gini impurity. ![Gini Two Values]() For data with three possible values, the Gini impurity is also visualized using the same chart given the condition that \\(p\_3 = 1 - p\_1 - p\_2\\). The following chart shows the Gini impurity for data with three possible values. The color indicates the Gini impurity. ![Gini 3 Values]() ## Try It: Gini Impurity of a Two-class Dataset Change how many of the 20 records are class 1 and see the Gini impurity move along its curve. An interactive chart of a two-class dataset of 20 records, with a slider for the number of records of class 1. It shows the Gini impurity and its curve over all mixes. It needs JavaScript. In short: the impurity is 0 for a pure dataset and largest, 0.5, for an even mix. --- **Related:** [Information Gain]() · [Tree-Based Models]() # Information Gain > [!NOTE] > > **In one minute** > > Information gain is the change in entropy when a dataset is split, and tree- based methods use it to judge a split. The page works through a decision tree node: its entropy before the split, the entropy of the two groups after it, and the gain as their difference. > > **Read first:** [Entropy]() Information gain is a frequently used metric in calculating the gain during a split in tree-based methods. First of all, the [entropy]() of a dataset is defined as \\\[ S = - \\sum\_i p\_i \\log p\_i - \\sum\_i (1-p\_i)\\log (1-p\_i), \\\] where \\(p\_i\\) is the probability of a class. The information gain is the change of entropy. To illustrate this idea, we use decision tree as an example. In a decision tree algorithm, we would split a node. Before splitting, we assign a label \\(m\\) to the node, the entropy is \\\[ S\_m = - p\_m \\log p\_m - (1-p\_m)\\log (1-p\_m). \\\] After the splitting, we have two groups that contributes to the entropy, group \\(L\\) and group \\(R\\) [^/concepts/information-gain/#bib-shalev-shwartz_ben-david_2014], \\\[ S'\_m = p\_L (- p\_m \\log p\_m - (1-p\_m)\\log (1-p\_m)) + p\_R (- p\_m \\log p\_m - (1-p\_m)\\log (1-p\_m)), \\\] where \\(p\_L\\) and \\(p\_R\\) are the probabilities of the two groups. Suppose we have 100 samples before splitting and 29 samples in the left group and 71 samples in the right group, we have \\(p\_L = 29/100\\) and \\(p\_R = 71/100\\). The information gain is the difference between \\(S\_m\\) and \\(S'\_m\\), \\\[ \\mathrm{Gain} = S\_m - S'\_m. \\\] ## Try It: The Gain of a Split A node of 40 records is split into a left and a right group. Set how many records are class 1, how many go left, and how many of those are class 1. Entropies are in nats. An interactive diagram of a node of 40 records split into two groups, with sliders for the class mix and the split. It shows the entropy of the node, of both groups, and the information gain. It needs JavaScript. In short: the gain is the entropy of the node minus the size-weighted entropy of the two groups; it is largest when both groups are pure and 0 when both have the same mix as the node. --- **Related:** [Gini Impurity]() · [Tree-Based Models]() [^/concepts/information-gain/#bib-shalev-shwartz_ben-david_2014]: Shalev-Shwartz S., Ben-David S.. Understanding Machine Learning: From Theory to Algorithms. *Cambridge University Press*. 2014. [https://doi.org/10.1017/CBO9781107298019]() # Generalization > [!NOTE] > > **In one minute** > > The generalization error is the difference between a model's loss on the whole population and its loss on the data it was fitted to. The population loss is unknown, so in practice it is approximated with a held-out test set. To measure the generalization, we define a generalization error[^/concepts/generalization/#bib-Roelofs2019-dm], \\\[ \\mathcal G = \\mathcal L\_{P}(\\hat f) - \\mathcal L\_E(\\hat f), \\\] where \\(\\mathcal L\_{P}\\) is the population loss, \\(\\mathcal L\_E\\) is the empirical loss, and \\(\\hat f\\) is our model by minimizing the empirical loss. However, we do not know the actual joint probability \\(p(x, y)\\) of our dataset \\(\\\\{x\_i, y\_i\\\\}\\). Thus the population loss is not known. In machine learning, we usually use cross validation where we split our dataset into train and test dataset. We approximate the population loss using the test dataset. --- **Related:** [Time Series Forecasting Evaluation]() [^/concepts/generalization/#bib-Roelofs2019-dm]: Roelofs R.. Measuring Generalization and Overfitting in Machine Learning. 2019. [https://escholarship.org/uc/item/6j01x9mz]() # Dynamic Time Warping (**DTW**) > [!NOTE] > > **In one minute** > > Dynamic time warping (DTW) finds the best way to align two sequences and measures their misalignment with a distance defined recursively, much like the Levenshtein distance between two words. It is useful for comparing series of different lengths, for example a forecast and an actual series. 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[^/concepts/timeseries-data.dtw/#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\\)th 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. > [!NOTE] > > **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. > [!NOTE] > > **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 [^/concepts/timeseries-data.dtw/#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[^/concepts/timeseries-data.dtw/#darts-dtw-metric]. ## Try It: Aligning Two Series The second series has the same shape as the first, shifted and stretched in time. The lines show which points DTW aligns, and the grid shows the accumulated cost \\(D\\) from the definition above with the cheapest path through it. The local distance is \\(d(x, y) = \\lvert x - y \\rvert\\). An interactive chart of two series of 18 points, with sliders that shift and stretch the second one in time. It shows which points dynamic time warping aligns, the accumulated cost matrix with the cheapest path, and the DTW distance next to the point-by-point distance. It needs JavaScript. In short: for the same shape at a different pace, the DTW distance stays small while the point-by-point distance grows. ## Examples The forecasting package darts provides a [demo of DTW](). --- **Related:** [DTW Barycenter Averaging]() · [Time Series Forecasting Metrics]() [^/concepts/timeseries-data.dtw/#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]() [^/concepts/timeseries-data.dtw/#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]() [^/concepts/timeseries-data.dtw/#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]() # DTW Barycenter Averaging > [!NOTE] > > **In one minute** > > DTW barycenter averaging (DBA), proposed by Petitjean et al., averages a set of time series: it constructs the series that is their barycenter under the dynamic time warping distance. > > **Read first:** [Dynamic Time Warping (**DTW**)]() [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 [^/concepts/timeseries-data.dtw-barycenter-averaging/#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**). > [!NOTE] > > **DBA Implementation** > > [https://github.com/fpetitjean/DBA]() --- **Related:** [Data Augmentation for Time Series]() [^/concepts/timeseries-data.dtw-barycenter-averaging/#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]() [^/concepts/timeseries-data.dtw-barycenter-averaging/#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]() # Contrastive Models > [!TIP] > > **Contrastive Models** > > Learn to compare. [^/self-supervised/contrastive/intro/#Liu2020]: Liu X, Zhang F, Hou Z, Wang Z, Mian L, Zhang J, et al. Self-supervised Learning: Generative or Contrastive. arXiv \[cs.LG\]. 2020. Available: [http://arxiv.org/abs/2006.08218]() # Deep Infomax > [!NOTE] > > **In one minute** > > Deep InfoMax trains an encoder by maximizing an estimate of the mutual information between the input and its encoding. Doing this for the whole input is often not enough, so it is also done between local patches of the feature maps and the encoding, which pushes the encoding to use information that is shared across the input. > > **Read first:** [Mutual Information]() > [!TIP] > > **Max Global Mutual Information** > > Why not just use the global mutual information of the input and encoder output as the objective? > > > ... maximizing MI between the complete input and the encoder output (i.e., global MI) is often insufficient for learning useful representations. > > > > \-- Hjelm et al[^/self-supervised/contrastive/deep-infomax/#Devon2018] Mutual information maximization is performed on the input of the encoder \\(X\\) and the encoded feature \\(\\hat X=E\_\\theta (X)\\), \\\[ \\operatorname{arg\~max}\_\\theta I(X;E\_\\theta (X)). \\\] Being a quantity that is notoriously hard to compute, mutual information \\(I(X;E\_\\theta (X))\\) is usually estimated using its lower bound, which depends on a choice of a functional \\(T\_\\omega\\). Thus the objective will be maximizing a parametrized mutual information estimation, \\\[ \\operatorname{arg\~max}\_{\\theta, \\omega} \\hat I\_\\omega(X;E\_\\theta (X)) \\\] > [!NOTE] > > **Local or Global** > > Two approaches to apply mutual information on encoders: > > - Global mutual information of full input and full encoding. This is useful for reconstruction of the input. > - Local mutual information of local patches of input full encoding. This is useful for classification. ## Local Mutual Information To compare local features to the encoder output, we need to extract values from inside the encoder, i.e., \\\[ E\_{\\theta\_f, \\theta\_C} = f\_{\\theta\_f} \\circ C\_{\\theta\_C}. \\\] The first step, \\(C\_{\\theta\_C}\\) is to map the input into feature maps, the second step, \\(f\_{\\theta\_f}\\) maps the feature maps into the encoding. The feature map \\(C\_{\\theta\_C}\\) is splitted into patches, \\(C\_{\\theta\_C}=\\left\\{ C\_\\theta^{(i)} \\right\\}\\). The objective is \\\[ \\operatorname{arg\~max}\_{\\theta\_f, \\theta\_C, \\omega}\\mathbb E\_{i} \\left\[ \\hat I\_\\omega( C\_{\\theta\_C}^{(i)} ;E\_\\theta (X)) \\right\]. \\\] ![Deep InfoMAX Local]() > [!TIP] > > **Why does local mutual information help** > > Hjelm et al explained the idea behind choosing local mutual information[^/self-supervised/contrastive/deep-infomax/#Devon2018]. > > Global mutual information doesn't specify what is the meaningful information. Some very local noise can also be treated as meaningful information too. > > Local mutual information splits the input into patches, and calculate the mutual information between each patch and the encoding. If the model only uses some information from a few local patches, the mutual information objective will be small after averaging all the patches. Thus local mutual information forces the model to use information that is global in the input. ## Code - [rdevon/DIM](): by the authors - [DuaneNielsen/DeepInfomaxPytorch](): a clean implementation --- **Related:** [Contrastive Predictive Coding]() · [Alignment and Uniformity]() [^/self-supervised/contrastive/deep-infomax/#Devon2018]: Devon Hjelm R, Fedorov A, Lavoie-Marchildon S, Grewal K, Bachman P, Trischler A, et al. Learning deep representations by mutual information estimation and maximization. arXiv \[stat.ML\]. 2018. Available: [http://arxiv.org/abs/1808.06670]() [^/self-supervised/contrastive/deep-infomax/#Newell2020]: Newell A, Deng J. How Useful is Self-Supervised Pretraining for Visual Tasks? arXiv \[cs.CV\]. 2020. Available: [http://arxiv.org/abs/2003.14323]() # Contrastive Predictive Coding > [!NOTE] > > **In one minute** > > Contrastive predictive coding (CPC) encodes each segment of a sequence, models the encodings with an autoregressive model, and trains with the InfoNCE loss, which estimates a lower bound of mutual information. The encoders can then be used for downstream tasks such as classification. > > **Read first:** [Mutual Information]() · [Autoregressive Model]() Contrastive Predictive Coding, CPC, is an autoregressive model combined with InfoNCE loss[^/self-supervised/contrastive/contrastive-predictive-coding/#Oord2018]. > [!NOTE] > > **Predictive Coding** > > As a related topic, predictive coding is a different scheme than backpropagation. Predictive coding updates the weights using local updating rules only[^/self-supervised/contrastive/contrastive-predictive-coding/#bib-Millidge2020-mr]. There are two key ideas in CPC: - Autoregressive models in latent space, and - InfoNCE loss that combines mutual information and NCE. For the series of segments, \\(\\{x\_t\\}\\), we apply an encoder on each segment, and calculate the latent space, \\(\\{{\\color{blue}\\hat x\_t}\\}\\). The latent space \\(\\{{\\color{blue}\\hat x\_t}\\}\\) is then modeled using an autoregressive model to calculate the coding, \\(\\{{\\color{red}c\_t}\\}\\). ![CPC overview]() van den Oord et al The loss is built on NCE to estimate the lower bound of mutual information, \\\[ \\mathcal L = -\\mathbb E\_X \\left\[ \\log \\frac{f\_k(x\_{t+k}, c\_t)}{\\sum\_{j} f\_k(x\_{j}, c\_t) } \\right\], \\\] where \\(f\_k(x\_{t+i}, c\_t)\\) is estimated using a log-bilinear model, \\(f\_k(x\_{t+i}, c\_t) = \\exp\\left( z\_{t+i} W\_i c\_t \\right)\\). This is also a cross entropy loss. Minimizing \\(\\mathcal L\\) leads to a \\(f\_k\\) that estimates the ratio[^/self-supervised/contrastive/contrastive-predictive-coding/#Oord2018] \\\[ \\frac{p(x\_{t+k}\\mid c\_t)}{p(x\_{t+k})} = \\frac{p(x\_{t+k}, c\_t)}{p(x\_{t+k})p(c\_t)}. \\\] We can perform downstream tasks such as classifications using the encoders. > [!WARNING] > > **Maximizing this lower bound?** > > This so-called lower bound for mutual information in this case is not always going to work[^/self-supervised/contrastive/contrastive-predictive-coding/#Newell2020]. In some cases, the representations learned using this lower bound doesn't help or even worsen the performance of downstream tasks. ## Code [rschwarz15/CPCV2-PyTorch]() --- **Related:** [Deep Infomax]() · [Alignment and Uniformity]() [^/self-supervised/contrastive/contrastive-predictive-coding/#Newell2020]: Newell A, Deng J. How Useful is Self-Supervised Pretraining for Visual Tasks? arXiv \[cs.CV\]. 2020. Available: [http://arxiv.org/abs/2003.14323]() [^/self-supervised/contrastive/contrastive-predictive-coding/#Oord2018]: van den Oord A, Li Y, Vinyals O. Representation learning with Contrastive Predictive Coding. arXiv \[cs.LG\]. 2018. Available: [http://arxiv.org/abs/1807.03748]() [^/self-supervised/contrastive/contrastive-predictive-coding/#bib-Millidge2020-mr]: Millidge B., Tschantz A., Buckley C.L.. Predictive Coding Approximates Backprop along Arbitrary Computation Graphs. 2020. [http://arxiv.org/abs/2006.04182]() # MADE: Masked Autoencoder for Distribution Estimation # MAF: Masked Autoregressive Flow # f-GAN > [!NOTE] > > **In one minute** > > f-GAN generalizes the GAN: instead of the Jensen-Shannon divergence, it estimates an f-divergence between the data distribution and the generated distribution. Training searches for the saddle point of a variational objective, and a particular choice of functions recovers the loss of the original GAN. > > **Read first:** [GAN]() · [f-Divergence]() The essence of [GAN]() is comparing the generated distribution \\(p\_G\\) and the data distribution \\(p\_\\text{data}\\). The vanilla GAN considers the Jensen-Shannon divergence \\(\\operatorname{D}\_\\text{JS}(p\_\\text{data}\\Vert p\_{G})\\). The discriminator \\({\\color{green}D}\\) serves the purpose of forcing this divergence to be small. > [!NOTE] > > **Why do we need the discriminator?** > > If the JS divergence is an objective, why do we need the discriminator? Even in f-GAN we need a functional to approximate the f-divergence. This functional we choose works like the discriminator of GAN. There exists a more generic form of JS divergence, which is called [f-divergence]()[^/self-supervised/adversarial/f-gan/#f-divergence_wiki]. f-GAN obtains the model by estimating the f-divergence between the data distribution and the generated distribution[^/self-supervised/adversarial/f-gan/#Nowozin2016]. ## Variational Divergence Minimization The Variational Divergence Minimization (VDM) extends the variational estimation of f-divergence[^/self-supervised/adversarial/f-gan/#Nowozin2016]. VDM searches for the saddle point of an objective \\(F({\\color{red}\\theta}, {\\color{blue}\\omega})\\), i.e., min w.r.t. \\(\\theta\\) and max w.r.t \\({\\color{blue}\\omega}\\), where \\({\\color{red}\\theta}\\) is the parameter set of the generator \\({\\color{red}Q\_\\theta}\\), and \\({\\color{blue}\\omega}\\) is the parameter set of the variational approximation to estimate f-divergence, \\({\\color{blue}T\_\\omega}\\). The objective \\(F({\\color{red}\\theta}, {\\color{blue}\\omega})\\) is related to the choice of \\(f\\) in f-divergence and the variational functional \\({\\color{blue}T}\\), \\\[ \\begin{align} & F(\\theta, \\omega)\\\\ =& \\mathbb E\_{x\\sim p\_\\text{data}} \\left\[ {\\color{blue}T\_\\omega}(x) \\right\] - \\mathbb E\_{x\\sim {\\color{red}Q\_\\theta} } \\left\[ f^\*({\\color{blue}T\_\\omega}(x)) \\right\] \\\\ =& \\mathbb E\_{x\\sim p\_\\text{data}} \\left\[ g\_f(V\_{\\color{blue}\\omega}(x)) \\right\] - \\mathbb E\_{x\\sim {\\color{red}Q\_\\theta} } \\left\[ f^\*(g\_f(V\_{\\color{blue}\\omega}(x))) \\right\]. \\end{align} \\\] In the above objective, - \\(f^\*\\) is the [Legendre–Fenchel transformation]() of \\(f\\), i.e., \\(f^\*(t) = \\operatorname{sup}\_{u\\in \\mathrm{dom}\_f}\\left\\{ ut - f(u) \\right\\}\\). > [!TIP] > > **\\(T\\)** > > The function \\(T\\) is used to estimate the lower bound of f-divergence[^/self-supervised/adversarial/f-gan/#Nowozin2016]. > [!TIP] > > **Choice of \\(g\_f\\) and \\(V\\)** > > Nowozin et al provided a table for \\(g\_f\\) and \\(V\\)[^/self-supervised/adversarial/f-gan/#Nowozin2016]. > > ![]() We estimate - \\(\\mathbb E\_{x\\sim p\_\\text{data}}\\) by sampling from the mini-batch, and - \\(\\mathbb E\_{x\\sim {\\color{red}Q\_\\theta} }\\) by sampling from the generator. > [!NOTE] > > **Reduce to GAN** > > The VDM loss can be reduced to the [loss of GAN]() by setting[^/self-supervised/adversarial/f-gan/#Nowozin2016] > > \\\[ \\begin{align} \\log {\\color{green}D\_\\omega} =& g\_f(V\_{\\color{blue}\\omega}(x)) \\\\ \\log \\left( 1 - {\\color{green}D\_\\omega} \\right) =& -f^\*\\left( g\_f(V\_{\\color{blue}\\omega}(x)) \\right). \\end{align} \\\] > > It is straightforward to validate that the following result is a solution to the above set of equations, > > \\\[ g\_f(V) = \\log \\frac{1}{1 + e^{-V}}. \\\] ## Code - [minlee077/f-GAN-pytorch]() - [shayneobrien/generative-models]() --- **Related:** [InfoGAN]() [^/self-supervised/adversarial/f-gan/#f-divergence_wiki]: Contributors to Wikimedia projects. F-divergence. In: Wikipedia \[Internet\]. 17 Jul 2021 \[cited 6 Sep 2021\]. Available: [https://en.wikipedia.org/wiki/F-divergence\#Instances\_of\_f-divergences]() [^/self-supervised/adversarial/f-gan/#Nowozin2016]: Nowozin S, Cseke B, Tomioka R. f-GAN: Training Generative Neural Samplers using Variational Divergence Minimization. arXiv \[stat.ML\]. 2016. Available: [http://arxiv.org/abs/1606.00709]() [^/self-supervised/adversarial/f-gan/#convex_conjugate_wiki]: Contributors to Wikimedia projects. Convex conjugate. In: Wikipedia \[Internet\]. 20 Feb 2021 \[cited 7 Sep 2021\]. Available: [https://en.wikipedia.org/wiki/Convex\_conjugate]() # InfoGAN > [!NOTE] > > **In one minute** > > InfoGAN makes the latent space of a GAN more interpretable. Next to the random noise it feeds the generator a latent code, and it adds the mutual information between that code and the generated data to the GAN objective, so the generator is penalized when it loses the information in the code. > > **Read first:** [GAN]() · [Mutual Information]() In GAN, the latent space input is usually random noise, e.g., Gaussian noise. The objective of [GAN]() is a very generic one. It doesn't say anything about how exactly the latent space will be used. This is not desirable in many problems. We would like to have more interpretability in the latent space. InfoGAN introduced constraints to the objective to enforce interpretability of the latent space[^/self-supervised/adversarial/infogan/#Chen2016]. ## Constraint The constraint InfoGAN proposed is [mutual information](), \\\[ \\underset{{\\color{red}G}}{\\operatorname{min}} \\underset{{\\color{green}D}}{\\operatorname{max}} V\_I ({\\color{green}D}, {\\color{red}G}) = V({\\color{green}D}, {\\color{red}G}) - \\lambda I(c; {\\color{red}G}(z,c)), \\\] where - \\(c\\) is the latent code, - \\(z\\) is the random noise input, - \\(V({\\color{green}D}, {\\color{red}G})\\) is the objective of GAN, - \\(I(c; {\\color{red}G}(z,c))\\) is the mutual information between the input latent code and generated data. Using the lambda multiplier, we punish the model if the generator loses information in latent code \\(c\\). ## Training ![InfoGAN]() The training steps are almost the same as [GAN]() but with one extra loss to be calculated in each mini-batch. 1. Train \\(\\color{red}G\\) using loss: \\(\\operatorname{MSE}(v', v)\\); 2. Train \\(\\color{green}D\\) using loss: \\(\\operatorname{MSE}(v', v)\\); 3. Apply Constraint: 1. Sample data from mini-batch; 2. Calculate loss \\(\\lambda\_{l} H(l';l)+\\lambda\_c \\operatorname{MSE}(c,c')\\) ## Code [eriklindernoren/PyTorch-GAN]() --- **Related:** [f-GAN]() [^/self-supervised/adversarial/infogan/#Chen2016]: Chen X, Duan Y, Houthooft R, Schulman J, Sutskever I, Abbeel P. InfoGAN: Interpretable Representation Learning by Information Maximizing Generative Adversarial Nets. arXiv \[cs.LG\]. 2016. Available: [http://arxiv.org/abs/1606.03657]() [^/self-supervised/adversarial/infogan/#Agakov2004]: Agakov DBF. The im algorithm: a variational approach to information maximization. Adv Neural Inf Process Syst. 2004. Available: [https://books.google.com/books?hl=en&lr=&id=0F-9C7K8fQ8C&oi=fnd&pg=PA201&dq=Algorithm+variational+approach+Information+Maximization+Barber+Agakov&ots=TJGrkVS610&sig=yTKM2ZdcZQBTY4e5Vqk42ayUDxo]() # About # Map of the Book > [!NOTE] > > **In one minute** > > Every page of this book as a dot, coloured by chapter, with a line for every link between two pages. Select a page to see what it links to and what links to it, or switch to the list of pages by chapter. Orange marks the pages a selected page links to, blue the pages that link to it. The List view shows the same pages as buttons, grouped by chapter. An interactive map of the pages of this book and the links between them. It needs JavaScript; the navigation lists the same pages. # Roadmap When I switched to data science, I built [my digital garden, datumorphism](). I deliberately designed this digital garden as my second brain. As a result, most of the articles are fragments of knowledge and require context to understand them. Making bricks is easy but assembling them into a house is not easy. So I have decided to use this repository to practice my house-building techniques. I do not have a finished blueprint yet. But I have a framework in my mind: I want to consolidate some of my thoughts and learnings in an organized way. However, I do not want to compile a reference book, as [datumorphism]() already serves this purpose. I am thinking of an ## Open Source This is an open-source project on GitHub: . ## How do I Write It I am trying out a more "agile" method. Instead of finishing the whole project at once, I will release the book by chapter. A few thoughts on this plan: - Each new section should be a PR. - Release on every new section. ## How do I track the Progress I use GitHub Projects. [Here is my board](). # Changelog # Other pages # NCE # Diffusion Model References: 1. [`pts/model/time_grad/time_grad_network.py`]() ``` import dataclasses from functools import cached_property import numpy as np import pandas as pd import plotly.express as px import torch import torch.nn as nn from loguru import logger ``` ``` @dataclasses.dataclass class DiffusionParams: """ """ steps: int beta: float @cached_property def alpha(self) -> float: """ """ return 1.0 - self.beta @cached_property def alpha_bar_by_step(self) -> np.ndarray: """ """ return np.cumprod(self.alpha_by_step) @cached_property def beta_by_step(self) -> np.ndarray: """ """ return np.array([self.beta] * self.steps) @cached_property def alpha_by_step(self) -> np.ndarray: """ """ return np.array([self.alpha] * self.steps) # @cached_property # def sigma_q_squared(self) -> float: # r""" # $$ # \sigma_q^2(t) = \frac{ # (1 - \alpha(t))(1 - \bar\alpha(t-1)) # }{1 - \bar\alpha(t)} # $$ # """ # sigma_q_squared = ( # 1 - self.alpha_by_step[1:] # ) * (1 - self.alpha_bar_by_step[:-1]) / (1 - self.alpha_bar_by_step[1:]) # return np.insert(sigma_q_squared, 0, 0) class Diffusion(nn.Module): def __init__( self, batch_size: int, params: DiffusionParams, dtype: torch.dtype = torch.float32, ): self.batch_size = batch_size self.params = params self.dtype = dtype @cached_property def alpha_bar_by_step(self) -> torch.Tensor: return torch.tensor(self.params.alpha_bar_by_step, dtype=self.dtype).detach() @cached_property def alpha_by_step(self) -> torch.Tensor: return torch.tensor(self.params.alpha_by_step, dtype=self.dtype).detach() # @cached_property # def sigma_q_squared(self) -> torch.Tensor: # return torch.tensor(self.params.sigma_q_squared, dtype=self.dtype) def likelihood(self): pass def _gaussian(self, n_var: int, length: int) -> torch.Tensor: return torch.normal(mean=0, std=1, size=(n_var, length)) @cached_property def noise(self) -> torch.Tensor: return self._gaussian(self.batch_size, self.params.steps).detach() def _forward_process(self, initial: torch.Tensor) -> torch.Tensor: return ( torch.outer( initial, torch.sqrt(self.alpha_bar_by_step), ) + torch.sqrt(1 - self.alpha_bar_by_step) * self.noise ) def _forward_process_by_step(self, state: torch.Tensor, step: int) -> torch.Tensor: r"""Assuming that we know the noise at step $t$, $$ x(t) = \sqrt{\alpha(t)}x(t-1) + \sqrt{1 - \alpha(t)}\epsilon(t) $$ """ return ( torch.sqrt(self.alpha_by_step[step]) * state + torch.sqrt(1 - self.alpha_by_step[step]) * self.noise[:, step] ) def _inverse_process_by_step(self, state: torch.Tensor, step: int) -> torch.Tensor: r"""Assuming that we know the noise at step $t$, $$ x(t-1) = \frac{1}{\sqrt{\alpha(t)}} (x(t) - \sqrt{1 - \alpha(t)}\epsilon(t)) $$ """ return ( state - torch.sqrt(1 - self.alpha_by_step[step]) * self.noise[:, step] ) / torch.sqrt(self.alpha_by_step[step]) def forward(self): pass ``` ``` diffusion_params = DiffusionParams( steps=100, beta=0.005, # beta=0, ) diffusion_batch_size = 1000 # diffusion_batch_size = 2 diffusion_process = Diffusion(diffusion_batch_size, diffusion_params) ``` ``` # diffusion_initial_x = torch.sin( # torch.linspace(0, 1, diffusion_batch_size) # .reshape(diffusion_batch_size) # ) diffusion_initial_x = torch.rand(diffusion_batch_size) # diffusion_initial_x = ( # torch.distributions.Beta(torch.tensor([0.5]), torch.tensor([0.5])) # .sample((diffusion_batch_size, 1)) # .reshape(diffusion_batch_size) # ) diffusion_initial_x ``` ``` tensor([7.7775e-01, 2.5996e-03, 8.9573e-01, 2.8487e-02, 8.6702e-01, 6.3107e-01, 1.4697e-02, 5.6454e-01, 4.8029e-01, 3.7040e-01, 1.6683e-01, 1.2759e-01, 2.5198e-01, 7.2493e-01, 5.6882e-01, 6.8986e-01, 2.5026e-01, 4.2498e-01, 1.4950e-01, 6.0333e-02, 9.6513e-01, 7.2014e-01, 5.3760e-01, 2.4866e-01, 6.2440e-02, 3.5743e-01, 6.3690e-01, 5.4904e-01, 6.6745e-01, 2.7166e-01, 8.4943e-02, 5.8873e-01, 5.2532e-01, 8.4310e-01, 4.8329e-01, 2.1650e-01, 7.9686e-01, 6.1594e-01, 6.0277e-01, 9.7054e-01, 3.9735e-02, 9.0588e-01, 9.9158e-01, 7.8630e-01, 8.5138e-01, 2.3773e-01, 6.2784e-01, 7.2167e-01, 3.2273e-01, 1.7800e-01, 4.6897e-01, 1.3501e-01, 7.2497e-01, 6.2923e-01, 6.0175e-01, 7.1988e-01, 4.4167e-01, 7.4963e-01, 5.7014e-01, 9.5285e-01, 1.9862e-01, 2.0671e-01, 5.4677e-01, 4.3996e-02, 1.8597e-01, 6.6931e-01, 4.9900e-01, 7.9565e-01, 3.7688e-01, 5.2546e-01, 2.0067e-01, 1.4955e-01, 7.3732e-01, 3.2959e-01, 4.9122e-01, 9.3785e-01, 6.2275e-01, 6.8126e-01, 7.0630e-01, 6.1048e-01, 6.0603e-02, 4.7585e-01, 5.8108e-01, 2.2769e-01, 5.3971e-01, 6.8321e-01, 1.6413e-01, 1.9077e-01, 8.4308e-01, 2.9310e-01, 8.6060e-01, 5.1602e-01, 6.7872e-01, 9.7942e-01, 7.3843e-01, 8.1786e-01, 7.7456e-04, 4.9613e-01, 1.0111e-01, 9.8224e-01, 9.1857e-01, 2.4136e-01, 3.7621e-01, 2.4404e-01, 1.3175e-01, 3.8267e-01, 1.3462e-01, 2.7758e-01, 7.7329e-01, 6.2881e-01, 9.2023e-01, 9.2068e-01, 9.7770e-01, 9.0131e-01, 2.2477e-01, 5.4225e-01, 5.4110e-01, 1.6160e-02, 6.3782e-01, 3.3365e-01, 9.5199e-01, 5.7746e-01, 8.4396e-01, 4.8976e-01, 6.4052e-01, 9.0340e-01, 5.0595e-01, 6.4192e-01, 8.8458e-01, 2.5237e-01, 9.3700e-01, 1.4786e-01, 2.3235e-01, 8.7961e-01, 1.9093e-01, 8.6167e-01, 7.8171e-01, 9.7507e-01, 7.7072e-01, 9.9421e-01, 8.8434e-01, 2.1071e-01, 8.7159e-01, 2.4253e-01, 4.7680e-01, 6.6068e-01, 6.2021e-01, 2.2684e-01, 3.5826e-01, 6.4616e-01, 7.6931e-01, 2.6578e-01, 6.0351e-01, 8.5048e-01, 4.4067e-01, 6.2625e-01, 7.5104e-01, 2.7441e-01, 8.8279e-01, 6.9316e-01, 1.1449e-01, 5.2794e-01, 6.7864e-01, 2.3386e-01, 8.4397e-01, 7.9805e-01, 6.1662e-03, 8.2585e-02, 2.1492e-01, 4.6439e-01, 6.6296e-02, 7.6129e-01, 8.2308e-01, 5.4854e-01, 5.7754e-01, 3.5968e-01, 9.7841e-01, 6.4619e-02, 6.0760e-01, 6.8189e-01, 6.0830e-01, 7.3125e-01, 6.1340e-01, 9.1391e-01, 8.8631e-01, 2.2860e-01, 3.2060e-01, 2.3429e-01, 3.0797e-01, 5.4123e-01, 9.4756e-02, 7.6480e-01, 5.4720e-01, 7.9341e-01, 2.3891e-01, 1.0985e-01, 4.8592e-02, 4.8016e-01, 4.3936e-01, 3.2796e-01, 6.4088e-01, 4.0451e-02, 2.5374e-01, 1.5751e-01, 8.4985e-01, 5.4544e-04, 6.6412e-01, 9.9078e-01, 2.6698e-01, 9.1085e-01, 1.1263e-01, 6.0111e-02, 1.0284e-01, 3.7929e-01, 5.8882e-01, 3.9850e-01, 5.8496e-01, 7.2087e-01, 9.5728e-01, 5.9866e-01, 5.5852e-01, 5.3049e-01, 1.0203e-01, 6.8761e-01, 9.5779e-01, 9.8760e-01, 3.0381e-01, 6.5888e-01, 7.5650e-01, 8.7441e-01, 9.9628e-01, 6.2763e-01, 1.6729e-01, 5.5852e-01, 7.6903e-01, 5.1704e-02, 5.2176e-01, 8.3529e-01, 2.0617e-01, 9.1318e-01, 6.5168e-01, 7.1317e-01, 4.5139e-01, 9.4695e-01, 3.9636e-01, 7.5042e-01, 6.7440e-01, 8.9903e-01, 1.7006e-01, 3.3402e-01, 7.0436e-01, 9.0939e-01, 6.8231e-01, 7.9774e-01, 5.3023e-01, 5.1610e-01, 7.6396e-01, 5.1958e-01, 3.2967e-01, 3.5324e-01, 6.9631e-01, 7.1903e-01, 9.7596e-01, 9.2130e-03, 4.2002e-01, 6.5758e-02, 8.3896e-01, 6.7460e-02, 8.5848e-01, 8.6921e-01, 2.8666e-01, 7.7573e-01, 6.9970e-01, 4.3003e-01, 2.7693e-01, 4.2843e-01, 5.2535e-01, 6.5434e-02, 2.5410e-01, 9.5170e-01, 3.6324e-01, 7.7636e-01, 7.8613e-01, 1.7817e-01, 4.0108e-01, 7.6408e-01, 4.5393e-01, 8.9434e-01, 5.1267e-01, 7.5307e-01, 2.5809e-01, 1.5458e-01, 2.7147e-01, 7.3079e-01, 3.8734e-01, 3.8298e-01, 3.0626e-02, 3.1052e-01, 7.3706e-01, 8.8986e-01, 5.7330e-01, 4.3292e-01, 2.0249e-01, 4.1284e-01, 6.5766e-01, 1.8121e-01, 4.2965e-01, 5.8626e-01, 3.6327e-01, 4.0321e-01, 6.9334e-01, 6.5409e-01, 4.2427e-01, 1.6489e-01, 8.5117e-02, 6.3145e-01, 3.2458e-01, 7.8721e-01, 3.0656e-01, 5.8722e-01, 3.0550e-01, 6.4041e-01, 1.6568e-02, 8.7289e-01, 4.2902e-02, 6.4242e-01, 7.3430e-01, 3.8101e-01, 7.0357e-01, 7.5356e-02, 2.1209e-01, 8.9619e-01, 9.7166e-01, 3.9159e-01, 6.3906e-01, 6.8285e-01, 4.2104e-01, 4.6377e-01, 6.8677e-01, 3.2269e-01, 6.6650e-01, 2.4675e-01, 2.9736e-01, 4.8034e-01, 4.9603e-01, 2.6741e-01, 7.9447e-01, 3.0797e-01, 1.5957e-01, 3.4549e-01, 6.9508e-01, 8.8407e-01, 9.1275e-02, 3.7905e-01, 8.1314e-01, 8.8868e-01, 4.8188e-01, 9.5437e-01, 7.9598e-01, 4.1531e-01, 7.0536e-01, 9.0533e-01, 6.8560e-01, 8.9861e-01, 1.0241e-01, 6.3237e-01, 7.3239e-01, 4.3845e-01, 9.8481e-02, 5.7864e-01, 9.6508e-01, 6.0801e-01, 3.5014e-01, 5.1751e-01, 8.0159e-01, 1.1674e-01, 2.4511e-01, 8.7595e-01, 4.9931e-01, 2.0810e-01, 4.6225e-01, 3.1085e-02, 2.4318e-01, 5.6451e-01, 8.3331e-01, 3.9343e-01, 5.2788e-01, 9.6819e-01, 2.0900e-01, 9.3971e-01, 6.4002e-01, 2.4179e-02, 2.9278e-01, 3.5854e-01, 1.6630e-01, 4.4320e-01, 4.8403e-01, 9.9841e-01, 4.0711e-01, 5.2067e-01, 9.4308e-02, 1.5326e-01, 9.2903e-01, 4.2009e-01, 3.5016e-01, 3.8493e-01, 4.1645e-01, 5.0718e-01, 9.2889e-01, 5.9775e-01, 6.6466e-02, 6.0154e-01, 7.5452e-01, 7.1951e-02, 5.3474e-01, 3.4430e-01, 3.2890e-01, 6.7426e-02, 9.7682e-01, 1.0032e-01, 7.3257e-01, 3.2214e-01, 4.6050e-01, 8.2653e-01, 2.6279e-01, 3.5414e-02, 9.9554e-01, 9.5582e-01, 5.4223e-01, 3.2331e-01, 8.2948e-01, 4.7821e-02, 5.5640e-01, 6.6080e-01, 5.7909e-01, 4.5128e-01, 9.6965e-01, 7.8449e-01, 5.8548e-01, 9.4105e-01, 7.1899e-01, 6.7650e-01, 2.9274e-01, 7.0456e-01, 8.8447e-01, 8.0095e-01, 4.6605e-01, 7.8801e-01, 5.4600e-01, 8.7844e-01, 8.1421e-02, 1.8782e-01, 9.0921e-01, 1.1820e-01, 6.8928e-01, 7.1021e-01, 8.9415e-01, 1.0278e-01, 7.3842e-01, 1.5351e-01, 1.1304e-01, 7.7400e-01, 2.6465e-01, 1.8265e-01, 7.6791e-01, 8.6094e-01, 8.7606e-01, 1.0116e-01, 2.2351e-01, 8.2986e-01, 6.7074e-01, 2.2733e-01, 2.8505e-01, 4.6601e-01, 4.1463e-01, 6.8858e-01, 3.0736e-01, 3.4557e-01, 9.9313e-01, 3.6972e-01, 1.8696e-01, 1.0080e-01, 3.4693e-01, 1.5132e-01, 3.4358e-01, 9.3118e-01, 4.8359e-02, 7.4505e-01, 7.5342e-01, 4.9223e-01, 6.8864e-01, 1.1586e-01, 1.0392e-01, 2.9166e-02, 4.0281e-01, 2.6653e-01, 8.7507e-02, 3.5574e-01, 4.9399e-01, 3.8885e-01, 1.6902e-02, 7.9361e-01, 6.3418e-02, 1.1974e-01, 4.8186e-01, 7.5273e-01, 1.6932e-01, 7.9584e-01, 3.6735e-01, 4.8952e-01, 7.6881e-01, 3.0617e-01, 6.2502e-01, 8.8967e-01, 8.3056e-01, 7.3021e-01, 2.8281e-01, 6.3301e-01, 4.9556e-02, 4.3477e-01, 5.1404e-01, 9.4736e-01, 3.7648e-01, 4.2239e-01, 1.6176e-02, 8.2439e-01, 1.2797e-01, 7.1985e-01, 7.1590e-01, 7.0463e-01, 9.8746e-01, 8.2056e-01, 5.2468e-01, 1.5252e-01, 3.0611e-01, 7.2840e-01, 9.6575e-01, 8.0366e-01, 3.1065e-01, 7.0294e-01, 1.8660e-01, 8.7565e-04, 7.2417e-01, 3.4084e-01, 5.4660e-02, 3.6320e-01, 6.8421e-01, 3.5242e-02, 6.5374e-01, 2.8833e-02, 3.3636e-01, 5.7133e-01, 2.7856e-01, 9.4240e-01, 1.8305e-01, 6.0760e-01, 1.2833e-01, 4.7069e-01, 3.0750e-01, 2.2685e-01, 7.3897e-01, 3.7941e-01, 8.8522e-01, 7.2371e-01, 5.3601e-03, 2.9866e-01, 1.4292e-01, 1.4680e-01, 6.4781e-02, 5.7554e-01, 4.2656e-01, 6.8550e-01, 6.6180e-01, 5.5994e-01, 1.0606e-01, 2.0924e-01, 3.2525e-01, 7.5358e-01, 9.9037e-03, 6.5474e-01, 7.1112e-01, 2.6596e-01, 7.4475e-01, 5.3266e-01, 1.6579e-01, 2.2054e-01, 5.1728e-02, 7.0911e-02, 8.3083e-01, 1.8573e-01, 2.9299e-01, 1.9889e-01, 8.9104e-01, 7.2713e-01, 8.4764e-01, 4.3802e-01, 5.4559e-01, 5.1432e-01, 9.4528e-01, 5.4897e-01, 2.1803e-01, 3.7670e-01, 7.9393e-02, 8.0621e-01, 7.3804e-01, 4.9906e-01, 6.1492e-01, 7.6444e-01, 3.8084e-01, 7.8545e-01, 9.4032e-01, 8.0139e-01, 9.1406e-01, 3.4410e-02, 6.7650e-01, 4.8422e-01, 5.1009e-03, 3.4851e-01, 1.3183e-01, 5.0791e-01, 2.7883e-01, 9.0753e-01, 7.5274e-01, 1.1187e-01, 7.2958e-02, 4.2475e-01, 4.6859e-01, 3.7485e-01, 1.5859e-01, 9.2948e-01, 6.1692e-01, 2.8492e-01, 3.7137e-03, 5.0841e-01, 4.2595e-01, 7.2586e-01, 4.0947e-01, 4.5109e-01, 9.3411e-01, 5.2250e-01, 1.4618e-02, 7.6092e-01, 6.2295e-01, 8.0388e-01, 5.9361e-01, 5.5299e-01, 4.2948e-01, 9.3728e-01, 3.8873e-01, 2.0691e-01, 5.4546e-01, 6.5319e-01, 6.8088e-01, 4.8318e-01, 9.8598e-01, 9.4376e-01, 4.6390e-01, 6.5581e-02, 4.4518e-01, 8.5712e-01, 1.2211e-01, 8.6805e-01, 6.4558e-01, 1.8900e-01, 7.4766e-01, 6.8070e-01, 7.1700e-01, 3.7970e-01, 1.8861e-02, 1.0999e-01, 7.1632e-01, 1.3020e-01, 3.0324e-01, 7.4707e-01, 8.6258e-01, 6.5321e-02, 3.6113e-01, 5.5212e-01, 3.0473e-01, 6.5039e-01, 1.4016e-01, 7.1889e-01, 2.7115e-01, 4.7970e-01, 1.8653e-02, 9.2409e-01, 3.7443e-01, 8.6519e-01, 8.1863e-01, 1.9659e-01, 6.2090e-02, 2.6739e-01, 4.4408e-01, 4.9536e-02, 3.1252e-01, 4.8672e-01, 4.0193e-01, 8.3799e-01, 7.3112e-01, 1.1773e-01, 8.6357e-01, 7.8174e-01, 6.3846e-01, 9.7087e-01, 8.8215e-01, 9.8100e-01, 4.0457e-02, 7.4636e-01, 6.4701e-01, 9.6748e-01, 8.5181e-01, 8.4270e-01, 2.5210e-01, 5.5618e-01, 6.1268e-01, 2.9049e-01, 5.8486e-03, 8.3614e-01, 5.2293e-01, 7.5307e-01, 3.4375e-01, 6.9141e-01, 5.1986e-01, 8.8886e-02, 4.4001e-01, 8.0642e-01, 6.9916e-01, 3.4141e-01, 4.8531e-01, 1.5386e-01, 8.8560e-01, 7.7011e-01, 3.5852e-01, 4.0197e-01, 1.6917e-01, 9.0410e-01, 5.6652e-02, 8.9739e-02, 8.3546e-01, 1.4231e-01, 7.5872e-01, 1.9298e-01, 2.2334e-01, 6.6317e-01, 6.8090e-01, 2.9787e-01, 4.9769e-01, 7.2268e-01, 2.6624e-01, 8.3895e-02, 2.1302e-03, 2.6899e-01, 3.2295e-01, 4.3568e-01, 7.4568e-01, 9.8571e-01, 2.3218e-01, 5.5723e-01, 9.0697e-01, 2.0891e-02, 6.2216e-01, 5.6822e-01, 6.7836e-01, 7.0153e-01, 7.3307e-02, 7.8713e-01, 8.6419e-01, 2.2157e-01, 3.8879e-01, 8.5876e-01, 7.0462e-01, 4.5412e-01, 4.1135e-03, 1.0077e-03, 6.9164e-02, 9.5048e-01, 7.0820e-01, 5.0619e-01, 2.0390e-02, 8.4203e-01, 1.4392e-01, 7.9174e-01, 1.6168e-01, 1.0209e-01, 9.2645e-02, 7.6759e-01, 3.5858e-01, 9.3251e-01, 5.2742e-01, 4.8935e-01, 3.6429e-01, 2.3940e-01, 3.8057e-01, 3.4109e-01, 9.2896e-02, 4.4226e-01, 6.1727e-01, 1.7108e-01, 8.4865e-01, 5.1920e-01, 7.7916e-01, 1.6543e-01, 6.6999e-01, 8.7431e-01, 4.8421e-01, 6.1869e-01, 3.1869e-01, 5.4427e-01, 2.8945e-01, 6.5180e-01, 8.8363e-01, 2.2613e-01, 3.8391e-01, 8.3005e-01, 8.0331e-01, 6.6010e-01, 8.8596e-01, 7.2263e-01, 8.4103e-01, 8.8009e-01, 2.3610e-01, 6.6927e-01, 2.5128e-01, 1.1817e-01, 3.9681e-01, 4.7718e-01, 2.5893e-01, 4.3495e-01, 1.3493e-01, 2.4773e-01, 3.3844e-01, 7.9895e-01, 9.5699e-01, 6.3362e-02, 8.1743e-01, 8.9984e-01, 9.5229e-01, 1.8843e-01, 2.7876e-01, 9.0028e-01, 2.2192e-01, 5.3296e-01, 8.4839e-01, 1.0904e-02, 8.4025e-01, 8.6112e-01, 1.1830e-01, 4.2930e-01, 4.2108e-01, 2.9025e-01, 8.6971e-01, 5.4962e-01, 7.6904e-01, 6.3845e-01, 8.0178e-01, 6.7694e-02, 6.6343e-01, 1.8530e-01, 6.4330e-01, 6.8002e-01, 8.7087e-01, 5.2740e-02, 1.4102e-01, 5.3180e-01, 6.9374e-01, 3.5666e-01, 3.5258e-01, 8.7790e-01, 7.5954e-01, 5.0547e-01, 3.5620e-01, 4.5835e-01, 3.7510e-01, 4.4056e-01, 2.3522e-01, 7.1087e-01, 6.1566e-01, 2.3742e-01, 5.5114e-01, 4.9269e-02, 4.3503e-01, 4.2648e-01, 2.0570e-01, 8.5944e-01, 6.4330e-01, 8.6874e-02, 2.8968e-01, 3.5790e-01, 7.9048e-01, 8.1321e-01, 4.9819e-01, 7.6190e-03, 9.1852e-01, 1.3581e-01, 7.5183e-01, 3.2399e-01, 1.3880e-01, 7.9173e-02, 6.9724e-01, 9.8917e-01, 8.5540e-01, 1.9553e-01, 1.5356e-01, 8.0217e-01, 7.6672e-01, 1.8106e-01, 7.8420e-01, 1.2492e-02, 8.2971e-02, 8.3922e-01, 3.8834e-01, 2.2546e-01, 3.7024e-01, 7.1171e-01, 8.0455e-02, 3.4067e-01, 7.0084e-01, 6.8490e-01, 3.6791e-01, 8.7797e-01, 7.7800e-01, 5.9188e-01, 5.8658e-01, 7.4175e-02, 9.0019e-01, 6.5421e-01, 3.3252e-01, 2.2889e-01, 9.7904e-01, 3.3549e-01, 6.9161e-01, 9.4515e-01, 1.7380e-01, 6.1230e-01, 4.3354e-01, 5.2601e-01, 8.4111e-01, 3.8420e-02, 8.1740e-01, 1.6980e-01, 9.1878e-01, 2.1792e-01, 5.7883e-01, 6.4201e-01, 8.2646e-01, 7.1636e-01, 4.8284e-01, 2.6438e-01, 2.7945e-01, 5.9324e-01, 3.7198e-01, 5.5136e-01, 7.4510e-01, 5.8621e-01, 4.6951e-01, 7.7834e-02, 5.6186e-01, 3.6304e-01, 9.2944e-01, 1.4286e-01, 2.4521e-02, 9.9506e-01, 9.5994e-01, 1.3745e-01, 2.5560e-01, 5.9027e-01, 7.3438e-01, 8.7141e-03, 8.6143e-01, 8.5607e-01, 8.7939e-01, 3.8756e-02, 6.6746e-01, 1.2815e-01, 5.1976e-01, 8.9897e-01, 9.5882e-02, 6.2630e-01, 6.9545e-01, 8.4795e-01, 9.7535e-01, 4.2693e-01, 7.6053e-01, 9.1041e-01, 6.0815e-01, 7.3042e-01, 8.5945e-01, 4.9286e-01, 7.5139e-01, 2.1239e-01, 7.7489e-01, 4.9297e-01, 5.0023e-01, 8.8323e-01, 6.4429e-01, 7.9237e-01, 2.4938e-01, 4.6155e-01, 8.8885e-01, 2.1184e-01]) ``` ## Forward process step by step ``` diffusion_steps_step_by_step = [diffusion_initial_x.detach().numpy()] for i in range(0, diffusion_params.steps): logger.info(f"step {i}") i_state = ( diffusion_process._forward_process_by_step( torch.from_numpy(diffusion_steps_step_by_step[-1]), step=i ) .detach() .numpy() ) logger.info(f"i_state {i_state[:2]}") diffusion_steps_step_by_step.append(i_state) ``` > [!NOTE] > > **Output (61 lines)** > > ``` > ... (80 earlier lines) > 2025-04-18 23:16:25.281 | INFO  | __main__::4 - step 40 > 2025-04-18 23:16:25.282 | INFO  | __main__::8 - i_state [ 0.8094039 -0.33473575] > 2025-04-18 23:16:25.282 | INFO  | __main__::4 - step 41 > 2025-04-18 23:16:25.283 | INFO  | __main__::8 - i_state [ 0.83325726 -0.35788843] > ... (66 lines omitted) ... > 2025-04-18 23:16:25.319 | INFO  | __main__::8 - i_state [ 0.7483727 -0.08260181] > 2025-04-18 23:16:25.320 | INFO  | __main__::4 - step 73 > 2025-04-18 23:16:25.320 | INFO  | __main__::8 - i_state [ 0.7065493 -0.07097664] > 2025-04-18 23:16:25.321 | INFO  | __main__::4 - step 74 > 2025-04-18 23:16:25.322 | INFO  | __main__::8 - i_state [ 0.6612688 -0.08965354] > 2025-04-18 23:16:25.329 | INFO  | __main__::4 - step 75 > 2025-04-18 23:16:25.363 | INFO  | __main__::8 - i_state [ 0.6666412 -0.08845518] > 2025-04-18 23:16:25.364 | INFO  | __main__::4 - step 76 > 2025-04-18 23:16:25.366 | INFO  | __main__::8 - i_state [ 0.63734996 -0.16654542] > 2025-04-18 23:16:25.368 | INFO  | __main__::4 - step 77 > 2025-04-18 23:16:25.374 | INFO  | __main__::8 - i_state [ 0.6595737 -0.17816634] > 2025-04-18 23:16:25.375 | INFO  | __main__::4 - step 78 > 2025-04-18 23:16:25.377 | INFO  | __main__::8 - i_state [ 0.59145856 -0.26650017] > 2025-04-18 23:16:25.377 | INFO  | __main__::4 - step 79 > 2025-04-18 23:16:25.378 | INFO  | __main__::8 - i_state [ 0.61713743 -0.2778223 ] > 2025-04-18 23:16:25.379 | INFO  | __main__::4 - step 80 > 2025-04-18 23:16:25.380 | INFO  | __main__::8 - i_state [ 0.6666499 -0.31620997] > 2025-04-18 23:16:25.380 | INFO  | __main__::4 - step 81 > 2025-04-18 23:16:25.381 | INFO  | __main__::8 - i_state [ 0.78685683 -0.28278515] > 2025-04-18 23:16:25.381 | INFO  | __main__::4 - step 82 > 2025-04-18 23:16:25.382 | INFO  | __main__::8 - i_state [ 0.75152725 -0.19486004] > 2025-04-18 23:16:25.382 | INFO  | __main__::4 - step 83 > 2025-04-18 23:16:25.383 | INFO  | __main__::8 - i_state [ 0.74986356 -0.14494139] > 2025-04-18 23:16:25.384 | INFO  | __main__::4 - step 84 > 2025-04-18 23:16:25.384 | INFO  | __main__::8 - i_state [ 0.78781325 -0.1104292 ] > 2025-04-18 23:16:25.385 | INFO  | __main__::4 - step 85 > 2025-04-18 23:16:25.385 | INFO  | __main__::8 - i_state [ 0.80012774 -0.03022134] > 2025-04-18 23:16:25.386 | INFO  | __main__::4 - step 86 > 2025-04-18 23:16:25.386 | INFO  | __main__::8 - i_state [ 0.88045436 -0.06423807] > 2025-04-18 23:16:25.387 | INFO  | __main__::4 - step 87 > 2025-04-18 23:16:25.387 | INFO  | __main__::8 - i_state [0.8984322 0.01694922] > 2025-04-18 23:16:25.388 | INFO  | __main__::4 - step 88 > 2025-04-18 23:16:25.388 | INFO  | __main__::8 - i_state [ 0.9198323 -0.09139688] > 2025-04-18 23:16:25.389 | INFO  | __main__::4 - step 89 > 2025-04-18 23:16:25.390 | INFO  | __main__::8 - i_state [ 0.98721087 -0.06547409] > 2025-04-18 23:16:25.390 | INFO  | __main__::4 - step 90 > 2025-04-18 23:16:25.391 | INFO  | __main__::8 - i_state [ 1.0306114 -0.0627986] > 2025-04-18 23:16:25.391 | INFO  | __main__::4 - step 91 > 2025-04-18 23:16:25.392 | INFO  | __main__::8 - i_state [ 0.9438532 -0.01546319] > 2025-04-18 23:16:25.392 | INFO  | __main__::4 - step 92 > 2025-04-18 23:16:25.393 | INFO  | __main__::8 - i_state [ 0.9463828 -0.04726296] > 2025-04-18 23:16:25.393 | INFO  | __main__::4 - step 93 > 2025-04-18 23:16:25.394 | INFO  | __main__::8 - i_state [ 0.99907434 -0.04744781] > 2025-04-18 23:16:25.395 | INFO  | __main__::4 - step 94 > 2025-04-18 23:16:25.396 | INFO  | __main__::8 - i_state [ 0.9595288 -0.04881873] > 2025-04-18 23:16:25.396 | INFO  | __main__::4 - step 95 > 2025-04-18 23:16:25.397 | INFO  | __main__::8 - i_state [ 0.98240954 -0.09129829] > 2025-04-18 23:16:25.397 | INFO  | __main__::4 - step 96 > 2025-04-18 23:16:25.398 | INFO  | __main__::8 - i_state [ 1.0371981 -0.13770024] > 2025-04-18 23:16:25.398 | INFO  | __main__::4 - step 97 > 2025-04-18 23:16:25.399 | INFO  | __main__::8 - i_state [ 1.0262175 -0.1635927] > 2025-04-18 23:16:25.399 | INFO  | __main__::4 - step 98 > 2025-04-18 23:16:25.400 | INFO  | __main__::8 - i_state [ 1.0525571 -0.17633782] > 2025-04-18 23:16:25.401 | INFO  | __main__::4 - step 99 > 2025-04-18 23:16:25.401 | INFO  | __main__::8 - i_state [ 1.0235711 -0.19368996] > ``` ``` px.histogram(diffusion_initial_x) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` px.histogram(diffusion_steps_step_by_step[0]) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` px.histogram(diffusion_steps_step_by_step[-1]) ``` *Interactive Plotly figure: enable JavaScript to view it.* ## Calculate State at time t in one batch ``` diffusion_steps = diffusion_process._forward_process(diffusion_initial_x) diffusion_initial_x.shape, diffusion_steps.shape ``` ``` (torch.Size([1000]), torch.Size([1000, 100])) ``` ``` px.histogram(diffusion_steps[:, -1].detach().numpy().squeeze()) ``` *Interactive Plotly figure: enable JavaScript to view it.* ## Reverse step by step ``` diffusion_steps_reverse = [diffusion_steps_step_by_step[-1]] for i in range(diffusion_params.steps - 1, -1, -1): logger.info(f"step {i}") i_state = ( diffusion_process._inverse_process_by_step( torch.from_numpy(diffusion_steps_reverse[-1]), step=i ) .detach() .numpy() ) logger.info(f"i_state {i_state[:2]}") diffusion_steps_reverse.append(i_state) ``` > [!NOTE] > > **Output (61 lines)** > > ``` > ... (80 earlier lines) > 2025-04-18 23:16:25.681 | INFO  | __main__::4 - step 59 > 2025-04-18 23:16:25.682 | INFO  | __main__::8 - i_state [ 0.6951474 -0.38879928] > 2025-04-18 23:16:25.682 | INFO  | __main__::4 - step 58 > 2025-04-18 23:16:25.683 | INFO  | __main__::8 - i_state [ 0.73595834 -0.41042498] > ... (66 lines omitted) ... > 2025-04-18 23:16:25.724 | INFO  | __main__::8 - i_state [ 0.69292307 -0.45350495] > 2025-04-18 23:16:25.724 | INFO  | __main__::4 - step 26 > 2025-04-18 23:16:25.725 | INFO  | __main__::8 - i_state [ 0.6937502 -0.60519886] > 2025-04-18 23:16:25.725 | INFO  | __main__::4 - step 25 > 2025-04-18 23:16:25.726 | INFO  | __main__::8 - i_state [ 0.7822882 -0.8576625] > 2025-04-18 23:16:25.726 | INFO  | __main__::4 - step 24 > 2025-04-18 23:16:25.727 | INFO  | __main__::8 - i_state [ 0.88714874 -0.76542556] > 2025-04-18 23:16:25.727 | INFO  | __main__::4 - step 23 > 2025-04-18 23:16:25.728 | INFO  | __main__::8 - i_state [ 0.8904635 -0.72792196] > 2025-04-18 23:16:25.728 | INFO  | __main__::4 - step 22 > 2025-04-18 23:16:25.729 | INFO  | __main__::8 - i_state [ 0.92258674 -0.72440726] > 2025-04-18 23:16:25.729 | INFO  | __main__::4 - step 21 > 2025-04-18 23:16:25.730 | INFO  | __main__::8 - i_state [ 0.88699913 -0.84595186] > 2025-04-18 23:16:25.730 | INFO  | __main__::4 - step 20 > 2025-04-18 23:16:25.731 | INFO  | __main__::8 - i_state [ 0.7618088 -0.80919963] > 2025-04-18 23:16:25.731 | INFO  | __main__::4 - step 19 > 2025-04-18 23:16:25.732 | INFO  | __main__::8 - i_state [ 0.78601956 -0.81135654] > 2025-04-18 23:16:25.738 | INFO  | __main__::4 - step 18 > 2025-04-18 23:16:25.743 | INFO  | __main__::8 - i_state [ 0.680832 -0.5877883] > 2025-04-18 23:16:25.745 | INFO  | __main__::4 - step 17 > 2025-04-18 23:16:25.750 | INFO  | __main__::8 - i_state [ 0.6215372 -0.5862306] > 2025-04-18 23:16:25.752 | INFO  | __main__::4 - step 16 > 2025-04-18 23:16:25.757 | INFO  | __main__::8 - i_state [ 0.5862276 -0.50796723] > 2025-04-18 23:16:25.759 | INFO  | __main__::4 - step 15 > 2025-04-18 23:16:25.760 | INFO  | __main__::8 - i_state [ 0.5905369 -0.31537208] > 2025-04-18 23:16:25.760 | INFO  | __main__::4 - step 14 > 2025-04-18 23:16:25.761 | INFO  | __main__::8 - i_state [ 0.58957505 -0.2877775 ] > 2025-04-18 23:16:25.762 | INFO  | __main__::4 - step 13 > 2025-04-18 23:16:25.763 | INFO  | __main__::8 - i_state [ 0.5959704 -0.25140628] > 2025-04-18 23:16:25.764 | INFO  | __main__::4 - step 12 > 2025-04-18 23:16:25.767 | INFO  | __main__::8 - i_state [ 0.6318918 -0.2134175] > 2025-04-18 23:16:25.767 | INFO  | __main__::4 - step 11 > 2025-04-18 23:16:25.768 | INFO  | __main__::8 - i_state [ 0.6900686 -0.2123212] > 2025-04-18 23:16:25.768 | INFO  | __main__::4 - step 10 > 2025-04-18 23:16:25.769 | INFO  | __main__::8 - i_state [ 0.74115765 -0.12743005] > 2025-04-18 23:16:25.769 | INFO  | __main__::4 - step 9 > 2025-04-18 23:16:25.770 | INFO  | __main__::8 - i_state [ 0.6804571 -0.17437676] > 2025-04-18 23:16:25.771 | INFO  | __main__::4 - step 8 > 2025-04-18 23:16:25.772 | INFO  | __main__::8 - i_state [ 0.6416513 -0.07735392] > 2025-04-18 23:16:25.772 | INFO  | __main__::4 - step 7 > 2025-04-18 23:16:25.773 | INFO  | __main__::8 - i_state [ 0.6909528 -0.14884506] > 2025-04-18 23:16:25.773 | INFO  | __main__::4 - step 6 > 2025-04-18 23:16:25.774 | INFO  | __main__::8 - i_state [ 0.7000388 -0.16155608] > 2025-04-18 23:16:25.774 | INFO  | __main__::4 - step 5 > 2025-04-18 23:16:25.775 | INFO  | __main__::8 - i_state [ 0.60679346 -0.19287485] > 2025-04-18 23:16:25.776 | INFO  | __main__::4 - step 4 > 2025-04-18 23:16:25.777 | INFO  | __main__::8 - i_state [ 0.63962066 -0.17235725] > 2025-04-18 23:16:25.777 | INFO  | __main__::4 - step 3 > 2025-04-18 23:16:25.778 | INFO  | __main__::8 - i_state [ 0.6361206 -0.05406848] > 2025-04-18 23:16:25.778 | INFO  | __main__::4 - step 2 > 2025-04-18 23:16:25.779 | INFO  | __main__::8 - i_state [ 0.7482846 -0.05167478] > 2025-04-18 23:16:25.779 | INFO  | __main__::4 - step 1 > 2025-04-18 23:16:25.780 | INFO  | __main__::8 - i_state [ 0.7793836 -0.10398894] > 2025-04-18 23:16:25.780 | INFO  | __main__::4 - step 0 > 2025-04-18 23:16:25.781 | INFO  | __main__::8 - i_state [0.77775383 0.00259962] > ``` ``` px.histogram(diffusion_steps_reverse[-1]) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` px.histogram(diffusion_steps_reverse[0]) ``` *Interactive Plotly figure: enable JavaScript to view it.* ## Diffusion Distributions ``` px.line(diffusion_params.alpha_bar_by_step) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` df_diffusion_example = pd.DataFrame( np.concatenate( [ diffusion_initial_x.reshape(1, diffusion_batch_size).detach().numpy(), diffusion_steps.T.detach().numpy(), ] ), columns=[f"x_{i}" for i in range(len(diffusion_steps))], ) df_diffusion_example["step"] = df_diffusion_example.index df_diffusion_example_melted = df_diffusion_example.melt( id_vars=["step"], var_name="variable", value_name="value" ) df_diffusion_example_melted.tail() ``` | | step | variable | value | | --- | --- | --- | --- | | 100995 | 96 | x\_999 | 0.147864 | | 100996 | 97 | x\_999 | \-0.425635 | | 100997 | 98 | x\_999 | \-0.156875 | | 100998 | 99 | x\_999 | \-0.942937 | | 100999 | 100 | x\_999 | \-1.025280 | ``` px.histogram( df_diffusion_example_melted, x="value", histnorm="probability density", animation_frame="step", ) ``` ``` /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/plotly/express/_core.py:1985: FutureWarning: When grouping with a length-1 list-like, you will need to pass a length-1 tuple to get_group in a future version of pandas. Pass `(name,)` instead of `name` to silence this warning. ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` px.violin( df_diffusion_example_melted.loc[ df_diffusion_example_melted["step"].isin( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] ) ], x="step", y="value", ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` px.line( df_diffusion_example_melted, x="step", y="value", color="variable", ) ``` ``` /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/plotly/express/_core.py:1985: FutureWarning: When grouping with a length-1 list-like, you will need to pass a length-1 tuple to get_group in a future version of pandas. Pass `(name,)` instead of `name` to silence this warning. ``` *Interactive Plotly figure: enable JavaScript to view it.* ## Create Visuals ``` import matplotlib.pyplot as plt import seaborn as sns ``` ``` _, ax = plt.subplots(figsize=(10, 6)) sns.histplot( df_diffusion_example_melted.loc[df_diffusion_example_melted["step"] == 0], x="value", stat="probability", color="k", label="Initial Distribution", ax=ax, ) ax.set_title("Initial Distribution") ax.set_xlabel("Position") ``` ``` Text(0.5, 0, 'Position') ``` ![output]() ``` _, ax = plt.subplots(figsize=(10, 6)) sns.histplot( df_diffusion_example_melted.loc[ df_diffusion_example_melted["step"] == max(df_diffusion_example_melted["step"]) ], x="value", stat="probability", color="k", ax=ax, ) ax.set_title("Final Distribution") ax.set_xlabel("Position") ``` ``` Text(0.5, 0, 'Position') ``` ![output]() # Model ``` from lightning import LightningModule ``` ``` @dataclasses.dataclass class DiffusionEncoderParams: """Parameters for VAEEncoder and VAEDecoder :param latent_size: latent space dimension :param history_length: input sequence length :param n_features: number of features """ latent_size: int = 40 num_layers: int = 2 history_length: int n_features: int = 1 initial_state: torch.Tensor = None @cached_property def data_size(self) -> int: """The dimension of the input data when flattened. """ return self.sequence_length * self.n_features def asdict(self) -> dict: return dataclasses.asdict(self) class Encoder(nn.Module): """ """ def __init__(self, params: DiffusionEncoderParams): super().__init__() self.params = params self.hparams = params.asdict() self.rnn = nn.GRU( input_size=self.params.history_length, hidden_size=self.params.latent_size, num_layers=self.params.num_layers, ) def forward( self, x: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ :param x: input data, shape (batch_size, history_length, n_features) """ batch_size, _, _ = x.size() x = x.transpose(1, 2) outputs, state = self.rnn(x, self.params.initial_state) return outputs, state class Distribution(nn.Module): """ """ def __init__(self, params: DiffusionEncoderParams, samples: int = 100): super().__init__() self.params = params self.hparams = params.asdict() self.samples = samples self.linear = nn.Linear(self.params.latent_size, samples) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.linear(x) class DiffusionModel(nn.Module): """ """ def __init__( self, encoder_params: DiffusionEncoderParams, diffusion_params: DiffusionParams, batch_size: int, ): super().__init__() def forward(self, x: torch.Tensor) -> torch.Tensor: outputs, state = self.encoder(x) distribution = self.distribution(outputs) return distribution class Model(LightningModule): def __init__( self, encoder_params: DiffusionEncoderParams, diffusion_params: DiffusionParams, batch_size: int, ): self.encoder = Encoder(encoder_params) self.diffusion = Diffusion(batch_size, diffusion_params) self.distribution = Distribution(encoder_params, samples=100) def forward(self, x: torch.Tensor) -> torch.Tensor: outputs, state = self.encoder(x) distribution = self.distribution(outputs) return distribution def training_step(self, batch: torch.Tensor, batch_idx: int) -> torch.Tensor: x = batch["x"] y = batch["y"] distribution = self(x) loss = self.loss(distribution, y) return loss def loss(self, y: torch.Tensor, y_hat: torch.Tensor) -> torch.Tensor: return ``` ``` diffusion_params.steps ``` ``` 100 ``` ``` enc_params = DiffusionEncoderParams( latent_size=10, num_layers=1, history_length=5, n_features=1, initial_state=None, ) encoder = Encoder( params=enc_params, ) encoder( x=torch.rand(8, 5, 1), )[0].shape, encoder( x=torch.rand(8, 5, 1), )[-1].shape ``` ``` (torch.Size([8, 1, 10]), torch.Size([1, 1, 10])) ``` ``` class DiffusionEmbedding(nn.Module): def __init__(self, dim, proj_dim, max_steps=500): super().__init__() self.register_buffer( "embedding", self._build_embedding(dim, max_steps), persistent=False ) self.projection1 = nn.Linear(dim * 2, proj_dim) self.projection2 = nn.Linear(proj_dim, proj_dim) def forward(self, diffusion_step): x = self.embedding[diffusion_step] x = self.projection1(x) x = F.silu(x) x = self.projection2(x) x = F.silu(x) return x def _build_embedding(self, dim, max_steps): steps = torch.arange(max_steps).unsqueeze(1) # [T,1] dims = torch.arange(dim).unsqueeze(0) # [1,dim] table = steps * 10.0 ** (dims * 4.0 / dim) # [T,dim] table = torch.cat([torch.sin(table), torch.cos(table)], dim=1) return table class EpsilonTheta(nn.Module): def __init__( self, target_dim, cond_length, time_emb_dim=16, residual_layers=8, residual_channels=8, dilation_cycle_length=2, residual_hidden=64, ): super().__init__() self.input_projection = nn.Conv1d( 1, residual_channels, 1, padding=2, padding_mode="circular" ) self.diffusion_embedding = DiffusionEmbedding( time_emb_dim, proj_dim=residual_hidden ) self.cond_upsampler = CondUpsampler( target_dim=target_dim, cond_length=cond_length ) self.residual_layers = nn.ModuleList( [ ResidualBlock( residual_channels=residual_channels, dilation=2 ** (i % dilation_cycle_length), hidden_size=residual_hidden, ) for i in range(residual_layers) ] ) self.skip_projection = nn.Conv1d(residual_channels, residual_channels, 3) self.output_projection = nn.Conv1d(residual_channels, 1, 3) nn.init.kaiming_normal_(self.input_projection.weight) nn.init.kaiming_normal_(self.skip_projection.weight) nn.init.zeros_(self.output_projection.weight) def forward(self, inputs, time, cond): x = self.input_projection(inputs) x = F.leaky_relu(x, 0.4) diffusion_step = self.diffusion_embedding(time) cond_up = self.cond_upsampler(cond) skip = [] for layer in self.residual_layers: x, skip_connection = layer(x, cond_up, diffusion_step) skip.append(skip_connection) x = torch.sum(torch.stack(skip), dim=0) / math.sqrt(len(self.residual_layers)) x = self.skip_projection(x) x = F.leaky_relu(x, 0.4) x = self.output_projection(x) return x ``` ``` def extract(a, t, x_shape): b, *_ = t.shape out = a.gather(-1, t) mm = len(x_shape) - 1 return out.reshape(b, *((1,) * mm)) def q_sample(x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return ( extract(sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract(sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise ) def p_losses(x_start, cond, t, noise=None): loss_type = "l2" noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = q_sample(x_start=x_start, t=t, noise=noise) x_recon = denoise_fn(x_noisy, t, cond=cond) if loss_type == "l1": loss = torch.nn.functional.l1_loss(x_recon, noise) elif loss_type == "l2": loss = torch.nn.functional.mse_loss(x_recon, noise) elif loss_type == "huber": loss = torch.nn.functional.smooth_l1_loss(x_recon, noise) else: raise NotImplementedError() return loss def log_prob(self, x, cond, *args, **kwargs): if self.scale is not None: x /= self.scale B, T, _ = x.shape time = torch.randint(0, self.num_timesteps, (B * T,), device=x.device).long() loss = p_losses( x.reshape(B * T, 1, -1), cond.reshape(B * T, 1, -1), time, *args, **kwargs ) return loss ``` ``` tmp_x_start = torch.ones((2, 3)) tmp_x_start ``` ``` tensor([[1., 1., 1.], [1., 1., 1.]]) ``` ``` tmp_a = torch.Tensor([1, 2, 3, 4, 5]) tmp_a ``` ``` tensor([1., 2., 3., 4., 5.]) ``` ``` extract(tmp_a, tmp_a, x_shape=tmp_x_start.shape) ``` # Diffusion Process # LSTM In this notebook, we demonstrate a few special properties of LSTM. ``` import matplotlib.pyplot as plt ``` ``` import numpy as np import seaborn as sns sns.set_theme() import pandas as pd ``` ## Cell State Phase Space ``` def cell_state(f, m, c_prev: int = 1): return np.tanh(c_prev * f + m) ``` ``` f = np.linspace(-1, 1, 101) m = np.linspace(-1, 1, 101) ``` ``` c = [] for f_i in f: c_m = [] for m_i in m: c_m.append(cell_state(f_i, m_i)) c.append(c_m) ``` ``` df = pd.DataFrame(c, columns=[f"{i:.2f}" for i in m], index=[f"{i:.2f}" for i in f]) ``` ``` _, ax = plt.subplots(figsize=(8.5, 8)) ax = sns.heatmap(df, ax=ax) ax.set_title("LSTM Cell States") ax.set_xlabel(r"i * h") ``` ``` df = pd.DataFrame() c_init = 5 for f in [0.1, 0.9]: for i_g in [-0.5, 0.5, 0.9]: cell_states = [ { "iter": 0, "c": c_init, "f": f, "i*g": i_g, "c_prev": np.nan, "tanh_c": np.tanh(c_init), } ] for _ in range(10): f_ = cell_states[-1]["f"] c_ = cell_states[-1]["c"] i_g_ = cell_states[-1]["i*g"] c_new = cell_state(f=f_, m=i_g_, c_prev=c_) cell_states.append( { "iter": cell_states[-1]["iter"] + 1, "c": c_new, "f": f_, "i*g": i_g_, "c_prev": c_, "tanh_c": np.tanh(c_new), } ) df = pd.concat([df, pd.DataFrame(cell_states)]) ``` ``` df.head() ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.lineplot( df, x="iter", y="c", hue="f", style="i*g", size="f", palette=sns.palettes.color_palette("colorblind")[:2], markers=True, ax=ax, ) ax.set_xlabel("Iteration") ax.set_ylabel("c") ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.lineplot( df, x="iter", y="tanh_c", hue="f", style="i*g", size="f", palette=sns.palettes.color_palette("colorblind")[:2], markers=True, ax=ax, ) ax.set_xlabel("Iteration") ax.set_ylabel("tanh(c)") ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) sns.scatterplot( df, x="c_prev", y="c", hue="f", style="i*g", size="f", palette=sns.palettes.color_palette("colorblind")[:2], markers=True, ax=ax, ) ax.set_xlabel("c_prev") ax.set_ylabel("c") ``` # CPC for Time Series Data References: - [mqwfrog/ULTS/tree/main/models/CPC]() - [ECG200]() - R. T. Olszewski, “Generalized feature extraction for structural pattern recognition in time-series data,” Carnegie Mellon University, Pittsburgh, PA, 2001. Available: [https://www.cs.cmu.edu/\~bobski/pubs/tr01108-twosided.pdf]() configs ``` from pathlib import Path from typing import Literal ``` ``` import yaml from pydantic import BaseModel, Field ``` ``` class DataConfig(BaseModel): """Dataset location and dataset identity settings.""" dataset_name: str = "ECG200" data_dir: str = "data" class DataloaderConfig(BaseModel): """PyTorch DataLoader settings for train and validation loaders.""" batch_size: int = 64 drop_last: bool = False num_workers: int = 0 val_split: float = 0.1 class DataModuleConfig(BaseModel): """Top-level configuration object for CPC training.""" data: DataConfig = Field(default_factory=DataConfig) dataloader: DataloaderConfig = Field(default_factory=DataloaderConfig) ``` Data ``` import os import lightning as L import numpy as np import torch from torch.utils.data import DataLoader, Dataset, Subset class CPCDataset(Dataset): """Simple dataset wrapper for CPC tensors. Expected input object format: - ``samples``: array/tensor with shape ``[N, T]`` or ``[N, C, T]`` or ``[N, T, C]``. - ``labels``: array/tensor with shape ``[N]``. """ def __init__(self, dataset_obj): """Initialize dataset tensors. :param dataset_obj: Dictionary containing ``samples`` and ``labels`` arrays/tensors. Samples are converted to ``float32`` and labels to ``int64``. """ super().__init__() samples = dataset_obj["samples"] labels = dataset_obj["labels"] if isinstance(samples, np.ndarray): samples = torch.from_numpy(samples) if isinstance(labels, np.ndarray): labels = torch.from_numpy(labels) if samples.ndim == 2: samples = samples.unsqueeze(1) elif samples.ndim == 3: # Keep channels in dim=1. if list(samples.shape).index(min(samples.shape)) != 1: samples = samples.permute(0, 2, 1) self.samples = samples.float() self.labels = labels.long() def __len__(self): """Return number of samples ``N``.""" return self.samples.shape[0] def __getitem__(self, index): """Return one sample-label pair. :param index: Sample index. :returns: Tuple ``(x, y)`` where ``x`` has shape ``[C, T]`` and ``y`` is a scalar class label tensor. """ return self.samples[index], self.labels[index] def _stratified_split( labels: np.ndarray, val_fraction: float, random_state: int = 42 ) -> tuple[np.ndarray, np.ndarray]: """Stratified train/val index split without sklearn.""" rng = np.random.default_rng(random_state) train_idx, val_idx = [], [] for cls in np.unique(labels): cls_indices = np.where(labels == cls)[0] rng.shuffle(cls_indices) n_val = max(1, round(len(cls_indices) * val_fraction)) val_idx.extend(cls_indices[:n_val].tolist()) train_idx.extend(cls_indices[n_val:].tolist()) return np.array(train_idx), np.array(val_idx) class CPCDataModule(L.LightningDataModule): def __init__(self, config: DataModuleConfig): super().__init__() self.config = config self.train_loader = None self.val_loader = None self.test_loader = None self.input_channels = None def setup(self, stage=None): if self.train_loader is not None: return dataset_path = os.path.join( self.config.data.data_dir, self.config.data.dataset_name ) train_obj = torch.load(os.path.join(dataset_path, "train.pt")) test_obj = torch.load(os.path.join(dataset_path, "test.pt")) full_train_ds = CPCDataset(train_obj) test_ds = CPCDataset(test_obj) self.input_channels = int(full_train_ds.samples.shape[1]) labels = full_train_ds.labels.numpy() train_idx, val_idx = _stratified_split( labels, val_fraction=self.config.dataloader.val_split, random_state=42, ) train_ds = Subset(full_train_ds, train_idx) val_ds = Subset(full_train_ds, val_idx) dl_kwargs = dict( batch_size=self.config.dataloader.batch_size, num_workers=self.config.dataloader.num_workers, ) self.train_loader = DataLoader( train_ds, shuffle=True, drop_last=self.config.dataloader.drop_last, **dl_kwargs, ) self.val_loader = DataLoader( val_ds, shuffle=False, drop_last=False, **dl_kwargs ) self.test_loader = DataLoader( test_ds, shuffle=False, drop_last=False, **dl_kwargs ) def train_dataloader(self): return self.train_loader def val_dataloader(self): return self.val_loader def test_dataloader(self): return self.test_loader ``` Modules ``` class ConvLayerConfig(BaseModel): """Single 1D convolution specification. Parameters define one convolution block as ``Conv1d(in_channels, out_channels, kernel_size, stride, padding)``. """ kernel_size: int stride: int padding: int class EncoderConfig(BaseModel): """Encoder architecture and normalization settings.""" hidden_size: int = 256 norm_mode: Literal["batchNorm", "instanceNorm", "ID", "layerNorm"] = "layerNorm" conv_layers: list[ConvLayerConfig] = Field( default_factory=lambda: [ ConvLayerConfig(kernel_size=10, stride=5, padding=3), ConvLayerConfig(kernel_size=8, stride=4, padding=2), ConvLayerConfig(kernel_size=4, stride=2, padding=1), ConvLayerConfig(kernel_size=4, stride=2, padding=1), ConvLayerConfig(kernel_size=4, stride=2, padding=1), ] ) class ARConfig(BaseModel): """Autoregressive model selection and parameters. Supports recurrent modes (GRU/LSTM/RNN), Transformer mode, and identity mode (``no_ar``). """ mode: Literal["GRU", "LSTM", "RNN", "transformer", "no_ar"] = "LSTM" hidden_size: int = 256 n_levels: int = 1 reverse: bool = False class LossConfig(BaseModel): """CPC/InfoNCE objective configuration.""" n_predictions: int = 12 negative_sampling_ext: int = 128 temperature: float = 0.07 import math ``` ``` from functools import cached_property from typing import Callable, Literal import torch import torch.nn as nn import torch.nn.functional as F class CPCEncoder(nn.Module): """Convolutional encoder for time-series CPC. Input is expected as ``[B, C_in, T]`` and output as ``[B, H, T_enc]``, where ``H`` is ``size_hidden`` and ``T_enc`` depends on convolution specs. """ def __init__( self, input_channels: int = 1, size_hidden: int = 256, conv_specs: list[tuple[int, int, int]] | None = None, ): """Build the encoder stack. :param input_channels: Number of input channels ``C_in``. :param size_hidden: Number of output channels for each convolution block. :param conv_specs: List of convolution settings as ``(kernel_size, stride, padding)``. If ``None``, a default 5-layer downsampling stack is used. """ super().__init__() norm_factory: Callable[[int], nn.Module] norm_factory = nn.BatchNorm1d # norm_factory = nn.Identity if conv_specs is None: conv_specs = [ (10, 5, 3), (8, 4, 2), (4, 2, 1), (4, 2, 1), (4, 2, 1), ] blocks: list[nn.Module] = [] in_channels = input_channels for kernel_size, stride, padding in conv_specs: blocks.extend( [ nn.Conv1d( in_channels, size_hidden, kernel_size, stride=stride, padding=padding, ), norm_factory(size_hidden), nn.ReLU(), ] ) in_channels = size_hidden self.network = nn.Sequential(*blocks) self.output_dim = size_hidden @cached_property def output_dimension(self) -> int: """Return the encoder feature dimension ``H``.""" return self.output_dim def forward(self, x: torch.Tensor) -> torch.Tensor: """Encode raw sequence features. :param x: Input tensor with shape ``[B, C_in, T]``. :returns: Encoded tensor with shape ``[B, H, T_enc]``. """ return self.network(x) class CPCAR(nn.Module): """Recurrent autoregressive context model for CPC. Operates on encoded sequences in ``[B, T, C]`` format and returns contextualized representations in ``[B, T, C_ctx]``. """ def __init__( self, dim_encoded: int, dim_output: int, n_levels_gru: int = 1, rnn_type: Literal["GRU", "LSTM", "RNN"] = "LSTM", reverse: bool = False, ): """Initialize recurrent AR module. :param dim_encoded: Input feature size ``C`` from the encoder. :param dim_output: Hidden/context size ``C_ctx`` of the recurrent module. :param n_levels_gru: Number of recurrent layers. :param rnn_type: Recurrent cell type. :param reverse: If ``True``, run AR in reverse time and flip output back. """ super().__init__() self.reverse = reverse rnn_cls = {"LSTM": nn.LSTM, "RNN": nn.RNN, "GRU": nn.GRU}[rnn_type] self.rnn = rnn_cls( dim_encoded, dim_output, num_layers=n_levels_gru, batch_first=True ) @cached_property def output_dimension(self) -> int: """Return context feature dimension ``C_ctx``.""" return self.rnn.hidden_size def forward(self, x: torch.Tensor) -> torch.Tensor: """Run recurrent AR on encoded sequence. :param x: Encoded tensor with shape ``[B, T, C]``. :returns: Context tensor with shape ``[B, T, C_ctx]``. """ if self.reverse: x = torch.flip(x, [1]) try: self.rnn.flatten_parameters() except RuntimeError: pass x, _ = self.rnn(x) if self.reverse: x = torch.flip(x, [1]) return x class CPCModel(nn.Module): """Compose encoder and autoregressive context model.""" def __init__(self, encoder: nn.Module, ar: nn.Module): """Initialize CPC model. :param encoder: Module mapping ``[B, C_in, T]`` to ``[B, C_enc, T_enc]``. :param ar: Module mapping ``[B, T_enc, C_enc]`` to context features ``[B, T_enc, C_ctx]``. """ super().__init__() self.encoder = encoder self.ar = ar def forward(self, batch_data: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: """Run encoder then AR network. :param batch_data: Input batch with shape ``[B, C_in, T]``. :returns: Tuple ``(context, encoded)`` where ``context`` has shape ``[B, T_enc, C_ctx]`` and ``encoded`` has shape ``[B, T_enc, C_enc]``. """ encoded = self.encoder(batch_data).permute(0, 2, 1) context = self.ar(encoded) return context, encoded class CPCCriterion(nn.Module): """InfoNCE loss used by Contrastive Predictive Coding. For each prediction horizon ``k``, the criterion predicts future encoded vectors from context, then contrasts one positive against sampled negatives. """ def __init__( self, dim_context: int, dim_encoded: int, n_predictions: int = 12, n_negatives: int = 128, temperature: float = 0.07, ): """Initialize CPC criterion. :param dim_context: Context feature dimension ``C_ctx``. :param dim_encoded: Encoded target feature dimension ``C_enc``. :param n_predictions: Number of future steps to predict. :param n_negatives: Number of negative samples per query. :param temperature: Logit temperature scaling factor. """ super().__init__() self.n_predictions = n_predictions self.n_negatives = n_negatives self.temperature = temperature self.predictors = nn.ModuleList( [ nn.Linear(dim_context, dim_encoded, bias=False) for _ in range(n_predictions) ] ) def _sample_negatives( self, encoded_pool: torch.Tensor, n_queries: int ) -> torch.Tensor: """Sample negative encoded vectors. :param encoded_pool: Flattened encoded with shape ``[B*T, C_enc]``. :param n_queries: Number of query vectors to match. :returns: Negative samples with shape ``[n_queries, n_negatives, C_enc]``. """ idx = torch.randint( low=0, high=encoded_pool.size(0), size=(n_queries, self.n_negatives), device=encoded_pool.device, ) return encoded_pool[idx] def forward(self, context: torch.Tensor, encoded: torch.Tensor) -> torch.Tensor: """Compute averaged InfoNCE loss across valid prediction horizons. :param context: Context tensor with shape ``[B, T, C_ctx]``. :param encoded: Encoded tensor with shape ``[B, T, C_enc]``. :returns: Scalar loss tensor. :raises RuntimeError: If no prediction horizon is valid, usually because ``T`` is too short relative to ``n_predictions``. """ _, seq_len, _ = encoded.shape encoded_pool = F.normalize(encoded.flatten(0, 1), dim=-1) total_loss: torch.Tensor | None = None used_steps = 0 for k in range(1, self.n_predictions + 1): if seq_len - k <= 0: break c_t = context[:, : seq_len - k, :] z_pos = encoded[:, k:, :] z_hat = self.predictors[k - 1](c_t) z_hat = F.normalize(z_hat.flatten(0, 1), dim=-1) z_pos = F.normalize(z_pos.flatten(0, 1), dim=-1) n_queries = z_hat.size(0) pos_logits = torch.sum(z_hat * z_pos, dim=-1, keepdim=True) z_neg = self._sample_negatives(encoded_pool, n_queries) neg_logits = torch.einsum("nc,nkc->nk", z_hat, z_neg) logits = torch.cat([pos_logits, neg_logits], dim=1) / self.temperature targets = torch.zeros(n_queries, dtype=torch.long, device=logits.device) step_loss = F.cross_entropy(logits, targets) total_loss = step_loss if total_loss is None else total_loss + step_loss used_steps += 1 if used_steps == 0: raise RuntimeError( "CPCCriterion has no valid prediction steps: encoded sequence length is too short " f"(seq_len={seq_len}) for n_predictions={self.n_predictions}. " "Use fewer downsampling conv layers, smaller strides, or lower n_predictions." ) if total_loss is None: raise RuntimeError( "CPCCriterion failed to compute loss: total_loss is None after processing all prediction steps. " ) return total_loss / used_steps ``` Model ``` class OptimizerConfig(BaseModel): """Optimizer hyperparameters.""" learning_rate: float = 2e-4 weight_decay: float = 1e-6 class TrainerConfig(BaseModel): """Trainer runtime options, including epoch count and output path.""" epochs: int = 100 output_dir: str = "lightning_logs/ts_cpc" class RuntimeConfig(BaseModel): """Execution environment settings such as seed and device.""" seed: int = 0 accelerator: Literal["auto", "cpu", "gpu", "mps"] = "auto" devices: int = 1 class TrainConfig(BaseModel): """Top-level configuration object for CPC training.""" data: DataConfig = Field(default_factory=DataConfig) dataloader: DataloaderConfig = Field(default_factory=DataloaderConfig) encoder: EncoderConfig = Field(default_factory=EncoderConfig) ar: ARConfig = Field(default_factory=ARConfig) loss: LossConfig = Field(default_factory=LossConfig) optimizer: OptimizerConfig = Field(default_factory=OptimizerConfig) trainer: TrainerConfig = Field(default_factory=TrainerConfig) runtime: RuntimeConfig = Field(default_factory=RuntimeConfig) @classmethod def from_yaml(cls, path: Path) -> "TrainConfig": """Load a training configuration from YAML. :param path: Path to a YAML file containing any subset of ``TrainConfig`` fields. :returns: Parsed configuration with defaults applied to omitted fields. """ with open(path) as f: data = yaml.safe_load(f) return cls(**(data or {})) ``` ``` import os import lightning as L import torch from lightning.pytorch.callbacks import ModelCheckpoint class CPCLightningModule(L.LightningModule): """Lightning wrapper around CPC model and criterion. This module handles model construction, train/validation steps, and optimizer configuration. """ def __init__(self, config: TrainConfig, input_channels: int): """Initialize the Lightning module. :param config: Hierarchical training configuration. :param input_channels: Number of input channels in each sample ``x`` where ``x`` has shape ``[B, C_in, T]``. """ super().__init__() self.config = config self.save_hyperparameters(config.model_dump()) encoder = CPCEncoder( input_channels=input_channels, size_hidden=config.encoder.hidden_size, # norm_mode=config.encoder.norm_mode, conv_specs=[ (l.kernel_size, l.stride, l.padding) for l in config.encoder.conv_layers ], ) ar = CPCAR( dim_encoded=config.encoder.hidden_size, dim_output=config.ar.hidden_size, n_levels_gru=config.ar.n_levels, rnn_type=config.ar.mode, reverse=config.ar.reverse, ) self.model = CPCModel(encoder, ar) self.criterion = CPCCriterion( dim_context=ar.output_dimension, dim_encoded=encoder.output_dimension, n_predictions=config.loss.n_predictions, n_negatives=config.loss.negative_sampling_ext, temperature=config.loss.temperature, ) def _shared_step(self, batch, split: str): """Run one shared forward/loss step for train or validation. :param batch: Tuple ``(x, y)`` where ``x`` has shape ``[B, C_in, T]`` and ``y`` is the label tensor. :param split: Metric prefix, typically ``"train"`` or ``"val"``. :returns: Scalar CPC loss. """ batch_x, _ = batch batch_x = batch_x.float() context, encoded = self.model(batch_x) loss = self.criterion(context, encoded) self.log( f"{split}_loss", loss, on_step=False, on_epoch=True, prog_bar=True, batch_size=batch_x.size(0), ) return loss def training_step(self, batch, batch_idx): """Run one training step. :param batch: Mini-batch tuple ``(x, y)``. :param batch_idx: Batch index within the epoch. :returns: Scalar training loss. """ return self._shared_step(batch, "train") def validation_step(self, batch, batch_idx): """Run one validation step. :param batch: Mini-batch tuple ``(x, y)``. :param batch_idx: Batch index within the validation epoch. """ self._shared_step(batch, "val") def predict_step( self, data, batch_idx: int = 0 ) -> tuple[torch.Tensor, torch.Tensor]: """Run one prediction step. :param data: Mini-batch tuple ``(x, y)``. :param batch_idx: Batch index within the prediction epoch. :returns: Tuple of context and encoded tensors. """ x = data.float() context, encoded = self.model(x) return context, encoded def configure_optimizers(self): """Create optimizer for model and criterion parameters. :returns: Adam optimizer configured from ``config.optimizer``. """ return torch.optim.Adam( list(self.model.parameters()) + list(self.criterion.parameters()), lr=self.config.optimizer.learning_rate, weight_decay=self.config.optimizer.weight_decay, ) ``` ``` # config = TrainConfig.from_yaml( # Path("configs/predictive_coding/config.ecg200.yaml") # ) # config = TrainConfig.from_yaml( # Path("configs/predictive_coding/config.ecg5000.yaml") # ) # config = TrainConfig.from_yaml( # Path("configs/predictive_coding/config.forda.yaml") # ) # config = TrainConfig.from_yaml(Path("configs/predictive_coding/config.sleep.yaml")) config = TrainConfig.from_yaml( Path("configs/predictive_coding/config.binaryheartbeat.yaml") ) ``` ``` config.model_dump() ``` ``` {'data': {'dataset_name': 'ECG200', 'data_dir': 'data/predictive_coding'}, 'dataloader': {'batch_size': 32, 'drop_last': False, 'num_workers': 0, 'val_split': 0.1}, 'encoder': {'hidden_size': 50, 'norm_mode': 'layerNorm', 'conv_layers': [{'kernel_size': 10, 'stride': 5, 'padding': 3}, {'kernel_size': 8, 'stride': 4, 'padding': 2}, {'kernel_size': 3, 'stride': 1, 'padding': 1}]}, 'ar': {'mode': 'GRU', 'hidden_size': 150, 'n_levels': 1, 'reverse': True}, 'loss': {'n_predictions': 2, 'negative_sampling_ext': 64, 'temperature': 0.07}, 'optimizer': {'learning_rate': 0.0002, 'weight_decay': 1e-06}, 'trainer': {'epochs': 400, 'output_dir': 'lightning_logs/ecg200_cpc'}, 'runtime': {'seed': 137, 'accelerator': 'auto', 'devices': 1}} ``` ``` L.seed_everything(config.runtime.seed, workers=True) os.makedirs(config.trainer.output_dir, exist_ok=True) data_module = CPCDataModule( DataModuleConfig( data=config.data, dataloader=config.dataloader, ) ) data_module.setup(stage="fit") lightning_module = CPCLightningModule( config=config, input_channels=data_module.input_channels ) trainer = L.Trainer( max_epochs=config.trainer.epochs, accelerator=config.runtime.accelerator, devices=config.runtime.devices, default_root_dir=config.trainer.output_dir, log_every_n_steps=5, ) trainer.fit(lightning_module, datamodule=data_module) ``` > [!NOTE] > > **Output (22 lines)** > > ``` > Seed set to 137 > /var/folders/gk/cdkvr2rn1yn547mssh0ccq4c0000gp/T/ipykernel_79284/1434763535.py:90: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature. > train_obj = torch.load(os.path.join(dataset_path, "train.pt")) > /var/folders/gk/cdkvr2rn1yn547mssh0ccq4c0000gp/T/ipykernel_79284/1434763535.py:91: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature. > test_obj = torch.load(os.path.join(dataset_path, "test.pt")) > GPU available: True (mps), used: True > TPU available: False, using: 0 TPU cores > IPU available: False, using: 0 IPUs > HPU available: False, using: 0 HPUs > | Name | Type | Params > ------------------------------------------- > 0 | model | CPCModel | 119 K > 1 | criterion | CPCCriterion | 15.0 K > ------------------------------------------- > 134 K Trainable params > 0 Non-trainable params > 134 K Total params > 0.537 Total estimated model params size (MB) > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'val_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'train_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/loops/fit_loop.py:293: The number of training batches (3) is smaller than the logging interval Trainer(log_every_n_steps=5). Set a lower value for log_every_n_steps if you want to see logs for the training epoch. > `Trainer.fit` stopped: `max_epochs=400` reached. > ``` ## Load Artifacts and Interpret ``` import numpy as np import pandas as pd import plotly.express as px import torch from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler ``` ### Visualize One Batch ``` for i in data_module.train_dataloader(): pred_data, pred_label = i break ``` ``` pred_data.shape, pred_label.shape ``` ``` (torch.Size([32, 1, 96]), torch.Size([32])) ``` ``` data_pca2 = PCA( n_components=2, ).fit_transform(pred_data.detach().numpy()[:, 0, :]) df_data_pca = pd.DataFrame(data_pca2, columns=["pc_1", "pc_2"]) df_data_pca["label"] = pred_label.numpy().astype(str) df_data_pca.head() ``` | | pc\_1 | pc\_2 | label | | --- | --- | --- | --- | | 0 | 6.116100 | \-4.477189 | 1 | | 1 | 1.128644 | 2.686490 | 1 | | 2 | \-5.751511 | \-1.372460 | 0 | | 3 | 1.572557 | 3.002156 | 1 | | 4 | 0.138050 | 3.217791 | 1 | ``` px.scatter( df_data_pca, x="pc_1", y="pc_2", color="label", title="PCA of CPC Input Data", width=800, height=600, color_discrete_sequence=px.colors.qualitative.Set2, ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` pred_label.numpy() ``` ``` array([1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1]) ``` ``` pred_context, pred_encoded = trainer.model.predict_step(pred_data) ``` ``` pred_context.shape, pred_encoded.shape ``` ``` (torch.Size([32, 4, 150]), torch.Size([32, 4, 50])) ``` ``` from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression from sklearn.manifold import TSNE from sklearn.metrics import silhouette_score from sklearn.model_selection import StratifiedKFold, cross_val_score ``` ``` context_pca2 = PCA( n_components=2, ).fit_transform(pred_context.detach().numpy()[:, 0, :]) df_context = pd.DataFrame(context_pca2, columns=["pc_1", "pc_2"]) df_context["label"] = pred_label.numpy().astype(str) df_context.head() ``` | | pc\_1 | pc\_2 | label | | --- | --- | --- | --- | | 0 | 0.628119 | 0.632394 | 1 | | 1 | \-1.162201 | \-0.019420 | 1 | | 2 | 0.278232 | \-0.113320 | 0 | | 3 | \-0.973403 | 0.825931 | 1 | | 4 | \-0.455618 | \-0.060431 | 1 | ``` px.scatter( df_context, x="pc_1", y="pc_2", color="label", title="PCA of CPC Context Representations", width=800, height=600, color_discrete_sequence=px.colors.qualitative.Set2, ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` context_tsne2d = TSNE( n_components=2, perplexity=15, random_state=0, # init="pca" ).fit_transform( # PCA( # n_components=10, # ).fit_transform( # pred_context.detach().numpy()[:,0,:] # ) pred_context.detach().numpy()[:, 0, :] ) df_context_tsne = pd.DataFrame(context_tsne2d, columns=["tsne_1", "tsne_2"]) df_context_tsne["label"] = pred_label.numpy().astype(str) df_context_tsne.head() ``` | | tsne\_1 | tsne\_2 | label | | --- | --- | --- | --- | | 0 | 105.335564 | \-61.871784 | 1 | | 1 | \-40.250008 | \-82.131645 | 1 | | 2 | 1.649548 | 52.997387 | 0 | | 3 | \-55.881496 | \-57.068775 | 1 | | 4 | 38.901333 | \-53.158035 | 1 | ``` px.scatter( df_context_tsne, x="tsne_1", y="tsne_2", color="label", title="t-SNE of CPC Context Representations", width=800, height=600, color_discrete_sequence=px.colors.qualitative.Set2, ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` encoded_pca2 = PCA( n_components=2, ).fit_transform(pred_encoded.detach().numpy()[:, 0, :]) df_encoded_pca = pd.DataFrame(encoded_pca2, columns=["pc_1", "pc_2"]) df_encoded_pca["label"] = pred_label.numpy().astype(str) df_encoded_pca.head() ``` | | pc\_1 | pc\_2 | label | | --- | --- | --- | --- | | 0 | 1.262788 | \-0.604505 | 1 | | 1 | 0.872135 | 2.952796 | 1 | | 2 | \-3.089964 | \-0.079860 | 0 | | 3 | 0.897206 | 1.603664 | 1 | | 4 | \-0.266165 | \-1.715062 | 1 | ``` px.scatter( df_encoded_pca, x="pc_1", y="pc_2", color="label", title="PCA of CPC Encoded Representations", width=800, height=600, color_discrete_sequence=px.colors.qualitative.Set2, ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` encoded_tsne2d = TSNE( n_components=2, perplexity=15, random_state=0, # init="pca" ).fit_transform( # PCA( # n_components=10, # ).fit_transform( # pred_encoded.detach().numpy()[:,0,:] # ) pred_encoded.detach().numpy()[:, 0, :] ) df_encoded_tsne = pd.DataFrame(encoded_tsne2d, columns=["tsne_1", "tsne_2"]) df_encoded_tsne["label"] = pred_label.numpy().astype(str) df_encoded_tsne.head() ``` | | tsne\_1 | tsne\_2 | label | | --- | --- | --- | --- | | 0 | \-1.881363 | 3.878124 | 1 | | 1 | \-1.062006 | 6.837996 | 1 | | 2 | \-0.531934 | 0.195463 | 0 | | 3 | \-1.218854 | 6.131797 | 1 | | 4 | 0.197280 | 2.856672 | 1 | ``` px.scatter( df_encoded_tsne, x="tsne_1", y="tsne_2", color="label", title="t-SNE of CPC Encoded Representations", width=800, height=600, color_discrete_sequence=px.colors.qualitative.Set2, ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ### Visualizez All ``` import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objects as go from sklearn.decomposition import PCA ``` ``` # Faceted comparison: raw vs context vs encoded for the same reduction method # Produces two figures: # 1) PCA with facet rows (raw/context/encoded) # 2) t-SNE with facet rows (raw/context/encoded) # Rebuild tensors if they are not already in memory if ( "raw_all" not in globals() or "context_all" not in globals() or "encoded_all" not in globals() ): module = trainer.model if hasattr(trainer, "model") else lightning_module module.eval() device = module.device all_raw, all_context, all_encoded, all_labels = [], [], [], [] with torch.no_grad(): for x, y_batch in data_module.train_dataloader(): x = x.float().to(device) context, encoded = module.model(x) all_raw.append(x.cpu()) all_context.append(context.cpu()) all_encoded.append(encoded.cpu()) all_labels.append(y_batch.cpu()) raw_all = torch.cat(all_raw, dim=0) # [N, C_in, T] context_all = torch.cat(all_context, dim=0) # [N, T_enc, C] encoded_all = torch.cat(all_encoded, dim=0) # [N, T_enc, C] y = torch.cat(all_labels, dim=0).numpy() y_str = y.astype(str) # Choose one view per family for fair visual comparison Z_by_family = { "raw": raw_all.reshape(raw_all.shape[0], -1).numpy(), # flatten_all_channels "context": context_all.reshape(context_all.shape[0], -1).numpy(), # flatten_tokens "encoded": encoded_all.reshape(encoded_all.shape[0], -1).numpy(), # flatten_tokens # "encoded": ( # encoded_all[:, 0, :] # .reshape(encoded_all.shape[0], -1) # .numpy(), # flatten_tokens # ) } family_order = ["raw", "context", "encoded"] def reduce_family(Z, method="pca", random_state=0): if method == "pca": return make_pipeline( StandardScaler(), PCA(n_components=2, random_state=random_state), ).fit_transform(Z) if method == "tsne": n = Z.shape[0] perp = max(5, min(30, (n - 1) // 3)) return TSNE( n_components=2, perplexity=perp, random_state=random_state, init="pca", ).fit_transform(Z) raise ValueError(f"Unknown method: {method}") def build_facet_df(method): rows = [] for fam in family_order: Z2 = reduce_family(Z_by_family[fam], method=method, random_state=0) df_f = pd.DataFrame( { "dim1": Z2[:, 0], "dim2": Z2[:, 1], "label": y_str, "family": fam, } ) rows.append(df_f) return pd.concat(rows, ignore_index=True) def plot_facet(dataframe, method, width=700, height=1100): df_plot = dataframe.copy() title = f"{method.upper()} comparison by family (facet rows)" fig = px.scatter( df_plot, x="dim1", y="dim2", color="label", facet_row="family", category_orders={"family": family_order}, title=title, width=width, height=height, # color_discrete_sequence=px.colors.qualitative.Set2, opacity=0.8, ) fig.update_traces(marker=dict(size=5)) fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1])) fig.update_layout(legend_title_text="label") fig.update_xaxes(matches=None) fig.update_yaxes(matches=None) fig.show() # Show both methods with the same faceting layout df_plot_pca = build_facet_df("pca") plot_facet(df_plot_pca, "pca") df_plot_tsne = build_facet_df("tsne") plot_facet(df_plot_tsne, "tsne") ``` *Interactive Plotly figure: enable JavaScript to view it.* *Interactive Plotly figure: enable JavaScript to view it.* ``` df_dr = pd.merge( df_plot_pca[["dim1", "dim2"]], df_plot_tsne, how="left", left_index=True, right_index=True, suffixes=("_pca", "_tsne"), ) df_dr ``` | | dim1\_pca | dim2\_pca | dim1\_tsne | dim2\_tsne | label | family | | --- | --- | --- | --- | --- | --- | --- | | 0 | 2.950376 | \-2.864436 | 0.618348 | 0.264208 | 1 | raw | | 1 | 2.506416 | \-3.436044 | 1.084404 | \-1.501831 | 1 | raw | | 2 | 1.843408 | \-3.240472 | \-2.921056 | 1.063462 | 1 | raw | | 3 | 2.427340 | \-2.945407 | 0.168692 | \-1.342368 | 1 | raw | | 4 | 3.068460 | \-3.444828 | 0.569116 | \-0.961520 | 1 | raw | | ... | ... | ... | ... | ... | ... | ... | | 265 | 6.230095 | 0.403519 | \-4.444399 | 5.568133 | 0 | encoded | | 266 | \-0.616168 | \-7.360590 | 4.366518 | 2.369284 | 0 | encoded | | 267 | \-4.767138 | \-4.490649 | 2.753743 | \-2.349631 | 1 | encoded | | 268 | \-4.484152 | \-0.612002 | 0.638832 | \-1.503255 | 1 | encoded | | 269 | 9.594614 | \-2.312617 | \-4.331682 | 5.875957 | 0 | encoded | 270 rows × 6 columns ``` import numpy as np import pandas as pd # Expect df_dr columns from your merge: # dim1_pca, dim2_pca, dim1_tsne, dim2_tsne, label, family required = {"dim1_pca", "dim2_pca", "label", "family"} missing = required - set(df_dr.columns) if missing: raise ValueError(f"df_dr is missing required columns: {missing}") # Keep only families needed for this vector df_tmp = df_dr[df_dr["family"].isin(["raw", "encoded"])].copy() # Create per-sample index inside each family block so raw and encoded can be paired df_tmp["idx"] = df_tmp.groupby("family").cumcount() # Split and rename PCA columns raw_df = ( df_tmp[df_tmp["family"] == "raw"][["idx", "label", "dim1_pca", "dim2_pca"]] .rename(columns={"dim1_pca": "raw_x", "dim2_pca": "raw_y"}) .reset_index(drop=True) ) enc_df = ( df_tmp[df_tmp["family"] == "encoded"][["idx", "label", "dim1_pca", "dim2_pca"]] .rename(columns={"dim1_pca": "enc_x", "dim2_pca": "enc_y", "label": "label_enc"}) .reset_index(drop=True) ) # Pair raw and encoded rows by idx (and optionally validate labels) df_vec = raw_df.merge(enc_df, on="idx", how="inner") # Optional sanity check: label consistency if not (df_vec["label"] == df_vec["label_enc"]).all(): print("Warning: label mismatch found between raw and encoded pairing.") df_vec = df_vec.drop(columns=["label_enc"]) # Vector components and norm df_vec["vec_x"] = df_vec["enc_x"] - df_vec["raw_x"] df_vec["vec_y"] = df_vec["enc_y"] - df_vec["raw_y"] df_vec["vec_norm"] = np.linalg.norm(df_vec[["vec_x", "vec_y"]].to_numpy(), axis=1) df_vec.head() ``` | | idx | label | raw\_x | raw\_y | enc\_x | enc\_y | vec\_x | vec\_y | vec\_norm | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 0 | 0 | 1 | 2.950376 | \-2.864436 | \-5.389060 | 2.487167 | \-8.339437 | 5.351604 | 9.908878 | | 1 | 1 | 1 | 2.506416 | \-3.436044 | \-3.676352 | 3.964328 | \-6.182768 | 7.400371 | 9.643242 | | 2 | 2 | 1 | 1.843408 | \-3.240472 | \-0.605093 | 3.002216 | \-2.448501 | 6.242688 | 6.705693 | | 3 | 3 | 1 | 2.427340 | \-2.945407 | \-3.087973 | 2.702965 | \-5.515312 | 5.648372 | 7.894477 | | 4 | 4 | 1 | 3.068460 | \-3.444828 | \-5.482408 | 3.071847 | \-8.550868 | 6.516675 | 10.751019 | ``` labels = sorted(df_vec["label"].unique()) label_symbols = ["circle", "square", "triangle-up", "star", "hexagram"] raw_color = "rgba(31, 119, 180, 0.85)" # blue enc_color = "rgba(214, 39, 40, 0.85)" # red line_x = np.column_stack( [df_vec["raw_x"], df_vec["enc_x"], np.full(len(df_vec), np.nan)] ).ravel() line_y = np.column_stack( [df_vec["raw_y"], df_vec["enc_y"], np.full(len(df_vec), np.nan)] ).ravel() fig = go.Figure() fig.add_trace( go.Scatter( x=line_x, y=line_y, mode="lines", line=dict(color="rgba(80,80,80,0.20)", width=1), hoverinfo="skip", showlegend=False, ) ) for i, lbl in enumerate(labels): sym = label_symbols[i % len(label_symbols)] mask = df_vec["label"] == lbl subset = df_vec[mask] # raw — blue, label symbol fig.add_trace( go.Scatter( x=subset["raw_x"], y=subset["raw_y"], mode="markers", marker=dict( size=9, symbol=sym, color=raw_color, line=dict(width=1, color="white") ), name=f"raw (label={lbl})", legendgroup=f"label_{lbl}", text=[f"idx={r}, label={lbl}" for r in subset["idx"]], hovertemplate="RAW
%{text}
x=%{x:.3f}, y=%{y:.3f}", ) ) # encoded — red, same label symbol fig.add_trace( go.Scatter( x=subset["enc_x"], y=subset["enc_y"], mode="markers", marker=dict( size=9, symbol=sym, color=enc_color, line=dict(width=1, color="white") ), name=f"encoded (label={lbl})", legendgroup=f"label_{lbl}", text=[ f"idx={r}, label={lbl}, norm={n:.3f}" for r, n in zip(subset["idx"], subset["vec_norm"]) ], hovertemplate="ENCODED
%{text}
x=%{x:.3f}, y=%{y:.3f}", ) ) fig.update_layout( title=f"Per-index vectors — color: raw(blue)/encoded(red), symbol: label (N={len(df_vec)})", xaxis_title="PC1 (raw space) / PC1 (encoded space)", yaxis_title="PC2", width=980, height=720, legend=dict(groupclick="toggleitem"), ) fig.show() ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` # Pick one label value to plot target_label = 1.0 # change this to the label you want # For float/continuous labels, exact equality can be brittle, so use tolerance tol = 1e-8 subset = df_vec[ np.isclose(df_vec["label"].astype(float), float(target_label), atol=tol) ].copy() if subset.empty: raise ValueError(f"No rows found for target_label={target_label} (tol={tol})") raw_color = "rgba(31, 119, 180, 0.85)" # blue enc_color = "rgba(214, 39, 40, 0.85)" # red # Connector lines for only the selected label line_x = np.column_stack( [subset["raw_x"], subset["enc_x"], np.full(len(subset), np.nan)] ).ravel() line_y = np.column_stack( [subset["raw_y"], subset["enc_y"], np.full(len(subset), np.nan)] ).ravel() fig = go.Figure() fig.add_trace( go.Scatter( x=line_x, y=line_y, mode="lines", line=dict(color="rgba(80,80,80,0.20)", width=1), hoverinfo="skip", showlegend=False, ) ) fig.add_trace( go.Scatter( x=subset["raw_x"], y=subset["raw_y"], mode="markers", marker=dict( size=9, symbol="circle", color=raw_color, line=dict(width=1, color="white") ), name=f"raw (label={target_label})", text=[ f"idx={r}, label={lbl}" for r, lbl in zip(subset["idx"], subset["label"]) ], hovertemplate="RAW
%{text}
x=%{x:.3f}, y=%{y:.3f}", ) ) fig.add_trace( go.Scatter( x=subset["enc_x"], y=subset["enc_y"], mode="markers", marker=dict( size=9, symbol="diamond", color=enc_color, line=dict(width=1, color="white") ), name=f"encoded (label={target_label})", text=[ f"idx={r}, label={lbl}, norm={n:.3f}" for r, lbl, n in zip(subset["idx"], subset["label"], subset["vec_norm"]) ], hovertemplate="ENCODED
%{text}
x=%{x:.3f}, y=%{y:.3f}", ) ) fig.update_layout( title=f"Per-index vectors for label={target_label} (N={len(subset)})", xaxis_title="PC1 (raw space) / PC1 (encoded space)", yaxis_title="PC2", width=980, height=720, ) fig.show() ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` # Derive vec_x / vec_y from whichever df_vec is in scope vec_x = (df_vec["enc_x"] - df_vec["raw_x"]).values vec_y = (df_vec["enc_y"] - df_vec["raw_y"]).values V = np.stack([vec_x, vec_y], axis=1) # [N, 2] labels = df_vec["label"].values # 1) Mean displacement and residuals v_mean = V.mean(axis=0) residuals = V - v_mean residual_norms = np.linalg.norm(residuals, axis=1) vector_norms = np.linalg.norm(V, axis=1) explained_by_mean = 1 - (residual_norms / (vector_norms + 1e-9)) print(f"Mean displacement vector: ({v_mean[0]:.3f}, {v_mean[1]:.3f})") print(f"Mean |v|: {vector_norms.mean():.3f} ± {vector_norms.std():.3f}") print(f"Mean |residual|: {residual_norms.mean():.3f} ± {residual_norms.std():.3f}") print(f"Fraction explained by global shift: {explained_by_mean.mean():.3f}") # 2) Angle relative to mean direction v_mean_unit = v_mean / (np.linalg.norm(v_mean) + 1e-9) cos_sim = np.clip(V @ v_mean_unit / (vector_norms + 1e-9), -1, 1) angles_deg = np.degrees(np.arccos(cos_sim)) # 3) PCA of displacement vectors pca_v = PCA(n_components=2).fit(V) print( f"\nPCA of displacement vectors — variance explained: {pca_v.explained_variance_ratio_}" ) df_angle = pd.DataFrame( { "angle_deg": angles_deg, "residual_norm": residual_norms, "vec_norm": vector_norms, "label": labels, } ) fig = px.histogram( df_angle, x="angle_deg", color="label", nbins=30, barmode="overlay", opacity=0.7, title="Distribution of displacement angle relative to mean vector (degrees)
" "Near 0° = moves with the crowd; large angle = outlier movement", labels={"angle_deg": "Angle to mean displacement (°)"}, width=850, height=450, ) fig.show() fig2 = px.scatter( df_angle, x="vec_norm", y="residual_norm", color="label", title="Vector norm vs residual norm after removing global shift
" "Near x-axis = moved with global trend; high residual = distinctive movement", labels={"vec_norm": "|v|", "residual_norm": "|v - v̄|"}, width=800, height=500, opacity=0.8, ) fig2.add_hline(y=0, line_dash="dot", line_color="gray") fig2.show() ``` ``` Mean displacement vector: (0.000, 0.000) Mean |v|: 11.922 ± 5.492 Mean |residual|: 11.922 ± 5.492 Fraction explained by global shift: -0.000 PCA of displacement vectors — variance explained: [0.6134818 0.3865182] ``` *Interactive Plotly figure: enable JavaScript to view it.* *Interactive Plotly figure: enable JavaScript to view it.* ## Downstream Tasks ``` import lightning as L ``` ``` import numpy as np import pandas as pd import torch import torch.nn as nn from lightning.pytorch.callbacks import EarlyStopping from sklearn.metrics import accuracy_score, f1_score from sklearn.model_selection import RepeatedStratifiedKFold from sklearn.preprocessing import StandardScaler from torch.utils.data import DataLoader, TensorDataset class SmallMLPClassifier(L.LightningModule): def __init__( self, input_dim: int, n_classes: int, hidden_dim: int = 128, dropout: float = 0.2, lr: float = 1e-3, weight_decay: float = 1e-4, class_weights: torch.Tensor | None = None, ): super().__init__() self.save_hyperparameters(ignore=["class_weights"]) self.net = nn.Sequential( nn.Linear(input_dim, hidden_dim), nn.ReLU(), nn.Dropout(dropout), nn.Linear(hidden_dim, hidden_dim // 2), nn.ReLU(), nn.Dropout(dropout), nn.Linear(hidden_dim // 2, n_classes), ) self.loss_fn = nn.CrossEntropyLoss(weight=class_weights) def forward(self, x): return self.net(x) def training_step(self, batch, batch_idx): x, y = batch logits = self(x) loss = self.loss_fn(logits, y) self.log("train_loss", loss, prog_bar=False, on_epoch=True, on_step=False) return loss def validation_step(self, batch, batch_idx): x, y = batch logits = self(x) loss = self.loss_fn(logits, y) self.log("val_loss", loss, prog_bar=False, on_epoch=True, on_step=False) return loss def predict_step(self, batch, batch_idx, dataloader_idx=0): x, _ = batch return self(x) def configure_optimizers(self): return torch.optim.AdamW( self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay, ) def collect_raw_and_encoded(loader, model_module): x_raw, x_enc, y_all = [], [], [] model_module.eval() device = model_module.device with torch.no_grad(): for x_batch, y_batch in loader: x_batch = x_batch.float() raw_feat = x_batch.reshape(x_batch.size(0), -1).cpu().numpy() _, encoded = model_module.model(x_batch.to(device)) # encoded is [B, T_enc, C]; pool over time (second dimension) -> [B, C] # enc_feat = encoded.mean(dim=1).cpu().numpy() # flatten the encoded enc_feat = encoded.reshape(encoded.size(0), -1).cpu().numpy() x_raw.append(raw_feat) x_enc.append(enc_feat) y_all.append(y_batch.cpu().numpy()) X_raw = np.concatenate(x_raw, axis=0) X_enc = np.concatenate(x_enc, axis=0) y = np.concatenate(y_all, axis=0) return X_raw, X_enc, y def fit_predict_mlp_on_fold( X_train, y_train, X_val, y_val, seed: int = 0, max_epochs: int = 80, batch_size: int = 32, ): # Scale inside each fold to avoid leakage scaler = StandardScaler() X_train_s = scaler.fit_transform(X_train).astype(np.float32) X_val_s = scaler.transform(X_val).astype(np.float32) y_train_t = torch.from_numpy(y_train.astype(np.int64)) y_val_t = torch.from_numpy(y_val.astype(np.int64)) train_ds = TensorDataset(torch.from_numpy(X_train_s), y_train_t) val_ds = TensorDataset(torch.from_numpy(X_val_s), y_val_t) train_loader = DataLoader( train_ds, batch_size=batch_size, shuffle=True, num_workers=0 ) val_loader = DataLoader(val_ds, batch_size=batch_size, shuffle=False, num_workers=0) n_classes = int(np.unique(y_train).size) counts = np.bincount(y_train, minlength=n_classes).astype(np.float32) class_weights = counts.sum() / np.maximum(counts, 1.0) class_weights = class_weights / class_weights.mean() class_weights_t = torch.tensor(class_weights, dtype=torch.float32) L.seed_everything(seed, workers=True) model = SmallMLPClassifier( input_dim=X_train_s.shape[1], n_classes=n_classes, hidden_dim=64, dropout=0.2, lr=1e-3, weight_decay=1e-4, class_weights=class_weights_t, ) trainer = L.Trainer( max_epochs=max_epochs, accelerator="auto", devices=1, logger=False, enable_checkpointing=False, enable_progress_bar=False, deterministic=True, callbacks=[EarlyStopping(monitor="val_loss", mode="min", patience=8)], ) trainer.fit(model, train_dataloaders=train_loader, val_dataloaders=val_loader) pred_batches = trainer.predict(model, dataloaders=val_loader) logits = torch.cat(pred_batches, dim=0) y_pred = torch.argmax(logits, dim=1).cpu().numpy() return y_pred def evaluate_representation_cv_mlp(X, y, splits, rep_name): rows = [] for split_id, (idx_tr, idx_va) in enumerate(splits, start=1): y_pred = fit_predict_mlp_on_fold( X_train=X[idx_tr], y_train=y[idx_tr], X_val=X[idx_va], y_val=y[idx_va], seed=split_id, max_epochs=80, batch_size=32, ) rows.append( { "representation": rep_name, "split_id": split_id, "repeat": (split_id - 1) // 5 + 1, "fold": (split_id - 1) % 5 + 1, "accuracy": accuracy_score(y[idx_va], y_pred), "f1_macro": f1_score(y[idx_va], y_pred, average="macro"), "f1_weighted": f1_score(y[idx_va], y_pred, average="weighted"), } ) return pd.DataFrame(rows) # Fixed CPC model module = trainer.model if hasattr(trainer, "model") else lightning_module # Feature extraction once (CPC frozen) train_loader = data_module.train_dataloader() test_loader = data_module.val_dataloader() X_train_raw, X_train_enc, y_train = collect_raw_and_encoded(train_loader, module) X_test_raw, X_test_enc, y_test = collect_raw_and_encoded(test_loader, module) USE_TEST_IN_CV = False if USE_TEST_IN_CV: X_raw = np.concatenate([X_train_raw, X_test_raw], axis=0) X_enc = np.concatenate([X_train_enc, X_test_enc], axis=0) y_all = np.concatenate([y_train, y_test], axis=0) else: X_raw = X_train_raw X_enc = X_train_enc y_all = y_train cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=5, random_state=42) splits = list(cv.split(X_raw, y_all)) df_raw = evaluate_representation_cv_mlp(X_raw, y_all, splits, "raw") df_enc = evaluate_representation_cv_mlp(X_enc, y_all, splits, "encoded") df_cv = pd.concat([df_raw, df_enc], ignore_index=True) summary = ( df_cv.groupby("representation")[["accuracy", "f1_macro", "f1_weighted"]] .agg(["mean", "std"]) .round(4) ) paired = df_raw[["split_id", "accuracy", "f1_macro", "f1_weighted"]].merge( df_enc[["split_id", "accuracy", "f1_macro", "f1_weighted"]], on="split_id", suffixes=("_raw", "_enc"), ) paired["acc_delta_enc_minus_raw"] = paired["accuracy_enc"] - paired["accuracy_raw"] paired["f1m_delta_enc_minus_raw"] = paired["f1_macro_enc"] - paired["f1_macro_raw"] paired["f1w_delta_enc_minus_raw"] = ( paired["f1_weighted_enc"] - paired["f1_weighted_raw"] ) print("=== MLP Repeated Stratified 5x5 CV Summary (mean ± std) ===") print(summary) print("\n=== Paired Delta Across Same Splits (encoded - raw) ===") print( paired[ [ "acc_delta_enc_minus_raw", "f1m_delta_enc_minus_raw", "f1w_delta_enc_minus_raw", ] ] .agg(["mean", "std", "min", "max"]) .round(4) ) print("\n=== Win Rate (encoded > raw) ===") print( { "accuracy": float((paired["acc_delta_enc_minus_raw"] > 0).mean()), "f1_macro": float((paired["f1m_delta_enc_minus_raw"] > 0).mean()), "f1_weighted": float((paired["f1w_delta_enc_minus_raw"] > 0).mean()), } ) df_cv.head() ``` > [!NOTE] > > **Output (61 lines)** > > ``` > ... (1254 earlier lines) > 15.0 K Trainable params > 0 Non-trainable params > 15.0 K Total params > 0.060 Total estimated model params size (MB) > ... (36 lines omitted) ... > | Name | Type | Params > --------------------------------------------- > 0 | net | Sequential | 15.0 K > 1 | loss_fn | CrossEntropyLoss | 0 > --------------------------------------------- > 15.0 K Trainable params > 0 Non-trainable params > 15.0 K Total params > 0.060 Total estimated model params size (MB) > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: PossibleUserWarning: > The 'val_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: PossibleUserWarning: > The 'train_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > `Trainer.fit` stopped: `max_epochs=80` reached. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: PossibleUserWarning: > The 'predict_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > Seed set to 25 > GPU available: True (mps), used: True > TPU available: False, using: 0 TPU cores > IPU available: False, using: 0 IPUs > HPU available: False, using: 0 HPUs > | Name | Type | Params > --------------------------------------------- > 0 | net | Sequential | 15.0 K > 1 | loss_fn | CrossEntropyLoss | 0 > --------------------------------------------- > 15.0 K Trainable params > 0 Non-trainable params > 15.0 K Total params > 0.060 Total estimated model params size (MB) > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: PossibleUserWarning: > The 'val_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: PossibleUserWarning: > The 'train_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > === MLP Repeated Stratified 5x5 CV Summary (mean ± std) === > accuracy f1_macro f1_weighted > mean std mean std mean std > representation > encoded 0.8689 0.0715 0.8466 0.0849 0.8679 0.0731 > raw 0.8778 0.0949 0.8557 0.1088 0.8765 0.0945 > === Paired Delta Across Same Splits (encoded - raw) === > acc_delta_enc_minus_raw f1m_delta_enc_minus_raw \ > mean -0.0089 -0.0091 > std 0.0780 0.0883 > min -0.1111 -0.1519 > max 0.1667 0.1845 > f1w_delta_enc_minus_raw > mean -0.0086 > std 0.0773 > min -0.1248 > max 0.1588 > === Win Rate (encoded > raw) === > {'accuracy': 0.28, 'f1_macro': 0.32, 'f1_weighted': 0.32} > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: PossibleUserWarning: > The 'predict_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > ``` | | representation | split\_id | repeat | fold | accuracy | f1\_macro | f1\_weighted | | --- | --- | --- | --- | --- | --- | --- | --- | | 0 | raw | 1 | 1 | 1 | 0.777778 | 0.750000 | 0.787037 | | 1 | raw | 2 | 1 | 2 | 0.944444 | 0.925926 | 0.942387 | | 2 | raw | 3 | 1 | 3 | 0.944444 | 0.934545 | 0.943030 | | 3 | raw | 4 | 1 | 4 | 0.611111 | 0.578595 | 0.617614 | | 4 | raw | 5 | 1 | 5 | 1.000000 | 1.000000 | 1.000000 | ``` from scipy.stats import binomtest, ttest_rel, wilcoxon def summarize_paired(metric_name, col_raw, col_enc): d = paired[col_enc] - paired[col_raw] n = len(d) t_res = ttest_rel(paired[col_enc], paired[col_raw], alternative="two-sided") w_res = wilcoxon(d, zero_method="wilcox", alternative="two-sided", correction=False) wins = int((d > 0).sum()) losses = int((d < 0).sum()) ties = int((d == 0).sum()) # Sign test ignores ties n_sign = wins + losses sign_p = np.nan if n_sign > 0: sign_p = binomtest(k=wins, n=n_sign, p=0.5, alternative="two-sided").pvalue mean_delta = float(d.mean()) std_delta = float(d.std(ddof=1)) se = std_delta / np.sqrt(n) ci95_low = mean_delta - 1.96 * se ci95_high = mean_delta + 1.96 * se return { "metric": metric_name, "n_splits": n, "mean_delta_enc_minus_raw": mean_delta, "std_delta": std_delta, "ci95_low": ci95_low, "ci95_high": ci95_high, "wins": wins, "losses": losses, "ties": ties, "ttest_p": float(t_res.pvalue), "wilcoxon_p": float(w_res.pvalue), "sign_test_p": float(sign_p) if not np.isnan(sign_p) else np.nan, } stats_rows = [ summarize_paired("accuracy", "accuracy_raw", "accuracy_enc"), summarize_paired("f1_macro", "f1_macro_raw", "f1_macro_enc"), summarize_paired("f1_weighted", "f1_weighted_raw", "f1_weighted_enc"), ] df_stats = pd.DataFrame(stats_rows).round(6) print("=== Paired significance tests: encoded vs raw (same 25 splits) ===") print(df_stats.to_string(index=False)) alpha = 0.05 print("\n=== Quick significance flags at alpha=0.05 ===") for _, r in df_stats.iterrows(): print( f"{r['metric']}: " f"ttest={r['ttest_p'] < alpha}, " f"wilcoxon={r['wilcoxon_p'] < alpha}, " f"sign_test={r['sign_test_p'] < alpha if not np.isnan(r['sign_test_p']) else False}" ) ``` ``` === Paired significance tests: encoded vs raw (same 25 splits) === metric n_splits mean_delta_enc_minus_raw std_delta ci95_low ci95_high wins losses ties ttest_p wilcoxon_p sign_test_p accuracy 25 -0.008889 0.078042 -0.039481 0.021704 7 12 6 0.574313 0.527604 0.359283 f1_macro 25 -0.009073 0.088270 -0.043675 0.025529 8 14 3 0.611992 0.684776 0.286279 f1_weighted 25 -0.008558 0.077293 -0.038857 0.021741 8 14 3 0.584967 0.661137 0.286279 === Quick significance flags at alpha=0.05 === accuracy: ttest=False, wilcoxon=False, sign_test=False f1_macro: ttest=False, wilcoxon=False, sign_test=False f1_weighted: ttest=False, wilcoxon=False, sign_test=False ``` # CPC for Time Series Data References: - [mqwfrog/ULTS/tree/main/models/CPC]() - [ECG200]() - R. T. Olszewski, “Generalized feature extraction for structural pattern recognition in time-series data,” Carnegie Mellon University, Pittsburgh, PA, 2001. Available: [https://www.cs.cmu.edu/\~bobski/pubs/tr01108-twosided.pdf]() configs ``` from pathlib import Path from typing import Literal ``` ``` import numpy as np import pandas as pd import plotly.express as px import yaml from pydantic import BaseModel, Field ``` ``` df = pd.DataFrame( {"t": np.linspace(0, 100, 501), "y": np.sin(np.linspace(0, 100, 501))} ) df = df.astype(np.float32) ``` ``` px.line(df, x="t", y="y") ``` *Interactive Plotly figure: enable JavaScript to view it.* Data ``` from ts_dl_utils.datasets.dataset import DataFrameDataModule ``` Modules ``` class ConvLayerConfig(BaseModel): """Single 1D convolution specification. Parameters define one convolution block as ``Conv1d(in_channels, out_channels, kernel_size, stride, padding)``. """ kernel_size: int stride: int padding: int class EncoderConfig(BaseModel): """Encoder architecture and normalization settings.""" hidden_size: int = 256 norm_mode: Literal["batchNorm", "instanceNorm", "ID", "layerNorm"] = "layerNorm" conv_layers: list[ConvLayerConfig] = Field( default_factory=lambda: [ ConvLayerConfig(kernel_size=10, stride=5, padding=3), ConvLayerConfig(kernel_size=8, stride=4, padding=2), ConvLayerConfig(kernel_size=4, stride=2, padding=1), ConvLayerConfig(kernel_size=4, stride=2, padding=1), ConvLayerConfig(kernel_size=4, stride=2, padding=1), ] ) class ARConfig(BaseModel): """Autoregressive model selection and parameters. Supports recurrent modes (GRU/LSTM/RNN), Transformer mode, and identity mode (``no_ar``). """ mode: Literal["GRU", "LSTM", "RNN", "transformer", "no_ar"] = "LSTM" hidden_size: int = 256 n_levels: int = 1 reverse: bool = False class LossConfig(BaseModel): """CPC/InfoNCE objective configuration.""" n_predictions: int = 12 negative_sampling_ext: int = 128 temperature: float = 0.07 import math ``` ``` from functools import cached_property from typing import Callable, Literal import torch import torch.nn as nn import torch.nn.functional as F class CPCEncoder(nn.Module): """Convolutional encoder for time-series CPC. Input is expected as ``[B, C_in, T]`` and output as ``[B, H, T_enc]``, where ``H`` is ``size_hidden`` and ``T_enc`` depends on convolution specs. """ def __init__( self, input_channels: int = 1, size_hidden: int = 256, conv_specs: list[tuple[int, int, int]] | None = None, ): """Build the encoder stack. :param input_channels: Number of input channels ``C_in``. :param size_hidden: Number of output channels for each convolution block. :param conv_specs: List of convolution settings as ``(kernel_size, stride, padding)``. If ``None``, a default 5-layer downsampling stack is used. """ super().__init__() norm_factory: Callable[[int], nn.Module] # norm_factory = nn.BatchNorm1d norm_factory = nn.Identity if conv_specs is None: conv_specs = [ (10, 5, 3), (8, 4, 2), (4, 2, 1), (4, 2, 1), (4, 2, 1), ] blocks: list[nn.Module] = [] in_channels = input_channels for kernel_size, stride, padding in conv_specs: blocks.extend( [ nn.Conv1d( in_channels, size_hidden, kernel_size, stride=stride, padding=padding, ), norm_factory(size_hidden), nn.ReLU(), ] ) in_channels = size_hidden self.network = nn.Sequential(*blocks) self.output_dim = size_hidden @cached_property def output_dimension(self) -> int: """Return the encoder feature dimension ``H``.""" return self.output_dim def forward(self, x: torch.Tensor) -> torch.Tensor: """Encode raw sequence features. :param x: Input tensor with shape ``[B, C_in, T]``. :returns: Encoded tensor with shape ``[B, H, T_enc]``. """ return self.network(x) class CPCAR(nn.Module): """Recurrent autoregressive context model for CPC. Operates on encoded sequences in ``[B, T, C]`` format and returns contextualized representations in ``[B, T, C_ctx]``. """ def __init__( self, dim_encoded: int, dim_output: int, n_levels_gru: int = 1, rnn_type: Literal["GRU", "LSTM", "RNN"] = "LSTM", reverse: bool = False, ): """Initialize recurrent AR module. :param dim_encoded: Input feature size ``C`` from the encoder. :param dim_output: Hidden/context size ``C_ctx`` of the recurrent module. :param n_levels_gru: Number of recurrent layers. :param rnn_type: Recurrent cell type. :param reverse: If ``True``, run AR in reverse time and flip output back. """ super().__init__() self.reverse = reverse rnn_cls = {"LSTM": nn.LSTM, "RNN": nn.RNN, "GRU": nn.GRU}[rnn_type] self.rnn = rnn_cls( dim_encoded, dim_output, num_layers=n_levels_gru, batch_first=True ) @cached_property def output_dimension(self) -> int: """Return context feature dimension ``C_ctx``.""" return self.rnn.hidden_size def forward(self, x: torch.Tensor) -> torch.Tensor: """Run recurrent AR on encoded sequence. :param x: Encoded tensor with shape ``[B, T, C]``. :returns: Context tensor with shape ``[B, T, C_ctx]``. """ if self.reverse: x = torch.flip(x, [1]) try: self.rnn.flatten_parameters() except RuntimeError: pass x, _ = self.rnn(x) if self.reverse: x = torch.flip(x, [1]) return x class CPCModel(nn.Module): """Compose encoder and autoregressive context model.""" def __init__(self, encoder: nn.Module, ar: nn.Module): """Initialize CPC model. :param encoder: Module mapping ``[B, C_in, T]`` to ``[B, C_enc, T_enc]``. :param ar: Module mapping ``[B, T_enc, C_enc]`` to context features ``[B, T_enc, C_ctx]``. """ super().__init__() self.encoder = encoder self.ar = ar def forward(self, batch_data: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: """Run encoder then AR network. :param batch_data: Input batch with shape ``[B, C_in, T]``. :returns: Tuple ``(context, encoded)`` where ``context`` has shape ``[B, T_enc, C_ctx]`` and ``encoded`` has shape ``[B, T_enc, C_enc]``. """ encoded = self.encoder(batch_data).permute(0, 2, 1) context = self.ar(encoded) return context, encoded class CPCCriterion(nn.Module): """InfoNCE loss used by Contrastive Predictive Coding. For each prediction horizon ``k``, the criterion predicts future encoded vectors from context, then contrasts one positive against sampled negatives. """ def __init__( self, dim_context: int, dim_encoded: int, n_predictions: int = 12, n_negatives: int = 128, temperature: float = 0.07, ): """Initialize CPC criterion. :param dim_context: Context feature dimension ``C_ctx``. :param dim_encoded: Encoded target feature dimension ``C_enc``. :param n_predictions: Number of future steps to predict. :param n_negatives: Number of negative samples per query. :param temperature: Logit temperature scaling factor. """ super().__init__() self.n_predictions = n_predictions self.n_negatives = n_negatives self.temperature = temperature self.predictors = nn.ModuleList( [ nn.Linear(dim_context, dim_encoded, bias=False) for _ in range(n_predictions) ] ) def _sample_negatives( self, encoded_pool: torch.Tensor, n_queries: int ) -> torch.Tensor: """Sample negative encoded vectors. :param encoded_pool: Flattened encoded with shape ``[B*T, C_enc]``. :param n_queries: Number of query vectors to match. :returns: Negative samples with shape ``[n_queries, n_negatives, C_enc]``. """ idx = torch.randint( low=0, high=encoded_pool.size(0), size=(n_queries, self.n_negatives), device=encoded_pool.device, ) return encoded_pool[idx] def forward(self, context: torch.Tensor, encoded: torch.Tensor) -> torch.Tensor: """Compute averaged InfoNCE loss across valid prediction horizons. :param context: Context tensor with shape ``[B, T, C_ctx]``. :param encoded: Encoded tensor with shape ``[B, T, C_enc]``. :returns: Scalar loss tensor. :raises RuntimeError: If no prediction horizon is valid, usually because ``T`` is too short relative to ``n_predictions``. """ _, seq_len, _ = encoded.shape encoded_pool = F.normalize(encoded.flatten(0, 1), dim=-1) total_loss: torch.Tensor | None = None used_steps = 0 for k in range(1, self.n_predictions + 1): if seq_len - k <= 0: break c_t = context[:, : seq_len - k, :] z_pos = encoded[:, k:, :] z_hat = self.predictors[k - 1](c_t) z_hat = F.normalize(z_hat.flatten(0, 1), dim=-1) z_pos = F.normalize(z_pos.flatten(0, 1), dim=-1) n_queries = z_hat.size(0) pos_logits = torch.sum(z_hat * z_pos, dim=-1, keepdim=True) z_neg = self._sample_negatives(encoded_pool, n_queries) neg_logits = torch.einsum("nc,nkc->nk", z_hat, z_neg) logits = torch.cat([pos_logits, neg_logits], dim=1) / self.temperature targets = torch.zeros(n_queries, dtype=torch.long, device=logits.device) step_loss = F.cross_entropy(logits, targets) total_loss = step_loss if total_loss is None else total_loss + step_loss used_steps += 1 if used_steps == 0: raise RuntimeError( "CPCCriterion has no valid prediction steps: encoded sequence length is too short " f"(seq_len={seq_len}) for n_predictions={self.n_predictions}. " "Use fewer downsampling conv layers, smaller strides, or lower n_predictions." ) if total_loss is None: raise RuntimeError( "CPCCriterion failed to compute loss: total_loss is None after processing all prediction steps. " ) return total_loss / used_steps ``` Model ``` class OptimizerConfig(BaseModel): """Optimizer hyperparameters.""" learning_rate: float = 2e-4 weight_decay: float = 1e-6 class TrainerConfig(BaseModel): """Trainer runtime options, including epoch count and output path.""" epochs: int = 100 output_dir: str = "lightning_logs/ts_cpc" class RuntimeConfig(BaseModel): """Execution environment settings such as seed and device.""" seed: int = 0 accelerator: Literal["auto", "cpu", "gpu", "mps"] = "auto" devices: int = 1 class TrainConfig(BaseModel): """Top-level configuration object for CPC training.""" encoder: EncoderConfig = Field(default_factory=EncoderConfig) ar: ARConfig = Field(default_factory=ARConfig) loss: LossConfig = Field(default_factory=LossConfig) optimizer: OptimizerConfig = Field(default_factory=OptimizerConfig) trainer: TrainerConfig = Field(default_factory=TrainerConfig) runtime: RuntimeConfig = Field(default_factory=RuntimeConfig) @classmethod def from_yaml(cls, path: Path) -> "TrainConfig": """Load a training configuration from YAML. :param path: Path to a YAML file containing any subset of ``TrainConfig`` fields. :returns: Parsed configuration with defaults applied to omitted fields. """ with open(path) as f: data = yaml.safe_load(f) return cls(**(data or {})) ``` ``` class CPCLightningModule(L.LightningModule): """Lightning wrapper around CPC model and criterion. This module handles model construction, train/validation steps, and optimizer configuration. """ def __init__(self, config: TrainConfig, input_channels: int): """Initialize the Lightning module. :param config: Hierarchical training configuration. :param input_channels: Number of input channels in each sample ``x`` where ``x`` has shape ``[B, C_in, T]``. """ super().__init__() self.config = config self.save_hyperparameters(config.model_dump()) encoder = CPCEncoder( input_channels=input_channels, size_hidden=config.encoder.hidden_size, # norm_mode=config.encoder.norm_mode, conv_specs=[ (l.kernel_size, l.stride, l.padding) for l in config.encoder.conv_layers ], ) ar = CPCAR( dim_encoded=config.encoder.hidden_size, dim_output=config.ar.hidden_size, n_levels_gru=config.ar.n_levels, rnn_type=config.ar.mode, reverse=config.ar.reverse, ) self.model = CPCModel(encoder, ar) self.criterion = CPCCriterion( dim_context=ar.output_dimension, dim_encoded=encoder.output_dimension, n_predictions=config.loss.n_predictions, n_negatives=config.loss.negative_sampling_ext, temperature=config.loss.temperature, ) def _shared_step(self, batch, split: str): """Run one shared forward/loss step for train or validation. :param batch: Tuple ``(x, y)`` where ``x`` has shape ``[B, C_in, T]`` and ``y`` is the label tensor. :param split: Metric prefix, typically ``"train"`` or ``"val"``. :returns: Scalar CPC loss. """ batch_x, _ = batch batch_x = batch_x.permute(0, 2, 1).float() context, encoded = self.model(batch_x) loss = self.criterion(context, encoded) self.log( f"{split}_loss", loss, on_step=False, on_epoch=True, prog_bar=True, batch_size=batch_x.size(0), ) return loss def training_step(self, batch, batch_idx): """Run one training step. :param batch: Mini-batch tuple ``(x, y)``. :param batch_idx: Batch index within the epoch. :returns: Scalar training loss. """ return self._shared_step(batch, "train") def validation_step(self, batch, batch_idx): """Run one validation step. :param batch: Mini-batch tuple ``(x, y)``. :param batch_idx: Batch index within the validation epoch. """ self._shared_step(batch, "val") def predict_step( self, data, batch_idx: int = 0 ) -> tuple[torch.Tensor, torch.Tensor]: """Run one prediction step. :param data: Mini-batch tuple ``(x, y)``. :param batch_idx: Batch index within the prediction epoch. :returns: Tuple of context and encoded tensors. """ x = data.permute(0, 2, 1).float() context, encoded = self.model(x) return context, encoded def configure_optimizers(self): """Create optimizer for model and criterion parameters. :returns: Adam optimizer configured from ``config.optimizer``. """ return torch.optim.Adam( list(self.model.parameters()) + list(self.criterion.parameters()), lr=self.config.optimizer.learning_rate, weight_decay=self.config.optimizer.weight_decay, ) ``` ``` # config = TrainConfig.from_yaml( # Path("configs/predictive_coding/config.ecg200.yaml") # ) # config = TrainConfig.from_yaml( # Path("configs/predictive_coding/config.ecg5000.yaml") # ) # config = TrainConfig.from_yaml( # Path("configs/predictive_coding/config.forda.yaml") # ) config = TrainConfig.from_yaml(Path("configs/predictive_coding/config.synth.yaml")) ``` ``` config.model_dump() ``` ``` {'encoder': {'hidden_size': 50, 'norm_mode': 'layerNorm', 'conv_layers': [{'kernel_size': 10, 'stride': 5, 'padding': 3}, {'kernel_size': 8, 'stride': 4, 'padding': 2}, {'kernel_size': 3, 'stride': 1, 'padding': 1}]}, 'ar': {'mode': 'GRU', 'hidden_size': 150, 'n_levels': 1, 'reverse': True}, 'loss': {'n_predictions': 2, 'negative_sampling_ext': 64, 'temperature': 0.07}, 'optimizer': {'learning_rate': 0.0002, 'weight_decay': 1e-06}, 'trainer': {'epochs': 400, 'output_dir': 'lightning_logs/synth_cpc'}, 'runtime': {'seed': 137, 'accelerator': 'auto', 'devices': 1}} ``` ``` history_length_1_step = 100 horizon_1_step = 1 pdm_1_step = DataFrameDataModule( history_length=history_length_1_step, horizon=horizon_1_step, dataframe=df[["y"]], ) ``` ``` for i in pdm_1_step.train_dataloader(): print(i[0].shape, i[1].shape) break ``` ``` torch.Size([32, 100, 1]) torch.Size([32, 1, 1]) ``` ``` L.seed_everything(config.runtime.seed, workers=True) os.makedirs(config.trainer.output_dir, exist_ok=True) lightning_module = CPCLightningModule(config=config, input_channels=1) trainer = L.Trainer( max_epochs=config.trainer.epochs, accelerator=config.runtime.accelerator, devices=config.runtime.devices, default_root_dir=config.trainer.output_dir, log_every_n_steps=5, precision="32-true", # Enforce float32 for MPS compatibility ) trainer.fit(lightning_module, datamodule=pdm_1_step) ``` > [!NOTE] > > **Output (18 lines)** > > ``` > Seed set to 137 > GPU available: True (mps), used: True > TPU available: False, using: 0 TPU cores > IPU available: False, using: 0 IPUs > HPU available: False, using: 0 HPUs > Missing logger folder: lightning_logs/synth_cpc/lightning_logs > | Name | Type | Params > ------------------------------------------- > 0 | model | CPCModel | 119 K > 1 | criterion | CPCCriterion | 15.0 K > ------------------------------------------- > 134 K Trainable params > 0 Non-trainable params > 134 K Total params > 0.536 Total estimated model params size (MB) > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'val_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'train_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > `Trainer.fit` stopped: `max_epochs=400` reached. > ``` ## Load Artifacts and Interpret ``` import pandas as pd import plotly.express as px import torch from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler ``` ### Visualize One Batch ``` for i in pdm_1_step.train_dataloader(): pred_data, pred_label = i break ``` ``` pred_data.shape, pred_label.shape ``` ``` (torch.Size([32, 100, 1]), torch.Size([32, 1, 1])) ``` ``` data_pca2 = PCA( n_components=2, ).fit_transform(pred_data.detach().numpy()[:, :, 0]) df_data_pca = pd.DataFrame(data_pca2, columns=["pc_1", "pc_2"]) df_data_pca["label"] = pred_label[:, 0, 0].numpy() df_data_pca.head() ``` | | pc\_1 | pc\_2 | label | | --- | --- | --- | --- | | 0 | 5.201829 | 1.431045 | 0.597760 | | 1 | \-3.394166 | 6.187806 | \-0.768255 | | 2 | \-4.203279 | 5.955332 | \-0.837627 | | 3 | 5.352355 | \-1.870396 | 0.901788 | | 4 | 4.818609 | 2.401448 | 0.470856 | ``` px.scatter( df_data_pca, x="pc_1", y="pc_2", color="label", title="PCA of CPC Input Data", width=800, height=600, color_continuous_scale="Viridis", ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` pred_context, pred_encoded = trainer.model.predict_step(pred_data) ``` ``` pred_context.shape, pred_encoded.shape ``` ``` (torch.Size([32, 5, 150]), torch.Size([32, 5, 50])) ``` ``` from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression from sklearn.manifold import TSNE from sklearn.metrics import silhouette_score from sklearn.model_selection import StratifiedKFold, cross_val_score ``` ``` context_pca2 = PCA( n_components=2, ).fit_transform(pred_context.detach().numpy()[:, 0, :]) df_context = pd.DataFrame(context_pca2, columns=["pc_1", "pc_2"]) df_context["label"] = pred_label[:, 0, 0].numpy() df_context.head() ``` | | pc\_1 | pc\_2 | label | | --- | --- | --- | --- | | 0 | 0.025133 | \-0.060999 | 0.597760 | | 1 | 0.035210 | \-0.030642 | \-0.768255 | | 2 | 0.048349 | \-0.046286 | \-0.837627 | | 3 | 0.086876 | 0.022421 | 0.901788 | | 4 | \-0.000341 | \-0.067931 | 0.470856 | ``` px.scatter( df_context, x="pc_1", y="pc_2", color="label", title="PCA of CPC Context Representations", width=800, height=600, color_continuous_scale="Viridis", ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` context_tsne2d = TSNE( n_components=2, perplexity=20, random_state=0, # init="pca" ).fit_transform( # PCA( # n_components=10, # ).fit_transform( # pred_context.detach().numpy()[:,0,:] # ) pred_context.detach().numpy()[:, 0, :] ) df_context_tsne = pd.DataFrame(context_tsne2d, columns=["tsne_1", "tsne_2"]) df_context_tsne["label"] = pred_label[:, 0, 0].numpy() df_context_tsne.head() ``` | | tsne\_1 | tsne\_2 | label | | --- | --- | --- | --- | | 0 | \-2.684160 | 3.486857 | 0.597760 | | 1 | \-0.698601 | 4.410301 | \-0.768255 | | 2 | \-0.671289 | 4.125423 | \-0.837627 | | 3 | \-2.622754 | 5.568111 | 0.901788 | | 4 | \-2.853034 | 2.592888 | 0.470856 | ``` px.scatter( df_context_tsne, x="tsne_1", y="tsne_2", color="label", title="t-SNE of CPC Context Representations", width=800, height=600, color_continuous_scale="Viridis", ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` encoded_pca2 = PCA( n_components=2, ).fit_transform(pred_encoded.detach().numpy()[:, 0, :]) df_encoded_pca = pd.DataFrame(encoded_pca2, columns=["pc_1", "pc_2"]) df_encoded_pca["label"] = pred_label[:, 0, 0].numpy() df_encoded_pca.head() ``` | | pc\_1 | pc\_2 | label | | --- | --- | --- | --- | | 0 | \-0.200375 | \-0.046381 | 0.597760 | | 1 | 0.223663 | 0.000218 | \-0.768255 | | 2 | 0.286055 | \-0.021745 | \-0.837627 | | 3 | \-0.056581 | \-0.267233 | 0.901788 | | 4 | \-0.207132 | 0.013016 | 0.470856 | ``` px.scatter( df_encoded_pca, x="pc_1", y="pc_2", color="label", title="PCA of CPC Encoded Representations", width=800, height=600, color_continuous_scale="Viridis", ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` encoded_tsne2d = TSNE( n_components=2, perplexity=20, random_state=0, # init="pca" ).fit_transform( # PCA( # n_components=10, # ).fit_transform( # pred_encoded.detach().numpy()[:,0,:] # ) pred_encoded.detach().numpy()[:, 0, :] ) df_encoded_tsne = pd.DataFrame(encoded_tsne2d, columns=["tsne_1", "tsne_2"]) df_encoded_tsne["label"] = pred_label[:, 0, 0].numpy() df_encoded_tsne.head() ``` | | tsne\_1 | tsne\_2 | label | | --- | --- | --- | --- | | 0 | \-4.308352 | \-9.063933 | 0.597760 | | 1 | \-3.098964 | \-5.126304 | \-0.768255 | | 2 | \-2.944472 | \-4.954911 | \-0.837627 | | 3 | \-2.641252 | \-8.971721 | 0.901788 | | 4 | \-4.883827 | \-9.032061 | 0.470856 | ``` px.scatter( df_encoded_tsne, x="tsne_1", y="tsne_2", color="label", title="t-SNE of CPC Encoded Representations", width=800, height=600, color_continuous_scale="Viridis", ) ``` *Interactive Plotly figure: enable JavaScript to view it.* ### Visualizez All ``` import pandas as pd import plotly.express as px import plotly.graph_objects as go from sklearn.decomposition import PCA ``` ``` # Faceted comparison: raw vs context vs encoded for the same reduction method # Produces two figures: # 1) PCA with facet rows (raw/context/encoded) # 2) t-SNE with facet rows (raw/context/encoded) # Rebuild tensors if they are not already in memory module = trainer.model if hasattr(trainer, "model") else lightning_module module.eval() device = module.device all_raw, all_context, all_encoded, all_labels = [], [], [], [] with torch.no_grad(): for x, y_batch in pdm_1_step.train_dataloader(): x = x.permute(0, 2, 1).float().to(device) context, encoded = module.model(x) all_raw.append(x.cpu()) all_context.append(context.cpu()) all_encoded.append(encoded.cpu()) all_labels.append(y_batch[:, 0, 0].cpu()) raw_all = torch.cat(all_raw, dim=0) # [N, C_in, T] context_all = torch.cat(all_context, dim=0) # [N, T_enc, C] encoded_all = torch.cat(all_encoded, dim=0) # [N, T_enc, C] y = torch.cat(all_labels, dim=0).numpy().astype(np.float32) # Choose one view per family for fair visual comparison Z_by_family = { "raw": raw_all.reshape(raw_all.shape[0], -1).numpy(), # flatten_all_channels "context": context_all.reshape(context_all.shape[0], -1).numpy(), # flatten_tokens # "encoded": encoded_all.reshape(encoded_all.shape[0], -1).numpy(),# flatten_tokens "encoded": encoded_all[:, 1, :] .reshape(encoded_all.shape[0], -1) .numpy(), # flatten_tokens } family_order = ["raw", "context", "encoded"] def reduce_family(Z, method="pca", random_state=0): if method == "pca": return make_pipeline( StandardScaler(), PCA(n_components=2, random_state=random_state), ).fit_transform(Z) if method == "tsne": n = Z.shape[0] perp = max(5, min(30, (n - 1) // 3)) return TSNE( n_components=2, perplexity=perp, random_state=random_state, init="pca", ).fit_transform(Z) raise ValueError(f"Unknown method: {method}") def build_facet_df(method): rows = [] for fam in family_order: Z2 = reduce_family(Z_by_family[fam], method=method, random_state=0) df_f = pd.DataFrame( { "dim1": Z2[:, 0], "dim2": Z2[:, 1], "label": y, "family": fam, } ) rows.append(df_f) return pd.concat(rows, ignore_index=True) def plot_facet(dataframe, method, width=700, height=1100): df_plot = dataframe.copy() title = f"{method.upper()} comparison by family (facet rows)" fig = px.scatter( df_plot, x="dim1", y="dim2", color="label", facet_row="family", category_orders={"family": family_order}, title=title, width=width, height=height, color_continuous_scale="Viridis", opacity=0.8, ) fig.update_traces(marker=dict(size=5)) fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1])) fig.update_layout(legend_title_text="label") fig.update_xaxes(matches=None) fig.update_yaxes(matches=None) fig.show() # Show both methods with the same faceting layout df_plot_pca = build_facet_df("pca") plot_facet(df_plot_pca, "pca") df_plot_tsne = build_facet_df("tsne") plot_facet(df_plot_tsne, "tsne") ``` *Interactive Plotly figure: enable JavaScript to view it.* *Interactive Plotly figure: enable JavaScript to view it.* ``` df_dr = pd.merge( df_plot_pca[["dim1", "dim2"]], df_plot_tsne, how="left", left_index=True, right_index=True, suffixes=("_pca", "_tsne"), ) df_dr ``` | | dim1\_pca | dim2\_pca | dim1\_tsne | dim2\_tsne | label | family | | --- | --- | --- | --- | --- | --- | --- | | 0 | \-0.391278 | \-9.804413 | 0.906583 | \-8.634899 | \-0.688411 | raw | | 1 | 7.910292 | \-6.226569 | 6.979243 | \-4.296796 | 0.156869 | raw | | 2 | 4.731640 | \-8.678458 | 5.010166 | \-6.831739 | \-0.240112 | raw | | 3 | \-9.522593 | \-3.778818 | \-7.466325 | \-4.326780 | \-0.943107 | raw | | 4 | \-8.051244 | 5.885795 | \-7.798515 | 4.101046 | \-0.181289 | raw | | ... | ... | ... | ... | ... | ... | ... | | 673 | 2.833340 | \-1.643466 | 7.519459 | 0.465748 | \-0.507897 | encoded | | 674 | 1.436681 | \-2.061466 | 4.620607 | 3.791852 | \-0.782775 | encoded | | 675 | 2.800535 | \-1.713862 | 6.913970 | 0.327560 | \-0.521551 | encoded | | 676 | 0.356620 | 1.482852 | \-6.779316 | 10.432781 | \-0.837627 | encoded | | 677 | \-1.838117 | 3.406347 | 15.547230 | \-9.297036 | 0.450441 | encoded | 678 rows × 6 columns ``` import numpy as np import pandas as pd # Expect df_dr columns from your merge: # dim1_pca, dim2_pca, dim1_tsne, dim2_tsne, label, family required = {"dim1_pca", "dim2_pca", "label", "family"} missing = required - set(df_dr.columns) if missing: raise ValueError(f"df_dr is missing required columns: {missing}") # Keep only families needed for this vector df_tmp = df_dr[df_dr["family"].isin(["raw", "encoded"])].copy() # Create per-sample index inside each family block so raw and encoded can be paired df_tmp["idx"] = df_tmp.groupby("family").cumcount() # Split and rename PCA columns raw_df = ( df_tmp[df_tmp["family"] == "raw"][["idx", "label", "dim1_pca", "dim2_pca"]] .rename(columns={"dim1_pca": "raw_x", "dim2_pca": "raw_y"}) .reset_index(drop=True) ) enc_df = ( df_tmp[df_tmp["family"] == "encoded"][["idx", "label", "dim1_pca", "dim2_pca"]] .rename(columns={"dim1_pca": "enc_x", "dim2_pca": "enc_y", "label": "label_enc"}) .reset_index(drop=True) ) # Pair raw and encoded rows by idx (and optionally validate labels) df_vec = raw_df.merge(enc_df, on="idx", how="inner") # Optional sanity check: label consistency if not (df_vec["label"] == df_vec["label_enc"]).all(): print("Warning: label mismatch found between raw and encoded pairing.") df_vec = df_vec.drop(columns=["label_enc"]) # Vector components and norm df_vec["vec_x"] = df_vec["enc_x"] - df_vec["raw_x"] df_vec["vec_y"] = df_vec["enc_y"] - df_vec["raw_y"] df_vec["vec_norm"] = np.linalg.norm(df_vec[["vec_x", "vec_y"]].to_numpy(), axis=1) df_vec.head() ``` | | idx | label | raw\_x | raw\_y | enc\_x | enc\_y | vec\_x | vec\_y | vec\_norm | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 0 | 0 | \-0.688411 | \-0.391278 | \-9.804413 | \-1.470029 | 0.647036 | \-1.078751 | 10.451448 | 10.506972 | | 1 | 1 | 0.156869 | 7.910292 | \-6.226569 | \-0.476231 | \-1.490762 | \-8.386523 | 4.735807 | 9.631285 | | 2 | 2 | \-0.240112 | 4.731640 | \-8.678458 | \-2.621885 | \-2.795312 | \-7.353525 | 5.883146 | 9.417311 | | 3 | 3 | \-0.943107 | \-9.522593 | \-3.778818 | 2.352323 | \-1.258931 | 11.874916 | 2.519887 | 12.139336 | | 4 | 4 | \-0.181289 | \-8.051244 | 5.885795 | 2.912867 | 2.103062 | 10.964111 | \-3.782732 | 11.598310 | ``` label_values = df_vec["label"].astype(np.float32).to_numpy() raw_color = "rgba(31, 119, 180, 0.2)" # blue-ish connector tint line_x = np.column_stack( [df_vec["raw_x"], df_vec["enc_x"], np.full(len(df_vec), np.nan)] ).ravel() line_y = np.column_stack( [df_vec["raw_y"], df_vec["enc_y"], np.full(len(df_vec), np.nan)] ).ravel() fig = go.Figure() fig.add_trace( go.Scatter( x=line_x, y=line_y, mode="lines", line=dict(color=raw_color, width=1), hoverinfo="skip", showlegend=False, ) ) fig.add_trace( go.Scatter( x=df_vec["raw_x"], y=df_vec["raw_y"], mode="markers", marker=dict( size=8, symbol="circle", color=label_values, coloraxis="coloraxis", line=dict(width=1, color="white"), ), name="raw", text=[ f"idx={r}, label={lbl:.4f}" for r, lbl in zip(df_vec["idx"], label_values) ], hovertemplate="RAW
%{text}
x=%{x:.3f}, y=%{y:.3f}", ) ) fig.add_trace( go.Scatter( x=df_vec["enc_x"], y=df_vec["enc_y"], mode="markers", marker=dict( size=8, symbol="diamond", color=label_values, coloraxis="coloraxis", line=dict(width=1, color="white"), ), name="encoded", text=[ f"idx={r}, label={lbl:.4f}, norm={n:.3f}" for r, lbl, n in zip(df_vec["idx"], label_values, df_vec["vec_norm"]) ], hovertemplate="ENCODED
%{text}
x=%{x:.3f}, y=%{y:.3f}", ) ) fig.update_layout( title=f"Per-index vectors — marker color: continuous label, shape: raw/encoded (N={len(df_vec)})", xaxis_title="PC1 (raw space) / PC1 (encoded space)", yaxis_title="PC2", width=980, height=720, coloraxis=dict(colorscale="Viridis", colorbar=dict(title="label")), ) fig.show() ``` *Interactive Plotly figure: enable JavaScript to view it.* ``` # Derive vec_x / vec_y from whichever df_vec is in scope vec_x = (df_vec["enc_x"] - df_vec["raw_x"]).values vec_y = (df_vec["enc_y"] - df_vec["raw_y"]).values V = np.stack([vec_x, vec_y], axis=1) # [N, 2] labels = df_vec["label"].values # 1) Mean displacement and residuals v_mean = V.mean(axis=0) residuals = V - v_mean residual_norms = np.linalg.norm(residuals, axis=1) vector_norms = np.linalg.norm(V, axis=1) explained_by_mean = 1 - (residual_norms / (vector_norms + 1e-9)) print(f"Mean displacement vector: ({v_mean[0]:.3f}, {v_mean[1]:.3f})") print(f"Mean |v|: {vector_norms.mean():.3f} ± {vector_norms.std():.3f}") print(f"Mean |residual|: {residual_norms.mean():.3f} ± {residual_norms.std():.3f}") print(f"Fraction explained by global shift: {explained_by_mean.mean():.3f}") # 2) Angle relative to mean direction v_mean_unit = v_mean / (np.linalg.norm(v_mean) + 1e-9) cos_sim = np.clip(V @ v_mean_unit / (vector_norms + 1e-9), -1, 1) angles_deg = np.degrees(np.arccos(cos_sim)) # 3) PCA of displacement vectors pca_v = PCA(n_components=2).fit(V) print( f"\nPCA of displacement vectors — variance explained: {pca_v.explained_variance_ratio_}" ) df_angle = pd.DataFrame( { "angle_deg": angles_deg, "residual_norm": residual_norms, "vec_norm": vector_norms, "label": labels, } ) fig = px.histogram( df_angle, x="angle_deg", color="label", nbins=30, barmode="overlay", opacity=0.7, title="Distribution of displacement angle relative to mean vector (degrees)
" "Near 0° = moves with the crowd; large angle = outlier movement", labels={"angle_deg": "Angle to mean displacement (°)"}, width=850, height=450, ) fig.show() fig2 = px.scatter( df_angle, x="vec_norm", y="residual_norm", color="label", title="Vector norm vs residual norm after removing global shift
" "Near x-axis = moved with global trend; high residual = distinctive movement", labels={"vec_norm": "|v|", "residual_norm": "|v - v̄|"}, width=800, height=500, opacity=0.8, ) fig2.add_hline(y=0, line_dash="dot", line_color="gray") fig2.show() ``` ``` Mean displacement vector: (-0.000, 0.000) Mean |v|: 10.584 ± 1.882 Mean |residual|: 10.584 ± 1.882 Fraction explained by global shift: 0.000 PCA of displacement vectors — variance explained: [0.65481544 0.34518456] ``` *Interactive Plotly figure: enable JavaScript to view it.* *Interactive Plotly figure: enable JavaScript to view it.* ## Downstream Tasks ``` import lightning as L ``` ``` import numpy as np import pandas as pd import torch import torch.nn as nn from lightning.pytorch.callbacks import EarlyStopping from sklearn.metrics import accuracy_score, f1_score from sklearn.model_selection import RepeatedStratifiedKFold from sklearn.preprocessing import StandardScaler from torch.utils.data import DataLoader, TensorDataset class MLPCForecaster(L.LightningModule): def __init__( self, input_dim: int, forecast_steps: int, hidden_dim: int = 128, dropout: float = 0.2, lr: float = 1e-3, pre_trained_model: nn.Module | None = None, ): super().__init__() self.save_hyperparameters(ignore=["pre_trained_model"]) if pre_trained_model is not None: self.pre_net = pre_trained_model else: self.pre_net = nn.Identity() self.net = nn.Sequential( nn.Linear(input_dim, hidden_dim), nn.ReLU(), nn.Dropout(dropout), nn.Linear(hidden_dim, hidden_dim // 2), nn.ReLU(), nn.Dropout(dropout), nn.Linear(hidden_dim // 2, forecast_steps), ) self.loss = nn.MSELoss() def forward(self, x): x = self.pre_net(x) return self.net(x) def training_step(self, batch, batch_idx): x, y = batch forecast = self(x.permute(0, 2, 1)) loss = self.loss(forecast, y.squeeze()) self.log("train_loss", loss, prog_bar=False, on_epoch=True, on_step=False) return loss def validation_step(self, batch, batch_idx): x, y = batch forecast = self(x.permute(0, 2, 1)) loss = self.loss(forecast, y.squeeze()) self.log("val_loss", loss, prog_bar=False, on_epoch=True, on_step=False) return loss def predict_step(self, batch, batch_idx, dataloader_idx=0): x, _ = batch return self(x.permute(0, 2, 1)) def configure_optimizers(self): return torch.optim.AdamW( self.parameters(), lr=self.hparams.lr, ) model = MLPCForecaster( input_dim=history_length_1_step, forecast_steps=horizon_1_step, hidden_dim=64, dropout=0.2, lr=1e-3, ) forecaster_trainer_naive = L.Trainer( max_epochs=100, accelerator="auto", devices=1, logger=False, enable_checkpointing=False, enable_progress_bar=False, deterministic=True, callbacks=[EarlyStopping(monitor="val_loss", mode="min", patience=8)], ) forecaster_trainer_naive.fit(model, datamodule=pdm_1_step) pred_batches = forecaster_trainer_naive.predict(model, datamodule=pdm_1_step) y_pred = torch.cat(pred_batches, dim=0) ``` > [!NOTE] > > **Output (23 lines)** > > ``` > GPU available: True (mps), used: True > TPU available: False, using: 0 TPU cores > IPU available: False, using: 0 IPUs > HPU available: False, using: 0 HPUs > | Name | Type | Params > --------------------------------------- > 0 | pre_net | Identity | 0 > 1 | net | Sequential | 8.6 K > 2 | loss | MSELoss | 0 > --------------------------------------- > 8.6 K Trainable params > 0 Non-trainable params > 8.6 K Total params > 0.034 Total estimated model params size (MB) > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'val_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/torch/nn/modules/loss.py:608: UserWarning: > Using a target size (torch.Size([25])) that is different to the input size (torch.Size([25, 1, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'train_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/torch/nn/modules/loss.py:608: UserWarning: > Using a target size (torch.Size([32])) that is different to the input size (torch.Size([32, 1, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/torch/nn/modules/loss.py:608: UserWarning: > Using a target size (torch.Size([2])) that is different to the input size (torch.Size([2, 1, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size. > /Users/leima/git/github/emptymalei/deep-learning/.venv/lib/python3.10/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:441: The 'predict_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=9` in the `DataLoader` to improve performance. > ``` # RNN Dynamics During Inference We have the intuition that RNN inference is similar to a first order differential equation. Here we explore and echo on this idea using numerical simulations. ``` from functools import cached_property ``` ``` import matplotlib.pyplot as plt import numpy as np import numpy.typing as npt import pandas as pd import seaborn as sns ``` ## RNN ``` class RNNState: """ Describes a RNN state and computes the history of the states based on inputs. :param w_h: $W_h$, the weight for $h$ :param w_i: $W_i$, the weight for $x$ :param b: $b$, the bias before applying activation :param h_init: the initial hidden state :param activation: the activation function to be applied. """ def __init__( self, w_h: npt.ArrayLike, w_i: npt.ArrayLike, b: npt.ArrayLike, h_init: npt.ArrayLike, activation: callable = np.tanh, ): self.w_h = np.array(w_h) self.w_i = np.array(w_i) self.b = np.array(b) self.h_init = np.array(h_init) self.activation = activation def compute_new_state( self, h_current: npt.ArrayLike, z_i: npt.ArrayLike ) -> tuple[npt.ArrayLike, npt.ArrayLike]: """ compute_new_state computes a new state :param h_current: the current hidden state :param z_i: external input :return: the new hidden state, and the difference between new and old """ h_new = self.activation( np.dot(self.w_h, h_current) + np.dot(self.w_i, z_i) + self.b ) h_delta = h_new - h_current return h_new, h_delta @cached_property def _metadata(self) -> dict: return { "experiment": ( f"w_h={np.array2string(self.w_h)};w_i={np.array2string(self.w_i)};" f"b={np.array2string(self.b)};h_init={np.array2string(self.h_init)};{self.activation.__name__}" ), "w_h": np.array2string(self.w_h), "w_i": np.array2string(self.w_i), "b": np.array2string(self.b), "activation": self.activation.__name__, "initial_state": np.array2string(self.h_init), } def states(self, z: npt.ArrayLike) -> dict[str : npt.ArrayLike]: """ states calculates the history of RNN states. We designed function to be easily readable by computing the values step by step. :param z: input values for the RNN :return: history of the RNN hidden states """ h_t = [self.h_init] t_steps = [0] h_t_delta = [np.zeros_like(self.h_init)] for t, z_i in enumerate(z): h_new, h_delta = self.compute_new_state(h_current=h_t[-1], z_i=z_i) h_t.append(h_new) h_t_delta.append(h_delta) t_steps.append(t + 1) total_time_steps = len(t_steps) return { **{ "t": np.array(t_steps), "h": np.array(h_t), "dh": np.array(h_t_delta), "z": np.pad(z, (1, 0), constant_values=0), }, **{k: [v] * total_time_steps for k, v in self._metadata.items()}, } ``` ``` def rnn_inference(rnn_params: list[dict], z: npt.ArrayLike) -> pd.DataFrame: """ Run through a list of parameters and return the states :param rnn_params: list of RNN parameters :param z: input time series values """ df_experiments = pd.DataFrame() for p in rnn_params: df_experiments = pd.concat( [df_experiments, pd.DataFrame(RNNState(**p).states(z=z))] ) return df_experiments def rnn_inference_1d_visual(dataframe_experiment: pd.DataFrame, title: str) -> None: """ Visualize RNN inference experiments :param dataframe_experiment: dataframe from the inference experiment :param title: title of the figure """ z = dataframe_experiment.loc[ dataframe_experiment.experiment == dataframe_experiment.experiment.iloc[0] ].z _, ax = plt.subplots(figsize=(10, 6.18)) sns.lineplot( dataframe_experiment, x="t", y="h", hue="w_h", size="initial_state", linestyle="dashed", ax=ax, ) ax_right = ax.twinx() sns.lineplot( x=np.arange(1, len(z) + 1), y=z, linestyle="dashed", color="gray", label=r"Input: $z$", ax=ax_right, ) ax_right.set_ylabel(r"$z$") ax.legend(loc=1) ax.set_title(title) ax.legend(loc=4) ``` ## One Dimensional State ``` z_1 = np.linspace(0, 10, 101) # z_1 = z_1 = np.random.rand(20) # z_1 = np.sin(np.linspace(0, 10, 51)) ``` ``` experiment_params = [ {"w_h": 0.5, "w_i": 1, "b": 0, "h_init": 0.1}, {"w_h": 1.5, "w_i": 1, "b": 0, "h_init": 0.1}, {"w_h": 0.5, "w_i": 1, "b": 0, "h_init": 2}, {"w_h": 1.5, "w_i": 1, "b": 0, "h_init": 2}, ] ``` ``` rnn_inference_1d_visual( dataframe_experiment=rnn_inference( rnn_params=experiment_params, z=np.ones(10) * 0.5 ), title="RNN Inference for Long Forecast Horizon (Constant Input)", ) ``` ``` rnn_inference_1d_visual( dataframe_experiment=rnn_inference( rnn_params=experiment_params, z=np.linspace(0, 10, 101) ), title="RNN Inference for Long Forecast Horizon (Linear Input)", ) ``` ``` rnn_inference_1d_visual( dataframe_experiment=rnn_inference( rnn_params=experiment_params, z=np.random.rand(20) ), title="RNN Inference for Long Forecast Horizon (Random Input)", ) ``` ``` rnn_inference_1d_visual( dataframe_experiment=rnn_inference( rnn_params=experiment_params, z=np.sin(np.linspace(0, 10, 51)) ), title="RNN Inference for Long Forecast Horizon (Sin Input)", ) ``` ### Two dimensional state ``` # z_2 = np.random.rand(100, 2) * 0.1 # z_2 = np.ones((100, 2)) # z_2 = np.zeros((1000, 2)) z_2 = ( np.random.rand(100, 2) * 0.1 + np.stack([np.zeros(100), np.linspace(0, 99, 100)]).T ) ``` ``` experiment_2d_params = [ { "w_h": np.array([[0.5, 0.5], [0.5, 0.5]]), "w_i": np.array([[0.5, 0.5], [0.5, 0.5]]), "b": np.array([0, 0]), "h_init": np.array([0.5, 0.5]), }, { "w_h": np.array([[1.5, 0.5], [0.5, 1.5]]), "w_i": np.array([[1.5, 0.5], [0.5, 1.5]]), "b": np.array([0, 0]), "h_init": np.array([0.5, 0.5]), }, ] experiments_2d = [] for p in experiment_2d_params: experiments_2d.append(RNNState(**p).states(z=z_2)) ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) experiments_2d_colors = sns.color_palette("husl", len(experiments_2d)) for idx, i in enumerate(experiments_2d): ax.plot( i["t"][2:], i["h"][2:, 1], marker=".", color=experiments_2d_colors[idx], label=i["experiment"][0], ) ax.plot( i["t"][2:], i["h"][2:, 0], marker="x", color=experiments_2d_colors[idx], label=i["experiment"][0], ) plt.legend() ``` # Comparing RNN Models for Time Series Forecasting In this notebook, we compare different RNN models for time series forecasting. ``` import dataclasses ``` ``` import lightning as L import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from lightning.pytorch.callbacks.early_stopping import EarlyStopping from torch import nn from ts_dl_utils.datasets.dataset import DataFrameDataModule from ts_dl_utils.evaluation.evaluator import Evaluator from ts_dl_utils.naive_forecasters.last_observation import LastObservationForecaster ``` ## Data We prepare a toy dataset using `sin` ``` df = pd.DataFrame( {"t": np.linspace(0, 100, 501), "y": np.sin(np.linspace(0, 100, 501))} ) ``` ``` df.head() ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) df.plot(x="t", y="y", ax=ax) ``` ## Model In this section, we create the RNN model. ``` @dataclasses.dataclass class TSRNNParams: """A dataclass to be served as our parameters for the model. :param hidden_size: number of dimensions in the hidden state :param input_size: input dim :param num_layers: number of units stacked """ hidden_size: int input_size: int = 1 num_layers: int = 1 class TSRNN(nn.Module): """RNN for univaraite time series modeling. :param history_length: the length of the input history. :param horizon: the number of steps to be forecasted. :param rnn_params: the parameters for the RNN network. """ def __init__(self, history_length: int, horizon: int, rnn_params: TSRNNParams): super().__init__() self.rnn_params = rnn_params self.history_length = history_length self.horizon = horizon self.rnn = nn.RNN( input_size=self.rnn_params.input_size, hidden_size=self.rnn_params.hidden_size, num_layers=self.rnn_params.num_layers, batch_first=True, ) self.regulate_output = nn.Linear(self.rnn_params.hidden_size, self.horizon) @property def rnn_config(self): return dataclasses.asdict(self.rnn_params) def forward(self, x: torch.Tensor) -> torch.Tensor: # x = self.regulate_input(x) x, _ = self.rnn(x) return self.regulate_output(x) ``` ## Training We use [lightning]() to train our model. ### Training Utilities ``` history_length_1_step = 100 horizon_1_step = 1 ``` We will build a few utilities 1. To be able to feed the data into our model, we build a class (`DataFrameDataset`) that converts the pandas dataframe into a Dataset for pytorch. 2. To make the lightning training code simpler, we will build a [LightningDataModule]() (`DataFrameDataModule`) and a [LightningModule]() (`RNNForecaster`). ``` class RNNForecaster(L.LightningModule): def __init__(self, rnn: nn.Module): super().__init__() self.rnn = rnn def configure_optimizers(self): optimizer = torch.optim.SGD(self.parameters(), lr=1e-3) return optimizer def training_step(self, batch, batch_idx): x, y = batch x = x.squeeze().type(self.dtype) y = y.squeeze(-1).type(self.dtype) y_hat = self.rnn(x) loss = nn.functional.l1_loss(y_hat, y) self.log_dict({"train_loss": loss}, prog_bar=True) return loss def validation_step(self, batch, batch_idx): x, y = batch x = x.squeeze().type(self.dtype) y = y.squeeze(-1).type(self.dtype) y_hat = self.rnn(x) loss = nn.functional.l1_loss(y_hat, y) self.log_dict({"val_loss": loss}, prog_bar=True) return loss def predict_step(self, batch, batch_idx): x, y = batch x = x.squeeze().type(self.dtype) y = y.squeeze(-1).type(self.dtype) y_hat = self.rnn(x) return x, y_hat def forward(self, x): x = x.squeeze().type(self.dtype) return x, self.rnn(x) ``` ### Data, Model and Training #### DataModule ``` pdm_1_step = DataFrameDataModule( history_length=history_length_1_step, horizon=horizon_1_step, dataframe=df[["y"]], ) ``` #### LightningModule ``` ts_rnn_params_1_step = TSRNNParams(input_size=1, hidden_size=64, num_layers=1) ts_rnn_1_step = TSRNN( history_length=history_length_1_step, horizon=horizon_1_step, rnn_params=ts_rnn_params_1_step, ) ts_rnn_1_step ``` ``` rnn_forecaster_1_step = RNNForecaster(rnn=ts_rnn_1_step) ``` #### Trainer ``` logger_1_step = L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="rnn_ts_1_step" ) trainer_1_step = L.Trainer( precision="64", max_epochs=100, min_epochs=5, callbacks=[ EarlyStopping(monitor="val_loss", mode="min", min_delta=1e-7, patience=3) ], logger=logger_1_step, ) ``` #### Fitting ``` trainer_1_step.fit(model=rnn_forecaster_1_step, datamodule=pdm_1_step) ``` #### Retrieving Predictions ``` predictions_1_step = trainer_1_step.predict( model=rnn_forecaster_1_step, datamodule=pdm_1_step ) ``` ### Naive Forecaster ``` trainer_naive_1_step = L.Trainer(precision="64") lobs_forecaster_1_step = LastObservationForecaster(horizon=horizon_1_step) lobs_1_step_predictions = trainer_naive_1_step.predict( model=lobs_forecaster_1_step, datamodule=pdm_1_step ) ``` ### Evaluations ``` evaluator_1_step = Evaluator(step=0) ``` ``` fig, ax = plt.subplots(figsize=(10, 6.18)) ax.plot( evaluator_1_step.y_true(dataloader=pdm_1_step.predict_dataloader()), "g-", label="truth", ) ax.plot(evaluator_1_step.y(predictions_1_step), "r--", label="predictions") ax.plot(evaluator_1_step.y(lobs_1_step_predictions), "b-.", label="naive predictions") plt.legend() ``` ``` evaluator_1_step.metrics(predictions_1_step, pdm_1_step.predict_dataloader()) ``` ``` evaluator_1_step.metrics(lobs_1_step_predictions, pdm_1_step.predict_dataloader()) ``` ``` pd.merge( evaluator_1_step.metrics(predictions_1_step, pdm_1_step.predict_dataloader()), evaluator_1_step.metrics(lobs_1_step_predictions, pdm_1_step.predict_dataloader()), how="inner", left_index=True, right_index=True, suffixes=["_rnn", "_last_obs"], ) ``` ## Real Life We take the [Airpassenger dataset](). ``` df_ap = pd.read_csv( "https://raw.githubusercontent.com/DataHerb/dataset-airpassenger/main/dataset/AirPassengers.csv" ) ``` # TimeVAE Use VAE to generate time series data. In this example, we will train a VAE model to sinusoidal time series data. The overall structure of the model is shown below: ``` graph TD data["Time Series Chunks"] --> E[Encoder] E --> L[Latent Space] L --> D[Decoder] D --> gen["Generated Time Series Chunks"] ``` Reference: [https://github.com/wangyz1999/timeVAE-pytorch]() ``` import dataclasses ``` ``` from functools import cached_property from numbers import Number from typing import Dict, List, Tuple import lightning as L import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch from lightning.pytorch.callbacks.early_stopping import EarlyStopping from loguru import logger from torch import nn from torch.utils.data import DataLoader, Dataset ``` ## Data We will reuse our classic pendulum dataset. ``` class KioskVisitors: """generate number of visitors for a kiosk store :param daily_profile: expectations of visitors within a fixed time window during a day """ def __init__(self, daily_profile: np.ndarray): self.daily_profile = daily_profile self.daily_segments = len(daily_profile) def __call__( self, n_days: int, seed: Number = 42, ) -> pd.DataFrame: """generate number of visitors for n_days :param n_days: number of days to generate visitors """ rng = np.random.default_rng(seed) visitors = np.concatenate( [rng.poisson(self.daily_profile) for _ in range(n_days)] ) df = pd.DataFrame( { "visitors": visitors, "t": np.arange(len(visitors)), "expectation": np.tile(self.daily_profile, n_days), } ) return df ``` ``` def profile_sin( t: np.ndarray, lambda_min: float, lambda_max: float, ) -> np.ndarray: """generate a sin wave profile for the expected number of visitors within a few min for each hour during a day :param t: time in minutes :param lambda_min: minimum number of visitors :param lambda_max: maximum number of visitors """ amplitude = lambda_max - lambda_min t_rescaled = (t - t.min()) / t.max() * np.pi return amplitude * np.sin(t_rescaled) + lambda_min ``` ``` daily_profile = profile_sin(np.arange(0, 12 * 60 / 5, 1), lambda_min=9, lambda_max=10) kiosk_visitors = KioskVisitors(daily_profile=daily_profile) df_visitors = kiosk_visitors(n_days=30).melt( id_vars="t", value_vars=["visitors", "expectation"], var_name="data", value_name="count", ) df_visitors.head() _, ax = plt.subplots(figsize=(6, 6.18 * 0.6)) sns.lineplot( df_visitors, x="t", y="count", style="data", hue="data", ax=ax, ) ``` ``` df = df_visitors.loc[df_visitors["data"] == "visitors"][["t", "count"]] df["count"] = df["count"] + 2 ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) df.head(100).plot(x="t", y="count", ax=ax) ``` ``` _, ax = plt.subplots(figsize=(10, 6.18)) df.plot(x="t", y="count", ax=ax) ``` ``` df ``` ``` def time_delay_embed(df: pd.DataFrame, window_size: int) -> pd.DataFrame: """embed time series into a time delay embedding space Time column `t` is required in the input data frame. :param df: original time series data frame :param window_size: window size for the time delay embedding """ dfs_embedded = [] for i in df.rolling(window_size): i_t = i.t.iloc[0] dfs_embedded.append( pd.DataFrame(i.reset_index(drop=True)) .drop(columns=["t"]) .T.reset_index(drop=True) # .rename(columns={"index": "name"}) # .assign(t=i_t) ) df_embedded = pd.concat(dfs_embedded[window_size - 1 :]) return df_embedded ``` ``` time_delay_embed(df, 3) ``` ```` class TimeVAEDataset(Dataset): """A dataset from a pandas dataframe. For a given pandas dataframe, this generates a pytorch compatible dataset by sliding in time dimension. ```python ds = DataFrameDataset( dataframe=df, history_length=10, horizon=2 ) ``` :param dataframe: input dataframe with a DatetimeIndex. :param window_size: length of time series slicing chunks """ def __init__( self, dataframe: pd.DataFrame, window_size: int, ): super().__init__() self.dataframe = dataframe self.window_size = window_size self.dataframe_rows = len(self.dataframe) self.length = self.dataframe_rows - self.window_size + 1 def moving_slicing(self, idx: int) -> np.ndarray: return self.dataframe[idx : self.window_size + idx].values def _validate_dataframe(self) -> None: """Validate the input dataframe. - We require the dataframe index to be DatetimeIndex. - This dataset is null aversion. - Dataframe index should be sorted. """ if not isinstance( self.dataframe.index, pd.core.indexes.datetimes.DatetimeIndex ): raise TypeError( "Type of the dataframe index is not DatetimeIndex" f": {type(self.dataframe.index)}" ) has_na = self.dataframe.isnull().values.any() if has_na: logger.warning("Dataframe has null") has_index_sorted = self.dataframe.index.equals( self.dataframe.index.sort_values() ) if not has_index_sorted: logger.warning("Dataframe index is not sorted") def __getitem__(self, idx: int) -> Tuple[np.ndarray, np.ndarray]: if isinstance(idx, slice): if (idx.start < 0) or (idx.stop >= self.length): raise IndexError(f"Slice out of range: {idx}") step = idx.step if idx.step is not None else 1 return [self.moving_slicing(i) for i in range(idx.start, idx.stop, step)] else: if idx >= self.length: raise IndexError("End of dataset") return self.moving_slicing(idx) def __len__(self) -> int: return self.length ```` ```` class TimeVAEDataModule(L.LightningDataModule): """Lightning DataModule for Time Series VAE. This data module takes a pandas dataframe and generates the corresponding dataloaders for training, validation and testing. ```python time_vae_dm_example = TimeVAEDataModule( window_size=30, dataframe=df[["count"]], batch_size=32 ) ``` """ def __init__( self, window_size: int, dataframe: pd.DataFrame, test_fraction: float = 0.3, val_fraction: float = 0.1, batch_size: int = 32, num_workers: int = 0, ): super().__init__() self.window_size = window_size self.batch_size = batch_size self.dataframe = dataframe self.test_fraction = test_fraction self.val_fraction = val_fraction self.num_workers = num_workers self.train_dataset, self.val_dataset = self.split_train_val( self.train_val_dataset ) @cached_property def df_length(self): return len(self.dataframe) @cached_property def df_test_length(self): return int(self.df_length * self.test_fraction) @cached_property def df_train_val_length(self): return self.df_length - self.df_test_length @cached_property def train_val_dataframe(self): return self.dataframe.iloc[: self.df_train_val_length] @cached_property def test_dataframe(self): return self.dataframe.iloc[self.df_train_val_length :] @cached_property def train_val_dataset(self): return TimeVAEDataset( dataframe=self.train_val_dataframe, window_size=self.window_size, ) @cached_property def test_dataset(self): return TimeVAEDataset( dataframe=self.test_dataframe, window_size=self.window_size, ) def split_train_val(self, dataset: Dataset): return torch.utils.data.random_split( dataset, [1 - self.val_fraction, self.val_fraction] ) def train_dataloader(self): return DataLoader( dataset=self.train_dataset, batch_size=self.batch_size, shuffle=True, num_workers=self.num_workers, persistent_workers=(True if self.num_workers > 0 else False), ) def test_dataloader(self): return DataLoader( dataset=self.test_dataset, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers, ) def val_dataloader(self): return DataLoader( dataset=self.val_dataset, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers, persistent_workers=(True if self.num_workers > 0 else False), ) def predict_dataloader(self): return DataLoader( dataset=self.test_dataset, batch_size=len(self.test_dataset), shuffle=False ) ```` ``` time_vae_dm_example = TimeVAEDataModule( window_size=30, dataframe=df[["count"]], batch_size=32 ) ``` ``` len(list(time_vae_dm_example.train_dataloader())) ``` ``` list(time_vae_dm_example.train_dataloader())[0].shape ``` ## Model ``` @dataclasses.dataclass class VAEParams: """Parameters for VAEEncoder and VAEDecoder :param hidden_layer_sizes: list of hidden layer sizes :param latent_size: latent space dimension :param sequence_length: input sequence length :param n_features: number of features """ hidden_layer_sizes: List[int] latent_size: int sequence_length: int n_features: int = 1 @cached_property def data_size(self) -> int: """The dimension of the input data when flattened. """ return self.sequence_length * self.n_features def asdict(self) -> dict: return dataclasses.asdict(self) ``` ``` class VAEMLPEncoder(nn.Module): """MLP Encoder of TimeVAE""" def __init__(self, params: VAEParams): super().__init__() self.params = params encode_layer_sizes = [self.params.data_size] + self.params.hidden_layer_sizes self.layers_used_to_encode = [ self._linear_block(size_in, size_out) for size_in, size_out in zip( encode_layer_sizes[:-1], encode_layer_sizes[1:] ) ] self.encode = nn.Sequential(*self.layers_used_to_encode) encoded_size = self.params.hidden_layer_sizes[-1] self.z_mean_layer = nn.Linear(encoded_size, self.params.latent_size) self.z_log_var_layer = nn.Linear(encoded_size, self.params.latent_size) def forward( self, x: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: batch_size, _, _ = x.size() x = x.transpose(1, 2) x = self.encode(x) z_mean = self.z_mean_layer(x) z_log_var = self.z_log_var_layer(x) epsilon = torch.randn( batch_size, self.params.n_features, self.params.latent_size ).type_as(x) z = z_mean + torch.exp(0.5 * z_log_var) * epsilon return z_mean, z_log_var, z def _linear_block(self, size_in: int, size_out: int) -> nn.Module: return nn.Sequential(*[nn.Linear(size_in, size_out), nn.ReLU()]) ``` ```` class VAEEncoder(nn.Module): """Encoder of TimeVAE ```python encoder = VAEEncoder( VAEParams( hidden_layer_sizes=[40, 30], latent_size=10, sequence_length=50 ) ) ``` :param params: parameters for the encoder """ def __init__(self, params: VAEParams): super().__init__() self.params = params self.hparams = params.asdict() encode_layer_sizes = [self.params.n_features] + self.params.hidden_layer_sizes self.layers_used_to_encode = [ self._conv_block(size_in, size_out) for size_in, size_out in zip( encode_layer_sizes[:-1], encode_layer_sizes[1:] ) ] + [nn.Flatten()] self.encode = nn.Sequential(*self.layers_used_to_encode) encoded_size = self.cal_conv1d_output_dim() * self.params.hidden_layer_sizes[-1] self.z_mean_layer = nn.Linear(encoded_size, self.params.latent_size) self.z_log_var_layer = nn.Linear(encoded_size, self.params.latent_size) def forward( self, x: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: batch_size, _, _ = x.size() x = x.transpose(1, 2) x = self.encode(x) z_mean = self.z_mean_layer(x).view( batch_size, self.params.n_features, self.params.latent_size ) z_log_var = self.z_log_var_layer(x).view( batch_size, self.params.n_features, self.params.latent_size ) epsilon = torch.randn( batch_size, self.params.n_features, self.params.latent_size ).type_as(x) z = z_mean + torch.exp(0.5 * z_log_var) * epsilon return z_mean, z_log_var, z def _linear_block(self, size_in: int, size_out: int) -> nn.Module: return nn.Sequential(*[nn.Linear(size_in, size_out), nn.ReLU()]) def _conv_block(self, size_in: int, size_out: int) -> nn.Module: return nn.Sequential( *[ nn.Conv1d(size_in, size_out, kernel_size=3, stride=2, padding=1), nn.ReLU(), ] ) def cal_conv1d_output_dim(self) -> int: """the output dimension of all the Conv1d layers""" output_size = self.params.sequence_length * self.params.n_features for l in self.layers_used_to_encode: if l._get_name() == "Conv1d": output_size = self._conv1d_output_dim(l, output_size) elif l._get_name() == "Sequential": for l2 in l: if l2._get_name() == "Conv1d": output_size = self._conv1d_output_dim(l2, output_size) return output_size def _conv1d_output_dim(self, layer: nn.Module, input_size: int) -> int: """Formula to calculate the output size of Conv1d layer """ return ( (input_size + 2 * layer.padding[0] - layer.kernel_size[0]) // layer.stride[0] ) + 1 ```` ``` mlp_encoder = VAEMLPEncoder( VAEParams(hidden_layer_sizes=[40, 30], latent_size=10, sequence_length=50) ) [i.size() for i in mlp_encoder(torch.ones(32, 50, 1))], mlp_encoder( torch.ones(32, 50, 1) )[-1] ``` ``` encoder = VAEEncoder( VAEParams(hidden_layer_sizes=[40, 30], latent_size=10, sequence_length=50) ) [i.size() for i in encoder(torch.ones(32, 50, 1))], encoder(torch.ones(32, 50, 1))[-1] ``` ```` class VAEDecoder(nn.Module): """Decoder of TimeVAE ```python decoder = VAEDecoder( VAEParams( hidden_layer_sizes=[30, 40], latent_size=10, sequence_length=50, ) ) ``` :param params: parameters for the decoder """ def __init__(self, params: VAEParams): super().__init__() self.params = params self.hparams = params.asdict() decode_layer_sizes = ( [self.params.latent_size] + self.params.hidden_layer_sizes + [self.params.data_size] ) self.decode = nn.Sequential( *[ self._linear_block(size_in, size_out) for size_in, size_out in zip( decode_layer_sizes[:-1], decode_layer_sizes[1:] ) ] ) def forward(self, z: torch.Tensor) -> torch.Tensor: output = self.decode(z) return output.view(-1, self.params.sequence_length, self.params.n_features) def _linear_block(self, size_in: int, size_out: int) -> nn.Module: """create linear block based on the specified sizes""" return nn.Sequential(*[nn.Linear(size_in, size_out), nn.Softplus()]) ```` ``` decoder = VAEDecoder( VAEParams(hidden_layer_sizes=[30, 40], latent_size=10, sequence_length=50) ) decoder(torch.ones(32, 1, 10)).size(), decoder(torch.ones(32, 1, 10)) ``` ``` class VAE(nn.Module): """VAE model with encoder and decoder :param encoder: encoder module :param decoder: decoder module """ def __init__(self, encoder: nn.Module, decoder: nn.Module): super().__init__() self.encoder = encoder self.decoder = decoder self.hparams = { **{f"encoder_{k}": v for k, v in self.encoder.hparams.items()}, **{f"decoder_{k}": v for k, v in self.decoder.hparams.items()}, } def forward( self, x: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: z_mean, z_log_var, z = self.encoder(x) x_reconstructed = self.decoder(z) return x_reconstructed, z_mean, z_log_var ``` ``` class VAEModel(L.LightningModule): """VAE model using VAEEncoder, VAEDecoder, and VAE :param model: VAE model :param reconstruction_weight: weight for the reconstruction loss :param learning_rate: learning rate for the optimizer :param scheduler_max_epochs: maximum epochs for the scheduler """ def __init__( self, model: VAE, reconstruction_weight: float = 1.0, learning_rate: float = 1e-3, scheduler_max_epochs: int = 10000, ): super().__init__() self.model = model self.reconstruction_weight = reconstruction_weight self.learning_rate = learning_rate self.scheduler_max_epochs = scheduler_max_epochs self.hparams.update( { **model.hparams, **{ "reconstruction_weight": reconstruction_weight, "learning_rate": learning_rate, "scheduler_max_epochs": scheduler_max_epochs, }, } ) self.save_hyperparameters(self.hparams) def forward(self, x): return self.model(x) def training_step(self, batch: torch.Tensor, batch_idx: int) -> torch.Tensor: batch_reconstructed, z_mean, z_log_var = self.model(batch) loss_total, loss_reconstruction, loss_kl = self.loss( x=batch, x_reconstructed=batch_reconstructed, z_mean=z_mean, z_log_var=z_log_var, ) self.log_dict( { "train_loss_total": loss_total, "train_loss_reconstruction": loss_reconstruction, "train_loss_kl": loss_kl, } ) return loss_total def validation_step(self, batch: torch.Tensor, batch_idx: int) -> torch.Tensor: batch_reconstructed, z_mean, z_log_var = self.model(batch) loss_total, loss_reconstruction, loss_kl = self.loss( x=batch, x_reconstructed=batch_reconstructed, z_mean=z_mean, z_log_var=z_log_var, ) self.log_dict( { "val_loss_total": loss_total, "val_loss_reconstruction": loss_reconstruction, "val_loss_kl": loss_kl, } ) return loss_total def test_step(self, batch: torch.Tensor, batch_idx: int) -> torch.Tensor: batch_reconstructed, z_mean, z_log_var = self.model(batch) loss_total, loss_reconstruction, loss_kl = self.loss( x=batch, x_reconstructed=batch_reconstructed, z_mean=z_mean, z_log_var=z_log_var, ) self.log_dict( { "test_loss_total": loss_total, "test_loss_reconstruction": loss_reconstruction, "test_loss_kl": loss_kl, } ) return loss_total def loss( self, x: torch.Tensor, x_reconstructed: torch.Tensor, z_log_var: torch.Tensor, z_mean: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: loss_reconstruction = self.reconstruction_loss(x, x_reconstructed) loss_kl = -0.5 * torch.sum(1 + z_log_var - z_mean**2 - z_log_var.exp()) loss_total = self.reconstruction_weight * loss_reconstruction + loss_kl return ( loss_total / x.size(0), loss_reconstruction / x.size(0), loss_kl / x.size(0), ) def reconstruction_loss( self, x: torch.Tensor, x_reconstructed: torch.Tensor ) -> torch.Tensor: r"""Reconstruction loss for VAE. $$ \sum_{i=1}^{N} (x_i - x_{reconstructed_i})^2 + \sum_{i=1}^{N} (\mu_i - \mu_{reconstructed_i})^2 $$ """ loss = torch.sum((x - x_reconstructed) ** 2) + torch.sum( (torch.mean(x, dim=1) - torch.mean(x_reconstructed, dim=1)) ** 2 ) return loss def configure_optimizers(self) -> dict: optimizer = torch.optim.SGD(self.parameters(), lr=self.learning_rate) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( optimizer, T_max=self.scheduler_max_epochs ) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": scheduler, "monitor": "train_loss", "interval": "step", "frequency": 1, }, } ``` # Training ``` window_size = 24 max_epochs = 2000 time_vae_dm = TimeVAEDataModule( window_size=window_size, dataframe=df[["count"]], batch_size=32 ) ``` ``` vae = VAE( encoder=VAEEncoder( VAEParams( hidden_layer_sizes=[200, 100, 50], latent_size=8, sequence_length=window_size, ) ), decoder=VAEDecoder( VAEParams( hidden_layer_sizes=[30, 50, 100], latent_size=8, sequence_length=window_size ) ), ) vae_model = VAEModel( vae, reconstruction_weight=1, learning_rate=5e-4, scheduler_max_epochs=max_epochs * len(time_vae_dm.train_dataloader()), ) ``` ``` trainer = L.Trainer( precision="64", max_epochs=max_epochs, min_epochs=5, # callbacks=[ # EarlyStopping( # monitor="val_loss_total", mode="min", min_delta=1e-10, patience=10 # ) # ], logger=L.pytorch.loggers.TensorBoardLogger( save_dir="lightning_logs", name="time_vae_koisk" ), ) ``` ``` trainer.fit(model=vae_model, datamodule=time_vae_dm) ``` ``` vae.encoder(pred_batch.cuda()) ``` ## Fitted Model ``` IS_RELOAD = True ``` ``` if IS_RELOAD: checkpoint_path = "lightning_logs/time_vae_koisk/version_8/checkpoints/epoch=1999-step=170000.ckpt" vae_model_reloaded = VAEModel.load_from_checkpoint(checkpoint_path, model=vae) else: vae_model_reloaded = vae_model ``` ``` for pred_batch in time_vae_dm.predict_dataloader(): print(pred_batch.size()) i_pred = vae_model_reloaded.model(pred_batch.float().cuda()) break ``` ``` i_pred[0].size() ``` ``` _, ax = plt.subplots() element = 4 ax.plot(pred_batch.detach().numpy()[element, :, 0]) ax.plot(i_pred[0].cpu().detach().numpy()[element, :, 0], "x-") ``` Data generation using the decoder. ``` sampling_z = torch.randn( pred_batch.size(0), vae_model_reloaded.model.encoder.params.latent_size ).type_as(vae_model_reloaded.model.encoder.z_mean_layer.weight) generated_samples_x = ( vae_model_reloaded.model.decoder(sampling_z).cpu().detach().numpy().squeeze() ) ``` ``` generated_samples_x.size ``` ``` _, ax = plt.subplots() for i in range(min(len(generated_samples_x), 4)): ax.plot(generated_samples_x[i, :], "x-") ``` ``` from openTSNE import TSNE ``` ``` n_tsne_samples = 100 ``` ``` original_samples = pred_batch.cpu().detach().numpy().squeeze()[:n_tsne_samples] original_samples.shape ``` ``` tsne = TSNE( perplexity=30, metric="euclidean", n_jobs=8, random_state=42, verbose=True, ) ``` ``` original_samples_embedding = tsne.fit(original_samples) ``` ``` generated_samples_x[:n_tsne_samples] ``` ``` generated_samples_embedding = original_samples_embedding.transform( generated_samples_x[:n_tsne_samples] ) ``` ``` fig, ax = plt.subplots(figsize=(7, 7)) ax.scatter( original_samples_embedding[:, 0], original_samples_embedding[:, 1], color="black", marker=".", label="original", ) ax.scatter( generated_samples_embedding[:, 0], generated_samples_embedding[:, 1], color="red", marker="x", label="generated", ) ax.set_title("t-SNE of original and generated samples") ax.set_xlabel("t-SNE 1") ax.set_ylabel("t-SNE 2") ``` ## Embeddings ``` from pathlib import Path import numpy as np import pandas as pd import plotly.express as px from torch.utils.data import DataLoader from torchdr import PCA, TSNE, UMAP from ts_dl_utils.datasets.dataset import DataFrameDataset ``` ``` vae_model_reloaded ``` ``` def embedding_extractor(forecaster: VAEModel, x: torch.Tensor) -> tuple[torch.Tensor]: """compute the embeddings based on the input :param forecaster: the trained forecaster :param x: input historical time series, """ forecaster.model.to(x.device) z_mean, z_log_var, z = forecaster.model.encoder( x.type_as(forecaster.model.encoder.z_mean_layer.weight) ) return z_mean, z_log_var, z ``` ``` investigation_dl = DataLoader( dataset=DataFrameDataset( dataframe=df[["count"]], history_length=window_size, horizon=1, gap=0 ), batch_size=400, shuffle=False, ) investigation_dl ``` ``` input_example = list(investigation_dl)[0][0] input_example.shape ``` ``` z_mean_example, z_log_var_example, z_example = embedding_extractor( vae_model_reloaded, input_example ) z_example.shape ``` ``` (z_example.shape, z_mean_example.shape, z_log_var_example.shape) ``` ``` n_components = 3 # dr_z_result = TSNE( dr_input_result = PCA( # n_neighbors=30, backend='torch', # perplexity=30, n_components=n_components ).fit_transform(input_example.detach().squeeze()) dr_input_result.shape ``` ``` dr_z_mean_result = TSNE( # dr_z_result = PCA( # n_neighbors=30, backend='torch', # perplexity=30, n_components=n_components ).fit_transform( # z_example.detach().squeeze() z_mean_example.detach().squeeze() ) dr_z_mean_result.shape ``` ``` def create_embedding_dataframe( dr_result: torch.Tensor, n_batches: int, input_example: torch.Tensor, n_components: int, ) -> pd.DataFrame: dr_df = pd.DataFrame( dr_result.detach().numpy(), columns=[f"DR_{i+1}" for i in range(n_components)] ) dr_df["batch"] = sum( [[i] * (len(dr_df) // n_batches) for i in range(n_batches)], [] ) dr_df["sample_idx"] = list(range(len(dr_df) // n_batches)) * n_batches # dr_df["input"] = np.concatenate( # input_example[:n_batches].detach().numpy().astype("float32") # ) dr_df = dr_df.merge( pd.DataFrame( input_example[:n_batches].detach()[:, 0, 0].numpy(), columns=["batch_first_value"], ) .reset_index() .rename(columns={"index": "batch"}), how="left", on="batch", ) return dr_df ``` ``` dr_input_df = create_embedding_dataframe( dr_result=dr_input_result, n_batches=input_example.shape[0], input_example=input_example, n_components=n_components, ) ``` ``` # px.scatter( px.scatter_3d( dr_input_df, x="DR_1", y="DR_2", z="DR_3", # z='batch_first_value', # color='sample_idx', # symbol='type', # color="batch", # color="DR_3", color="batch_first_value", title="Embedding of Input Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` dr_z_df = create_embedding_dataframe( dr_result=dr_z_mean_result, n_batches=z_example.shape[0], input_example=input_example, n_components=n_components, ) ``` ``` px.scatter( dr_z_df, x="DR_1", # y="batch_first_value", y="DR_2", # z='DR_3', # z='batch_first_value', # color='sample_idx', # symbol='type', # color="batch", # color="DR_2", color="batch_first_value", title="UMAP Embedding of Encoder Encoded Time Series", height=600, width=800, ).update_layout(legend=dict(itemsizing="constant", orientation="h", y=-0.2)).show() ``` ``` px.imshow(input_example.squeeze().T, aspect="auto") ``` ``` px.imshow(dr_input_result.T, aspect="auto") ``` ``` import os ``` ``` import numpy as np import torch import torch.nn as nn import torch.nn.init as init import torch.optim as optim ``` from .data import batch\_generator from utils import extract\_time, random\_generator, NormMinMax from .model import Encoder, Recovery, Generator, Discriminator, Supervisor # Utilities ``` def random_generator(batch_size, z_dim, T_mb, max_seq_len): """Random vector generation. Args: - batch_size: size of the random vector - z_dim: dimension of random vector - T_mb: time information for the random vector - max_seq_len: maximum sequence length Returns: - Z_mb: generated random vector """ Z_mb = list() for i in range(batch_size): temp = np.zeros([max_seq_len, z_dim]) temp_Z = np.random.uniform(0.0, 1, [T_mb[i], z_dim]) temp[: T_mb[i], :] = temp_Z Z_mb.append(temp_Z) return Z_mb ``` ``` def batch_generator(data, time, batch_size): """Mini-batch generator. Args: - data: time-series data - time: time information - batch_size: the number of samples in each batch Returns: - X_mb: time-series data in each batch - T_mb: time information in each batch """ no = len(data) idx = np.random.permutation(no) train_idx = idx[:batch_size] X_mb = list(data[i] for i in train_idx) T_mb = list(time[i] for i in train_idx) return X_mb, T_mb ``` ``` def NormMinMax(data): """Min-Max Normalizer. Args: - data: raw data Returns: - norm_data: normalized data - min_val: minimum values (for renormalization) - max_val: maximum values (for renormalization) """ min_val = np.min(np.min(data, axis=0), axis=0) data = data - min_val # [3661, 24, 6] max_val = np.max(np.max(data, axis=0), axis=0) norm_data = data / (max_val + 1e-7) return norm_data, min_val, max_val ``` ``` def _weights_init(m): classname = m.__class__.__name__ if isinstance(m, nn.Linear): init.xavier_uniform_(m.weight) m.bias.data.fill_(0) elif classname.find("Conv") != -1: m.weight.data.normal_(0.0, 0.02) elif classname.find("Norm") != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) elif classname.find("GRU") != -1: for name, param in m.named_parameters(): if "weight_ih" in name: init.xavier_uniform_(param.data) elif "weight_hh" in name: init.orthogonal_(param.data) elif "bias" in name: param.data.fill_(0) class Encoder(nn.Module): """Embedding network between original feature space to latent space. Args: - input: input time-series features. (L, N, X) = (24, ?, 6) - h3: (num_layers, N, H). [3, ?, 24] Returns: - H: embeddings """ def __init__(self, opt): super(Encoder, self).__init__() self.rnn = nn.GRU( input_size=opt.z_dim, hidden_size=opt.hidden_dim, num_layers=opt.num_layer ) self.fc = nn.Linear(opt.hidden_dim, opt.hidden_dim) self.sigmoid = nn.Sigmoid() self.apply(_weights_init) def forward(self, input, sigmoid=True): e_outputs, _ = self.rnn(input) H = self.fc(e_outputs) if sigmoid: H = self.sigmoid(H) return H class Recovery(nn.Module): """Recovery network from latent space to original space. Args: - H: latent representation - T: input time information Returns: - X_tilde: recovered data """ def __init__(self, opt): super(Recovery, self).__init__() self.rnn = nn.GRU( input_size=opt.hidden_dim, hidden_size=opt.z_dim, num_layers=opt.num_layer ) self.fc = nn.Linear(opt.z_dim, opt.z_dim) self.sigmoid = nn.Sigmoid() self.apply(_weights_init) def forward(self, input, sigmoid=True): r_outputs, _ = self.rnn(input) X_tilde = self.fc(r_outputs) if sigmoid: X_tilde = self.sigmoid(X_tilde) return X_tilde class Generator(nn.Module): """Generator function: Generate time-series data in latent space. Args: - Z: random variables - T: input time information Returns: - E: generated embedding """ def __init__(self, opt): super(Generator, self).__init__() self.rnn = nn.GRU( input_size=opt.z_dim, hidden_size=opt.hidden_dim, num_layers=opt.num_layer ) # self.norm = nn.LayerNorm(opt.hidden_dim) self.fc = nn.Linear(opt.hidden_dim, opt.hidden_dim) self.sigmoid = nn.Sigmoid() self.apply(_weights_init) def forward(self, input, sigmoid=True): g_outputs, _ = self.rnn(input) # g_outputs = self.norm(g_outputs) E = self.fc(g_outputs) if sigmoid: E = self.sigmoid(E) return E class Supervisor(nn.Module): """Generate next sequence using the previous sequence. Args: - H: latent representation - T: input time information Returns: - S: generated sequence based on the latent representations generated by the generator """ def __init__(self, opt): super(Supervisor, self).__init__() self.rnn = nn.GRU( input_size=opt.hidden_dim, hidden_size=opt.hidden_dim, num_layers=opt.num_layer, ) # self.norm = nn.LayerNorm(opt.hidden_dim) self.fc = nn.Linear(opt.hidden_dim, opt.hidden_dim) self.sigmoid = nn.Sigmoid() self.apply(_weights_init) def forward(self, input, sigmoid=True): s_outputs, _ = self.rnn(input) # s_outputs = self.norm(s_outputs) S = self.fc(s_outputs) if sigmoid: S = self.sigmoid(S) return S class Discriminator(nn.Module): """Discriminate the original and synthetic time-series data. Args: - H: latent representation - T: input time information Returns: - Y_hat: classification results between original and synthetic time-series """ def __init__(self, opt): super(Discriminator, self).__init__() self.rnn = nn.GRU( input_size=opt.hidden_dim, hidden_size=opt.hidden_dim, num_layers=opt.num_layer, ) # self.norm = nn.LayerNorm(opt.hidden_dim) self.fc = nn.Linear(opt.hidden_dim, opt.hidden_dim) self.sigmoid = nn.Sigmoid() self.apply(_weights_init) def forward(self, input, sigmoid=True): d_outputs, _ = self.rnn(input) Y_hat = self.fc(d_outputs) if sigmoid: Y_hat = self.sigmoid(Y_hat) return Y_hat ``` ``` class BaseModel: """Base Model for timegan""" def __init__(self, opt, ori_data): # Seed for deterministic behavior self.seed(opt.manualseed) # Initalize variables. self.opt = opt self.ori_data, self.min_val, self.max_val = NormMinMax(ori_data) self.ori_time, self.max_seq_len = extract_time(self.ori_data) self.data_num, _, _ = np.asarray(ori_data).shape # 3661; 24; 6 self.trn_dir = os.path.join(self.opt.outf, self.opt.name, "train") self.tst_dir = os.path.join(self.opt.outf, self.opt.name, "test") self.device = torch.device("cuda:0" if self.opt.device != "cpu" else "cpu") def seed(self, seed_value): """Seed Arguments: seed_value {int} -- [description] """ # Check if seed is default value if seed_value == -1: return # Otherwise seed all functionality import random random.seed(seed_value) torch.manual_seed(seed_value) torch.cuda.manual_seed_all(seed_value) np.random.seed(seed_value) torch.backends.cudnn.deterministic = True def save_weights(self, epoch): """Save net weights for the current epoch. Args: epoch ([int]): Current epoch number. """ weight_dir = os.path.join(self.opt.outf, self.opt.name, "train", "weights") if not os.path.exists(weight_dir): os.makedirs(weight_dir) torch.save( {"epoch": epoch + 1, "state_dict": self.nete.state_dict()}, "%s/netE.pth" % (weight_dir), ) torch.save( {"epoch": epoch + 1, "state_dict": self.netr.state_dict()}, "%s/netR.pth" % (weight_dir), ) torch.save( {"epoch": epoch + 1, "state_dict": self.netg.state_dict()}, "%s/netG.pth" % (weight_dir), ) torch.save( {"epoch": epoch + 1, "state_dict": self.netd.state_dict()}, "%s/netD.pth" % (weight_dir), ) torch.save( {"epoch": epoch + 1, "state_dict": self.nets.state_dict()}, "%s/netS.pth" % (weight_dir), ) def train_one_iter_er(self): """Train the model for one epoch.""" self.nete.train() self.netr.train() # set mini-batch self.X0, self.T = batch_generator( self.ori_data, self.ori_time, self.opt.batch_size ) self.X = torch.tensor(self.X0, dtype=torch.float32).to(self.device) # train encoder & decoder self.optimize_params_er() def train_one_iter_er_(self): """Train the model for one epoch.""" self.nete.train() self.netr.train() # set mini-batch self.X0, self.T = batch_generator( self.ori_data, self.ori_time, self.opt.batch_size ) self.X = torch.tensor(self.X0, dtype=torch.float32).to(self.device) # train encoder & decoder self.optimize_params_er_() def train_one_iter_s(self): """Train the model for one epoch.""" # self.nete.eval() self.nets.train() # set mini-batch self.X0, self.T = batch_generator( self.ori_data, self.ori_time, self.opt.batch_size ) self.X = torch.tensor(self.X0, dtype=torch.float32).to(self.device) # train superviser self.optimize_params_s() def train_one_iter_g(self): """Train the model for one epoch.""" """self.netr.eval() self.nets.eval() self.netd.eval()""" self.netg.train() # set mini-batch self.X0, self.T = batch_generator( self.ori_data, self.ori_time, self.opt.batch_size ) self.X = torch.tensor(self.X0, dtype=torch.float32).to(self.device) self.Z = random_generator( self.opt.batch_size, self.opt.z_dim, self.T, self.max_seq_len ) # train superviser self.optimize_params_g() def train_one_iter_d(self): """Train the model for one epoch.""" """self.nete.eval() self.netr.eval() self.nets.eval() self.netg.eval()""" self.netd.train() # set mini-batch self.X0, self.T = batch_generator( self.ori_data, self.ori_time, self.opt.batch_size ) self.X = torch.tensor(self.X0, dtype=torch.float32).to(self.device) self.Z = random_generator( self.opt.batch_size, self.opt.z_dim, self.T, self.max_seq_len ) # train superviser self.optimize_params_d() def train(self): """Train the model""" for iter in range(self.opt.iteration): # Train for one iter self.train_one_iter_er() print("Encoder training step: " + str(iter) + "/" + str(self.opt.iteration)) for iter in range(self.opt.iteration): # Train for one iter self.train_one_iter_s() print( "Superviser training step: " + str(iter) + "/" + str(self.opt.iteration) ) for iter in range(self.opt.iteration): # Train for one iter for kk in range(2): self.train_one_iter_g() self.train_one_iter_er_() self.train_one_iter_d() print( "Superviser training step: " + str(iter) + "/" + str(self.opt.iteration) ) self.save_weights(self.opt.iteration) self.generated_data = self.generation(self.opt.batch_size) print("Finish Synthetic Data Generation") # self.evaluation() """def evaluation(self): ## Performance metrics # Output initialization metric_results = dict() # 1. Discriminative Score discriminative_score = list() for _ in range(self.opt.metric_iteration): temp_disc = discriminative_score_metrics(self.ori_data, self.generated_data) discriminative_score.append(temp_disc) metric_results['discriminative'] = np.mean(discriminative_score) # 2. Predictive score predictive_score = list() for tt in range(self.opt.metric_iteration): temp_pred = predictive_score_metrics(self.ori_data, self.generated_data) predictive_score.append(temp_pred) metric_results['predictive'] = np.mean(predictive_score) # 3. Visualization (PCA and tSNE) visualization(self.ori_data, self.generated_data, 'pca') visualization(self.ori_data, self.generated_data, 'tsne') ## Print discriminative and predictive scores print(metric_results) """ def generation(self, num_samples, mean=0.0, std=1.0): if num_samples == 0: return None, None ## Synthetic data generation self.X0, self.T = batch_generator( self.ori_data, self.ori_time, self.opt.batch_size ) self.Z = random_generator( num_samples, self.opt.z_dim, self.T, self.max_seq_len # , mean, std ) self.Z = torch.tensor(self.Z, dtype=torch.float32).to(self.device) self.E_hat = self.netg(self.Z) # [?, 24, 24] self.H_hat = self.nets(self.E_hat) # [?, 24, 24] generated_data_curr = ( self.netr(self.H_hat).cpu().detach().numpy() ) # [?, 24, 24] generated_data = list() for i in range(num_samples): temp = generated_data_curr[i, : self.ori_time[i], :] generated_data.append(temp) # Renormalization generated_data = generated_data * self.max_val generated_data = generated_data + self.min_val return generated_data ``` ``` class TimeGAN(BaseModel): """TimeGAN Class""" @property def name(self): return "TimeGAN" def __init__(self, opt, ori_data): super(TimeGAN, self).__init__(opt, ori_data) # -- Misc attributes self.epoch = 0 self.times = [] self.total_steps = 0 # Create and initialize networks. self.nete = Encoder(self.opt).to(self.device) self.netr = Recovery(self.opt).to(self.device) self.netg = Generator(self.opt).to(self.device) self.netd = Discriminator(self.opt).to(self.device) self.nets = Supervisor(self.opt).to(self.device) if self.opt.resume != "": print("\nLoading pre-trained networks.") self.opt.iter = torch.load(os.path.join(self.opt.resume, "netG.pth"))[ "epoch" ] self.nete.load_state_dict( torch.load(os.path.join(self.opt.resume, "netE.pth"))["state_dict"] ) self.netr.load_state_dict( torch.load(os.path.join(self.opt.resume, "netR.pth"))["state_dict"] ) self.netg.load_state_dict( torch.load(os.path.join(self.opt.resume, "netG.pth"))["state_dict"] ) self.netd.load_state_dict( torch.load(os.path.join(self.opt.resume, "netD.pth"))["state_dict"] ) self.nets.load_state_dict( torch.load(os.path.join(self.opt.resume, "netS.pth"))["state_dict"] ) print("\tDone.\n") # loss self.l_mse = nn.MSELoss() self.l_r = nn.L1Loss() self.l_bce = nn.BCELoss() # Setup optimizer if self.opt.isTrain: self.nete.train() self.netr.train() self.netg.train() self.netd.train() self.nets.train() self.optimizer_e = optim.Adam( self.nete.parameters(), lr=self.opt.lr, betas=(self.opt.beta1, 0.999) ) self.optimizer_r = optim.Adam( self.netr.parameters(), lr=self.opt.lr, betas=(self.opt.beta1, 0.999) ) self.optimizer_g = optim.Adam( self.netg.parameters(), lr=self.opt.lr, betas=(self.opt.beta1, 0.999) ) self.optimizer_d = optim.Adam( self.netd.parameters(), lr=self.opt.lr, betas=(self.opt.beta1, 0.999) ) self.optimizer_s = optim.Adam( self.nets.parameters(), lr=self.opt.lr, betas=(self.opt.beta1, 0.999) ) def forward_e(self): """Forward propagate through netE""" self.H = self.nete(self.X) def forward_er(self): """Forward propagate through netR""" self.H = self.nete(self.X) self.X_tilde = self.netr(self.H) def forward_g(self): """Forward propagate through netG""" self.Z = torch.tensor(self.Z, dtype=torch.float32).to(self.device) self.E_hat = self.netg(self.Z) def forward_dg(self): """Forward propagate through netD""" self.Y_fake = self.netd(self.H_hat) self.Y_fake_e = self.netd(self.E_hat) def forward_rg(self): """Forward propagate through netG""" self.X_hat = self.netr(self.H_hat) def forward_s(self): """Forward propagate through netS""" self.H_supervise = self.nets(self.H) # print(self.H, self.H_supervise) def forward_sg(self): """Forward propagate through netS""" self.H_hat = self.nets(self.E_hat) def forward_d(self): """Forward propagate through netD""" self.Y_real = self.netd(self.H) self.Y_fake = self.netd(self.H_hat) self.Y_fake_e = self.netd(self.E_hat) def backward_er(self): """Backpropagate through netE""" self.err_er = self.l_mse(self.X_tilde, self.X) self.err_er.backward(retain_graph=True) print("Loss: ", self.err_er) def backward_er_(self): """Backpropagate through netE""" self.err_er_ = self.l_mse(self.X_tilde, self.X) self.err_s = self.l_mse(self.H_supervise[:, :-1, :], self.H[:, 1:, :]) self.err_er = 10 * torch.sqrt(self.err_er_) + 0.1 * self.err_s self.err_er.backward(retain_graph=True) # print("Loss: ", self.err_er_, self.err_s) def backward_g(self): """Backpropagate through netG""" self.err_g_U = self.l_bce(self.Y_fake, torch.ones_like(self.Y_fake)) self.err_g_U_e = self.l_bce(self.Y_fake_e, torch.ones_like(self.Y_fake_e)) self.err_g_V1 = torch.mean( torch.abs( torch.sqrt(torch.std(self.X_hat, [0])[1] + 1e-6) - torch.sqrt(torch.std(self.X, [0])[1] + 1e-6) ) ) # |a^2 - b^2| self.err_g_V2 = torch.mean( torch.abs((torch.mean(self.X_hat, [0])[0]) - (torch.mean(self.X, [0])[0])) ) # |a - b| self.err_s = self.l_mse(self.H_supervise[:, :-1, :], self.H[:, 1:, :]) self.err_g = ( self.err_g_U + self.err_g_U_e * self.opt.w_gamma + self.err_g_V1 * self.opt.w_g + self.err_g_V2 * self.opt.w_g + torch.sqrt(self.err_s) ) self.err_g.backward(retain_graph=True) print("Loss G: ", self.err_g) def backward_s(self): """Backpropagate through netS""" self.err_s = self.l_mse(self.H[:, 1:, :], self.H_supervise[:, :-1, :]) self.err_s.backward(retain_graph=True) print("Loss S: ", self.err_s) # print(torch.autograd.grad(self.err_s, self.nets.parameters())) def backward_d(self): """Backpropagate through netD""" self.err_d_real = self.l_bce(self.Y_real, torch.ones_like(self.Y_real)) self.err_d_fake = self.l_bce(self.Y_fake, torch.zeros_like(self.Y_fake)) self.err_d_fake_e = self.l_bce(self.Y_fake_e, torch.zeros_like(self.Y_fake_e)) self.err_d = ( self.err_d_real + self.err_d_fake + self.err_d_fake_e * self.opt.w_gamma ) if self.err_d > 0.15: self.err_d.backward(retain_graph=True) # print("Loss D: ", self.err_d) def optimize_params_er(self): """Forwardpass, Loss Computation and Backwardpass.""" # Forward-pass self.forward_er() # Backward-pass # nete & netr self.optimizer_e.zero_grad() self.optimizer_r.zero_grad() self.backward_er() self.optimizer_e.step() self.optimizer_r.step() def optimize_params_er_(self): """Forwardpass, Loss Computation and Backwardpass.""" # Forward-pass self.forward_er() self.forward_s() # Backward-pass # nete & netr self.optimizer_e.zero_grad() self.optimizer_r.zero_grad() self.backward_er_() self.optimizer_e.step() self.optimizer_r.step() def optimize_params_s(self): """Forwardpass, Loss Computation and Backwardpass.""" # Forward-pass self.forward_e() self.forward_s() # Backward-pass # nets self.optimizer_s.zero_grad() self.backward_s() self.optimizer_s.step() def optimize_params_g(self): """Forwardpass, Loss Computation and Backwardpass.""" # Forward-pass self.forward_e() self.forward_s() self.forward_g() self.forward_sg() self.forward_rg() self.forward_dg() # Backward-pass # nets self.optimizer_g.zero_grad() self.optimizer_s.zero_grad() self.backward_g() self.optimizer_g.step() self.optimizer_s.step() def optimize_params_d(self): """Forwardpass, Loss Computation and Backwardpass.""" # Forward-pass self.forward_e() self.forward_g() self.forward_sg() self.forward_d() self.forward_dg() # Backward-pass # nets self.optimizer_d.zero_grad() self.backward_d() self.optimizer_d.step() ``` ``` def sine_data_generation(no, seq_len, dim): """Sine data generation. Args: - no: the number of samples - seq_len: sequence length of the time-series - dim: feature dimensions Returns: - data: generated data """ # Initialize the output data = list() # Generate sine data for i in range(no): # Initialize each time-series temp = list() # For each feature for k in range(dim): # Randomly drawn frequency and phase freq = np.random.uniform(0, 0.1) phase = np.random.uniform(0, 0.1) # Generate sine signal based on the drawn frequency and phase temp_data = [np.sin(freq * j + phase) for j in range(seq_len)] temp.append(temp_data) # Align row/column temp = np.transpose(np.asarray(temp)) # Normalize to [0,1] temp = (temp + 1) * 0.5 # Stack the generated data data.append(temp) return data ``` ``` def extract_time(data): """Returns Maximum sequence length and each sequence length. Args: - data: original data Returns: - time: extracted time information - max_seq_len: maximum sequence length """ time = list() max_seq_len = 0 for i in range(len(data)): max_seq_len = max(max_seq_len, len(data[i][:, 0])) time.append(len(data[i][:, 0])) return time, max_seq_len ``` # Train ``` import dataclasses ``` ``` @dataclasses.dataclass class ModelParams: z_dim: int seq_len: int module: str hidden_dim: int num_layer: int iteration: int batch_size: int metric_iteration: int manualseed: int outf: str name: str device: str resume: str isTrain: bool = True lr: float = 0.0002 beta1: float = 0.9 w_gamma: float = 1 w_es: float = 0.1 w_e0: float = 10 w_g: float = 100 model_params = { "z_dim": 6, "seq_len": 24, "module": "gru", "hidden_dim": 24, "num_layer": 3, "iteration": 100, "batch_size": 128, "metric_iteration": 10, "manualseed": 42, "outf": "tmp", "name": "timegan", "device": "cpu", "resume": "", } ``` ``` data = sine_data_generation(3661, 24, 1) ``` ``` model = TimeGAN(ModelParams(**model_params), data) ``` ``` model.train() ``` > [!NOTE] > > **Output (61 lines)** > > ``` > ... (580 earlier lines) > Loss G: tensor(34.1517, grad_fn=) > Loss G: tensor(34.3027, grad_fn=) > Superviser training step: 60/100 > Loss G: tensor(34.0173, grad_fn=) > ... (66 lines omitted) ... > Superviser training step: 81/100 > Loss G: tensor(30.2938, grad_fn=) > Loss G: tensor(30.0817, grad_fn=) > Superviser training step: 82/100 > Loss G: tensor(30.2097, grad_fn=) > Loss G: tensor(30.0416, grad_fn=) > Superviser training step: 83/100 > Loss G: tensor(30.1256, grad_fn=) > Loss G: tensor(30.2187, grad_fn=) > Superviser training step: 84/100 > Loss G: tensor(29.8438, grad_fn=) > Loss G: tensor(29.8585, grad_fn=) > Superviser training step: 85/100 > Loss G: tensor(29.8011, grad_fn=) > Loss G: tensor(29.7525, grad_fn=) > Superviser training step: 86/100 > Loss G: tensor(29.4081, grad_fn=) > Loss G: tensor(29.6716, grad_fn=) > Superviser training step: 87/100 > Loss G: tensor(29.5619, grad_fn=) > Loss G: tensor(29.0439, grad_fn=) > Superviser training step: 88/100 > Loss G: tensor(29.3196, grad_fn=) > Loss G: tensor(29.0006, grad_fn=) > Superviser training step: 89/100 > Loss G: tensor(29.1867, grad_fn=) > Loss G: tensor(29.2946, grad_fn=) > Superviser training step: 90/100 > Loss G: tensor(29.0692, grad_fn=) > Loss G: tensor(29.2197, grad_fn=) > Superviser training step: 91/100 > Loss G: tensor(29.5392, grad_fn=) > Loss G: tensor(28.7492, grad_fn=) > Superviser training step: 92/100 > Loss G: tensor(28.8911, grad_fn=) > Loss G: tensor(28.9048, grad_fn=) > Superviser training step: 93/100 > Loss G: tensor(28.7696, grad_fn=) > Loss G: tensor(28.8680, grad_fn=) > Superviser training step: 94/100 > Loss G: tensor(28.4785, grad_fn=) > Loss G: tensor(28.5600, grad_fn=) > Superviser training step: 95/100 > Loss G: tensor(28.5202, grad_fn=) > Loss G: tensor(28.4299, grad_fn=) > Superviser training step: 96/100 > Loss G: tensor(28.6757, grad_fn=) > Loss G: tensor(28.8718, grad_fn=) > Superviser training step: 97/100 > Loss G: tensor(28.1194, grad_fn=) > Loss G: tensor(28.4028, grad_fn=) > Superviser training step: 98/100 > Loss G: tensor(28.2559, grad_fn=) > Loss G: tensor(28.1906, grad_fn=) > Superviser training step: 99/100 > ``` ``` model.generated_data.shape ``` ``` model.generated_data ``` ``` import matplotlib.pyplot as plt ``` ``` data[0] ``` ``` for i in range(len(data)): plt.plot(data[i].shape, ".") ``` # Transformer Explainer ``` import math ``` ``` import matplotlib.pyplot as plt import numpy as np import scipy as sp import torch from torch import nn ``` ## Examples ``` x = np.array([1, 3]) ``` ``` qk = np.outer(x, x) sp.special.expit(qk) ``` ``` sp.special.expit(qk).dot(x) ``` ``` sp.special.expit(np.outer([1, 1], [1, 1])) ``` ## The A Matrix Some examples of the A matrix. ``` x = np.array([1, 10]) ``` ``` def compare_a(a, x): return a, sp.special.expit(a), sp.special.expit(a).dot(x) ``` ``` a_1 = np.array([[1, 0], [0, 1]]) compare_a(a_1, x) ``` ``` a_2 = np.array([[1, -10], [-10, 1]]) compare_a(a_2, x) ``` ``` a_3 = np.array([[-10, 1], [1, -10]]) compare_a(a_3, x) ``` ## Visualize We plot out the q,k vectors and the corresponding attention. ``` atten_similarity_q = np.array([[1], [10]]) atten_similarity_k = np.array([[1], [10]]) atten_similarity_sim = sp.special.expit( np.outer(atten_similarity_q, atten_similarity_k) ) for a in [atten_similarity_q, atten_similarity_k, atten_similarity_sim]: fig, ax = plt.subplots(figsize=(7, 7)) ax.matshow(a) for (i, j), z in np.ndenumerate(a): ax.text( j, i, "{:0.1f}".format(z), ha="center", va="center", bbox=dict(boxstyle="round", facecolor="white", edgecolor="0.3"), fontsize="xx-large", ) ax.set_axis_off() ``` ## Positional Encoding ``` import math ``` ``` class PositionalEncodingSimple: """Positional encoding for our transformer written in numpy. :param d_model: hidden dimension of the encoder :param max_len: maximum length of our positional encoder. The encoder can not encode sequence length longer than max_len. """ def __init__(self, d_model: int, max_len: int = 100): position = np.expand_dims(np.arange(max_len), axis=1) div_term = np.exp(np.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)) self.pe = np.zeros((max_len, d_model)) self.pe[:, 0::2] = np.sin(position * div_term) self.pe[:, 1::2] = np.cos(position * div_term) def __call__(self, x: np.ndarray) -> np.ndarray: """ :param x: input to be encoded with shape `(batch_size, sequence_length, embedding_dim)` """ return self.pe[: x.shape[1]] pes = PositionalEncodingSimple(d_model=50) x_pes_in = np.ones((1, 10, 1)) x_pes_out = pes(x=x_pes_in) _, ax = plt.subplots(figsize=(10, 6.18)) ax.matshow(x_pes_out, cmap="cividis") ax.set_xlabel("Embedding") ax.set_ylabel("Temporal") ``` ``` _, ax = plt.subplots() ax.plot(x_pes_out[-1, :]) ax.plot(x_pes_out[0, :]) ``` Positional encoding in nixtla ``` class PositionalEmbedding(nn.Module): def __init__(self, hidden_size, max_len=5000): super(PositionalEmbedding, self).__init__() # Compute the positional encodings once in log space. pe = torch.zeros(max_len, hidden_size).float() pe.require_grad = False position = torch.arange(0, max_len).float().unsqueeze(1) div_term = ( torch.arange(0, hidden_size, 2).float() * -(math.log(10000.0) / hidden_size) ).exp() pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0) self.register_buffer("pe", pe) def forward(self, x): return self.pe[:, : x.size(1)] ``` ``` pe = PositionalEmbedding(hidden_size=192, max_len=20) ``` ``` plt.plot((torch.arange(0, 192, 2).float() * -(math.log(10000.0) / 192)).exp().numpy()) ``` Token Embedding ``` class TokenEmbedding(nn.Module): def __init__(self, c_in, hidden_size): super(TokenEmbedding, self).__init__() padding = 1 if torch.__version__ >= "1.5.0" else 2 self.tokenConv = nn.Conv1d( in_channels=c_in, out_channels=hidden_size, kernel_size=3, padding=padding, padding_mode="circular", bias=False, ) for m in self.modules(): if isinstance(m, nn.Conv1d): nn.init.kaiming_normal_( m.weight, mode="fan_in", nonlinearity="leaky_relu" ) def forward(self, x): x = self.tokenConv(x.permute(0, 2, 1)).transpose(1, 2) return x ``` ``` x_te_in = torch.ones((1, 10, 1)) ``` ``` te = TokenEmbedding(c_in=1, hidden_size=4) x_te = te(x_te_in) x_te.shape ``` ``` te_pe = PositionalEmbedding(hidden_size=4, max_len=20) te_pe(x) ``` ``` from neuralforecast.common._modules import DataEmbedding ``` ``` class TriangularCausalMask: def __init__(self, B, L, device="cpu"): mask_shape = [B, 1, L, L] with torch.no_grad(): self._mask = torch.triu( torch.ones(mask_shape, dtype=torch.bool), diagonal=1 ).to(device) @property def mask(self): return self._mask class FullAttention(nn.Module): """ FullAttention """ def __init__( self, mask_flag=True, scale=None, attention_dropout=0.1, output_attention=False ): super(FullAttention, self).__init__() self.scale = scale self.mask_flag = mask_flag self.output_attention = output_attention self.dropout = nn.Dropout(attention_dropout) def forward(self, queries, keys, values, attn_mask): B, L, H, E = queries.shape _, S, _, D = values.shape scale = self.scale or 1.0 / math.sqrt(E) scores = torch.einsum("blhe,bshe->bhls", queries, keys) if self.mask_flag: if attn_mask is None: attn_mask = TriangularCausalMask(B, L, device=queries.device) scores.masked_fill_(attn_mask.mask, -np.inf) A = self.dropout(torch.softmax(scale * scores, dim=-1)) V = torch.einsum("bhls,bshd->blhd", A, values) if self.output_attention: return (V.contiguous(), A) else: return (V.contiguous(), None) class AttentionLayer(nn.Module): def __init__(self, attention, hidden_size, n_head, d_keys=None, d_values=None): super(AttentionLayer, self).__init__() d_keys = d_keys or (hidden_size // n_head) d_values = d_values or (hidden_size // n_head) self.inner_attention = attention self.query_projection = nn.Linear(hidden_size, d_keys * n_head) self.key_projection = nn.Linear(hidden_size, d_keys * n_head) self.value_projection = nn.Linear(hidden_size, d_values * n_head) self.out_projection = nn.Linear(d_values * n_head, hidden_size) self.n_head = n_head def forward(self, queries, keys, values, attn_mask): B, L, _ = queries.shape _, S, _ = keys.shape H = self.n_head queries = self.query_projection(queries).view(B, L, H, -1) keys = self.key_projection(keys).view(B, S, H, -1) values = self.value_projection(values).view(B, S, H, -1) out, attn = self.inner_attention(queries, keys, values, attn_mask) # out = out.view(B, L, -1) # return self.out_projection(out), attn return out, attn ``` ``` enc_in = 1 hidden_size = 4 enc_embedding = DataEmbedding( c_in=enc_in, exog_input_size=0, hidden_size=hidden_size, pos_embedding=True ) ``` ``` x = torch.ones(size=(1, 10, 1)) # batch size: 1, history length 10, variables 1 ``` ``` x_embedded = enc_embedding(x) x_embedded.shape ``` ``` attention = FullAttention(mask_flag=False, output_attention=True) attention_layer = AttentionLayer( attention, hidden_size=hidden_size, n_head=1, ) ``` ``` attention_layer.query_projection(x_embedded).view(1, 10, 1, -1).shape ``` ``` al_out, al_att = attention_layer(x_embedded, x_embedded, x_embedded, attn_mask=False) al_out.shape ``` ``` queries = attention_layer.query_projection(x_embedded).view(1, 10, 1, -1) keys = attention_layer.key_projection(x_embedded).view(1, 10, 1, -1) torch.einsum("blhe,bshe->bhls", queries, keys).shape ``` ``` queries.shape ``` ``` class DataEmbedding_inverted(nn.Module): """ DataEmbedding_inverted """ def __init__(self, c_in, hidden_size, dropout=0.1): super(DataEmbedding_inverted, self).__init__() self.value_embedding = nn.Linear(c_in, hidden_size) self.dropout = nn.Dropout(p=dropout) def forward(self, x, x_mark): x = x.permute(0, 2, 1) # x: [Batch Variate Time] if x_mark is None: x = self.value_embedding(x) else: # the potential to take covariates (e.g. timestamps) as tokens x = self.value_embedding(torch.cat([x, x_mark.permute(0, 2, 1)], 1)) # x: [Batch Variate hidden_size] return self.dropout(x) ``` ``` i_de = DataEmbedding_inverted(10, hidden_size) i_enc_out = i_de(x, None) i_enc_out.shape ``` # Transformer Forecaster with neuralforecast ``` import os os.environ["NIXTLA_ID_AS_COL"] = "1" import datetime from typing import Optional import pandas as pd from loguru import logger ``` ## Load Data ``` data_source = "https://raw.githubusercontent.com/datumorphism/dataset-m5-simplified/b486cd6a3e183b80016a91ba0fd9b19493cdc587/dataset/m5_store_sales.csv" ``` ``` df = ( pd.read_csv(data_source, parse_dates=["date"]) .rename(columns={"date": "ds", "CA": "y"})[["ds", "y"]] .assign(unique_id=1) ) # - ``` ``` df.describe() ``` ``` import matplotlib.pyplot as plt import seaborn as sns from statsmodels.graphics.tsaplots import plot_acf sns.set_theme(context="paper", style="ticks", palette="colorblind") _, ax = plt.subplots(figsize=(10, 13), nrows=3) sns.lineplot(df, x="ds", y="y", color="k", ax=ax[0]) ax[0].set_title("Walmart Sales in CA") ax[0].set_ylabel("Sales") sns.lineplot( (df.loc[(df.ds >= "2015-01-01") & (df.ds < "2016-01-01")]), x="ds", y="y", color="k", ax=ax[1], ) ax[1].set_title("Walmart Sales in CA in 2015") ax[1].set_ylabel("Sales") plot_acf(df.y, ax=ax[2], color="k") ``` ## Prepare Data ``` df.ds.max(), df.ds.min() ``` ``` train_test_split_date = "2016-01-01" df_train = df[df.ds < train_test_split_date] df_test = df[(df.ds >= train_test_split_date)] horizon = 3 horizon ``` ## Baselines ``` from statsforecast import StatsForecast from statsforecast.arima import arima_string from statsforecast.models import AutoARIMA ``` ``` sf = StatsForecast( models=[ AutoARIMA( # season_length = 365.25 seasonal=False ) ], freq="d", ) ``` ``` sf.fit(df_train) ``` ``` def forecast_test( forecaster_pred: callable, df_train: pd.DataFrame, df_test: pd.DataFrame, ) -> pd.DataFrame: """Generate forecasts for tests :param forecaster_pred: forecasting function/method :param df_train: train dataframe :param df_test: test dataframe """ dfs_pred = [] for i in range(len(df_test)): logger.debug(f"Prediction Step: {i}") df_pred_input_i = pd.concat([df_train, df_test[:i]]).reset_index(drop=True) df_pred_output_i = forecaster_pred(df_pred_input_i) df_pred_output_i["step"] = i dfs_pred.append(df_pred_output_i) df_y_hat = pd.concat(dfs_pred) return df_y_hat ``` ``` def visualize_predictions( df_train: pd.DataFrame, df_test: pd.DataFrame, df_pred: pd.DataFrame, model_name: str, n_ahead: Optional[int] = None, title: Optional[str] = None, ax: Optional[plt.axes] = None, ) -> None: """ Visualizes the forecasts :param df_train: train dataframe :param df_test: test dataframe :param df_pred: prediction dataframe :param model_name: which model to visualize :param n_ahead: which future step to visualze :param title: title of the chart :param ax: matplotlib axes """ if ax is None: _, ax = plt.subplots(figsize=(10, 6.18)) sns.lineplot(df_train, x="ds", y="y", ax=ax) sns.lineplot(df_test, x="ds", y="y", color="k", ax=ax) if n_ahead is None: sns.lineplot( df_pred, x="ds", y=model_name, hue="step", linestyle="dashed", ax=ax ) else: dfs_pred_n_ahead = [] for i in df_pred.step.unique(): dfs_pred_n_ahead.append( df_pred.loc[df_pred.step == i].iloc[n_ahead - 1 : n_ahead] ) df_pred_n_ahead = pd.concat(dfs_pred_n_ahead) sns.lineplot(df_pred_n_ahead, x="ds", y=model_name, linestyle="dashed", ax=ax) ax.set_title("Sales Forecast" if title is None else title) ax.set_ylabel("Sales") ax.set_xlabel("Date") # ax.legend(prop={'size': 15}) # ax.grid() ``` ``` df_y_hat_arima = forecast_test( lambda x: sf.forecast(df=x, h=horizon), df_train=df_train, df_test=df_test ) df_y_hat_arima ``` ``` visualize_predictions( df_train=df_train, df_test=df_test, df_pred=df_y_hat_arima, model_name="AutoARIMA" ) ``` ``` visualize_predictions( df_train=df_train.loc[df_train.ds > "2015-01-01"], df_test=df_test, df_pred=df_y_hat_arima, model_name="AutoARIMA", ) ``` ``` visualize_predictions( df_train=df_train.loc[df_train.ds > "2015-01-01"], df_test=df_test, df_pred=df_y_hat_arima, model_name="AutoARIMA", n_ahead=1, ) ``` ``` visualize_predictions( df_train=df_train.loc[df_train.ds > "2015-01-01"], df_test=df_test, df_pred=df_y_hat_arima, model_name="AutoARIMA", n_ahead=2, ) ``` ``` visualize_predictions( df_train=df_train.loc[df_train.ds > "2015-01-01"], df_test=df_test, df_pred=df_y_hat_arima, model_name="AutoARIMA", n_ahead=3, title="Forecasting 3 Steps Ahead (ARIMA)", ) ``` ``` arima_string(sf.fitted_[0, 0].model_) ``` ## Transformers ``` from neuralforecast import NeuralForecast from neuralforecast.models import VanillaTransformer, iTransformer ``` ``` models = [ VanillaTransformer( hidden_size=128, n_head=4, learning_rate=0.0001, scaler_type="robust", max_steps=500, batch_size=32, windows_batch_size=512, random_seed=16, input_size=30, step_size=3, h=horizon, # **{'hidden_size': 128, # 'n_head': 4, # 'learning_rate': 0.00010614524276500768, # 'scaler_type': 'robust', # 'max_steps': 500, # 'batch_size': 32, # 'windows_batch_size': 512, # 'random_seed': 16, # 'input_size': 30, # 'step_size': 3, # "h": horizon, # } ), iTransformer( input_size=30, h=horizon, max_steps=50, n_series=1, ), ] nf = NeuralForecast(models=models, freq="d") ``` ``` nf.fit(df=df_train) ``` ``` df_y_hat_transformer = forecast_test(nf.predict, df_train=df_train, df_test=df_test) ``` ``` df_y_hat_transformer ``` ``` df_test ``` ``` df_y_hat_transformer.ds.dt.freq ``` ``` visualize_predictions( df_train=df_train, df_test=df_test, df_pred=df_y_hat_transformer, model_name="VanillaTransformer", ) ``` ``` visualize_predictions( df_train=df_train.loc[df_train.ds >= "2015-01-01"], df_test=df_test, df_pred=df_y_hat_transformer, model_name="VanillaTransformer", n_ahead=1, ) ``` ``` visualize_predictions( df_train=df_train.loc[df_train.ds >= "2015-01-01"], df_test=df_test, df_pred=df_y_hat_transformer, model_name="VanillaTransformer", n_ahead=2, ) ``` ``` visualize_predictions( df_train=df_train.loc[df_train.ds >= "2015-01-01"], df_test=df_test, df_pred=df_y_hat_transformer, model_name="VanillaTransformer", n_ahead=3, title="Forecasting 3 Steps Ahead (VanillaTransformer)", ) ``` ``` visualize_predictions( df_train=df_train.loc[df_train.ds >= "2015-01-01"], df_test=df_test, df_pred=df_y_hat_transformer, model_name="iTransformer", n_ahead=3, title="Forecasting 3 Steps Ahead (iTransformer)", ) ``` ## Evaluations ``` from utilsforecast.evaluation import evaluate from utilsforecast.losses import mae, mse, rmse ``` ``` def evaluate_step(df_pred: pd.DataFrame, df_true: pd.DataFrame) -> pd.DataFrame: """Metrics averaged over all series, one column per model.""" df = df_pred.merge(df_true, on=["unique_id", "ds"], how="left") models = [ c for c in df.columns if c not in ("unique_id", "ds", "y", "step", "index") ] return evaluate(df, metrics=[mse, mae, rmse], models=models, agg_fn="mean") ``` ``` df_y_hat_transformer.loc[df_y_hat_transformer.step == 0] ``` ``` df_test ``` ``` df_y_hat_transformer.loc[df_y_hat_transformer.step == 0] ``` ``` transformer_evals = [] for s in df_y_hat_transformer.step.unique(): df_transformer_eval_s = evaluate_step( df_y_hat_transformer.loc[df_y_hat_transformer.step == s], df_test ) df_transformer_eval_s["step"] = s transformer_evals.append(df_transformer_eval_s) df_transformer_eval = pd.concat(transformer_evals) df_transformer_eval.head() ``` ``` baseline_evals = [] for s in df_y_hat_arima.step.unique(): df_baseline_eval_s = evaluate_step( df_y_hat_arima.loc[df_y_hat_arima.step == s], df_test ) df_baseline_eval_s["step"] = s baseline_evals.append(df_baseline_eval_s) df_baseline_eval = pd.concat(baseline_evals) df_baseline_eval.head() ``` ``` df_eval_metrics = pd.merge( df_transformer_eval, df_baseline_eval, how="left", on=["metric", "step"] ).melt( id_vars=["metric", "step"], value_vars=[ "VanillaTransformer", "iTransformer", "AutoARIMA", ], var_name="model", ) df_eval_metrics ``` ``` _, ax = plt.subplots(figsize=(13, 5), ncols=3) for i, m in enumerate(df_eval_metrics.metric.unique()): sns.violinplot( df_eval_metrics.loc[df_eval_metrics.metric == m], x="model", y="value", hue="model", fill=False, ax=ax[i], label=m, ) ax[i].set_title(f"Metric: {m}") ``` ``` _, ax = plt.subplots(figsize=(10, 13), nrows=3) visualize_predictions( df_train=df_train.loc[df_train.ds > "2015-01-01"], df_test=df_test, df_pred=df_y_hat_arima, model_name="AutoARIMA", n_ahead=3, title="Forecasting 3 Steps Ahead (ARIMA)", ax=ax[0], ) visualize_predictions( df_train=df_train.loc[df_train.ds >= "2015-01-01"], df_test=df_test, df_pred=df_y_hat_transformer, model_name="VanillaTransformer", n_ahead=3, title="Forecasting 3 Steps Ahead (VanillaTransformer)", ax=ax[1], ) visualize_predictions( df_train=df_train.loc[df_train.ds >= "2015-01-01"], df_test=df_test, df_pred=df_y_hat_transformer, model_name="iTransformer", n_ahead=3, title="Forecasting 3 Steps Ahead (iTransformer)", ax=ax[2], ) ``` # Transformer Forecaster with neuralforecast ``` import matplotlib.pyplot as plt ``` ``` import pandas as pd import seaborn as sns sns.set_theme(context="paper", style="ticks", palette="colorblind") ``` ## Load Data ``` data_source = "https://gist.githubusercontent.com/emptymalei/15e548f483e896be0afc99e49dd6fbc9/raw/8384d82cdaaed4d9b0a555888efb70d79911dd2a/sunspot_nixtla.csv" df = pd.read_csv(data_source, parse_dates=["ds"]) ``` ``` df.describe() ``` ``` _, ax = plt.subplots() sns.lineplot(df, x="ds", y="y", ax=ax) ax.set_title("Sunspot Time Series") ax.set_ylabel("Sunspot Number") ``` ## Prepare Data ``` train_test_split_date = "2000-01-01" df_train = df[df.ds <= train_test_split_date] df_test = df[df.ds > train_test_split_date] horizon = 3 horizon ``` ## Baselines ``` from statsforecast import StatsForecast from statsforecast.models import AutoARIMA ``` ``` sf = StatsForecast(models=[AutoARIMA(season_length=12)], freq="YS") ``` ``` sf.fit(df_train) ``` ``` def forecast_test(forecaster_pred, df_train, df_test): dfs_pred = [] for i in range(len(df_test)): df_pred_input_i = pd.concat([df_train, df_test[:i]]) print(df_pred_input_i.ds.max()) df_pred_output_i = forecaster_pred(df_pred_input_i) df_pred_output_i["step"] = i dfs_pred.append(df_pred_output_i) df_y_hat = pd.concat(dfs_pred).reset_index(drop=False) return df_y_hat ``` ``` def visualize_predictions( df_train: pd.DataFrame, df_test: pd.DataFrame, df_pred: pd.DataFrame, model_name: str, ): _, ax = plt.subplots() sns.lineplot(df_train, x="ds", y="y", ax=ax) sns.lineplot(df_test, x="ds", y="y", color="k", ax=ax) sns.lineplot(df_pred, x="ds", y=model_name, hue="step", ax=ax) ax.set_title("Sunspot Forecast", fontsize=22) ax.set_ylabel("Sunspot Number", fontsize=20) ax.set_xlabel("Year", fontsize=20) ax.legend(prop={"size": 15}) ax.grid() ``` ``` df_y_hat_arima = forecast_test( lambda x: sf.predict(h=horizon, level=[95]), df_train=df_train, df_test=df_test ) ``` ``` visualize_predictions( df_train=df_train, df_test=df_test, df_pred=df_y_hat_arima, model_name="AutoARIMA" ) ``` ``` import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(20, 7)) df_chart = df_test.merge(df_y_hat_arima, how="left", on=["unique_id", "ds"]) df_chart = pd.concat([df_train, df_chart]).set_index("ds") df_chart[ [ "y", "AutoARIMA", # 'NHITS' ] ].plot(ax=ax, linewidth=2) ax.set_title("AirPassengers Forecast", fontsize=22) ax.set_ylabel("Monthly Passengers", fontsize=20) ax.set_xlabel("Timestamp [t]", fontsize=20) ax.legend(prop={"size": 15}) ax.grid() ``` ## Transformers ``` from neuralforecast import NeuralForecast from neuralforecast.models import NBEATS, NHITS, VanillaTransformer, iTransformer ``` ``` models = [ VanillaTransformer( # input_size=9, h=horizon, # n_head=4, # windows_batch_size=512, # learning_rate=0.00010614524276500768, # # conv_hidden_size=2, # # encoder_layers=6, # max_steps=500, # #early_stop_patience_steps=5, **{ "hidden_size": 128, "n_head": 4, "learning_rate": 0.00010614524276500768, "scaler_type": "robust", "max_steps": 500, "batch_size": 32, "windows_batch_size": 512, "random_seed": 16, "input_size": 30, "step_size": 3, "h": horizon, } ), # iTransformer( # input_size=history_length, h=horizon, # # n_head=1, # # conv_hidden_size=1, # # encoder_layers=6, # max_steps=50, # n_series=1, # #early_stop_patience_steps=5, # ), # NBEATS(input_size=history_length, h=horizon, max_steps=100, #early_stop_patience_steps=5 # ), # NHITS(input_size=history_length, h=horizon, max_steps=100, #early_stop_patience_steps=5 # ) ] nf = NeuralForecast(models=models, freq="YS") ``` ``` nf.fit(df=df_train) ``` ``` train_test_split_date ``` ``` dfs_pred = [] for i in range(len(df_test)): df_pred_input_i = pd.concat([df_train, df_test[:i]]) df_pred_output_i = nf.predict(df_pred_input_i) df_pred_output_i["step"] = i dfs_pred.append(df_pred_output_i) df_y_hat = pd.concat(dfs_pred).reset_index(drop=False) ``` ``` df_y_hat ``` ``` df_test ``` ``` df_y_hat.ds.dt.freq ``` ``` import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(20, 7)) sns.lineplot(df_train, x="ds", y="y", ax=ax) sns.lineplot(df_test, x="ds", y="y", color="k", ax=ax) sns.lineplot(df_y_hat, x="ds", y="VanillaTransformer", hue="step", ax=ax) ax.set_title("Sunspot Forecast", fontsize=22) ax.set_ylabel("Avg Sunspot Area", fontsize=20) ax.set_xlabel("Year", fontsize=20) ax.legend(prop={"size": 15}) ax.grid() ``` ``` from utilsforecast.evaluation import evaluate from utilsforecast.losses import mae, mse, rmse ``` ``` df_y_hat.loc[df_y_hat.step == 0] ``` ``` df_test ``` ``` df_eval_input = df_y_hat.loc[df_y_hat.step == 0].merge( df_test, on=["unique_id", "ds"], how="left" ) evaluation_df = evaluate( df_eval_input, metrics=[mse, mae, rmse], models=[ c for c in df_eval_input.columns if c not in ("unique_id", "ds", "y", "step", "index") ], ) evaluation_df.head() ``` # Transformer Forecaster with neuralforecast ``` import pandas as pd import seaborn as sns ``` ## Load Data ``` data_source = "https://gist.githubusercontent.com/emptymalei/921a624ce44e6a60bb6ec637b195ceaf/raw/4cb52fa20dcc598e16891eae2749fd96a97750e9/sunspot.csv" df = ( pd.read_csv(data_source, parse_dates=["date"]) .rename(columns={"date": "ds", "avg_sunspot_area": "y"}) .assign(unique_id=1) ) ``` ``` df.describe() ``` ``` df.plot(x="ds", y="y") ``` ## Prepare Data ``` train_test_split_date = "2000-01-01" df_train = df[df.ds <= train_test_split_date] df_test = df[df.ds > train_test_split_date] horizon = 3 horizon ``` ## Baselines ``` from statsforecast import StatsForecast from statsforecast.models import AutoARIMA ``` ``` sf = StatsForecast(models=[AutoARIMA(season_length=12)], freq="YS") ``` ``` sf.fit(df_train) ``` ``` df_y_hat_arima = sf.predict(h=horizon, level=[95]) df_y_hat_arima ``` ``` import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(20, 7)) df_chart = df_test.merge(df_y_hat_arima, how="left", on=["unique_id", "ds"]) df_chart = pd.concat([df_train, df_chart]).set_index("ds") df_chart[ [ "y", "AutoARIMA", # 'NHITS' ] ].plot(ax=ax, linewidth=2) ax.set_title("AirPassengers Forecast", fontsize=22) ax.set_ylabel("Monthly Passengers", fontsize=20) ax.set_xlabel("Timestamp [t]", fontsize=20) ax.legend(prop={"size": 15}) ax.grid() ``` ## Transformers ``` from neuralforecast import NeuralForecast from neuralforecast.auto import AutoVanillaTransformer from neuralforecast.models import NBEATS, NHITS, VanillaTransformer, iTransformer ``` ``` # vt_config = dict( # max_steps=1, val_check_steps=1, input_size=12, hidden_size=8 # ) auto_vt_model = AutoVanillaTransformer(h=horizon, backend="optuna") nf_auto = NeuralForecast(models=[auto_vt_model], freq="YS") ``` ``` nf_auto.fit(df=df_train, val_size=3) ``` ``` results = nf_auto.models[0].results.trials_dataframe() results.drop(columns="user_attrs_ALL_PARAMS") ``` ``` df_y_hat_optuna = nf_auto.predict().reset_index() df_y_hat_optuna.head() ``` ``` import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(20, 7)) df_chart = df_test.merge(df_y_hat_optuna, how="left", on=["unique_id", "ds"]) df_chart = pd.concat([df_train, df_chart]).set_index("ds") df_chart[ [ "y", "AutoVanillaTransformer", ] ].plot(ax=ax, linewidth=2) ax.set_title("Forecast", fontsize=22) ax.set_ylabel("Sunspot Area", fontsize=20) ax.set_xlabel("Timestamp [t]", fontsize=20) ax.legend(prop={"size": 15}) ax.grid() ``` ``` nf_auto.models[0].results.best_trial.params ``` ``` # nf_auto.save("lightning_logs/nf_auto_vanilla_transformer_sunspot") ``` ## Transformers ``` models = [ VanillaTransformer( # input_size=9, h=horizon, # n_head=4, # windows_batch_size=512, # learning_rate=0.00010614524276500768, # # conv_hidden_size=2, # # encoder_layers=6, # max_steps=500, # #early_stop_patience_steps=5, **{ "hidden_size": 128, "n_head": 4, "learning_rate": 0.00010614524276500768, "scaler_type": "robust", "max_steps": 500, "batch_size": 32, "windows_batch_size": 512, "random_seed": 16, "input_size": 30, "step_size": 3, "h": horizon, } ), # iTransformer( # input_size=history_length, h=horizon, # # n_head=1, # # conv_hidden_size=1, # # encoder_layers=6, # max_steps=50, # n_series=1, # #early_stop_patience_steps=5, # ), # NBEATS(input_size=history_length, h=horizon, max_steps=100, #early_stop_patience_steps=5 # ), # NHITS(input_size=history_length, h=horizon, max_steps=100, #early_stop_patience_steps=5 # ) ] nf = NeuralForecast(models=models, freq="YS") ``` ``` nf.fit(df=df_train) ``` ``` train_test_split_date ``` ``` dfs_pred = [] for i in range(len(df_test)): df_pred_input_i = pd.concat([df_train, df_test[:i]]) df_pred_output_i = nf.predict(df_pred_input_i) df_pred_output_i["step"] = i dfs_pred.append(df_pred_output_i) df_y_hat = pd.concat(dfs_pred).reset_index(drop=False) ``` ``` df_y_hat ``` ``` df_test ``` ``` df_y_hat.ds.dt.freq ``` ``` import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(20, 7)) sns.lineplot(df_train, x="ds", y="y", ax=ax) sns.lineplot(df_test, x="ds", y="y", color="k", ax=ax) sns.lineplot(df_y_hat, x="ds", y="VanillaTransformer", hue="step", ax=ax) ax.set_title("Sunspot Forecast", fontsize=22) ax.set_ylabel("Avg Sunspot Area", fontsize=20) ax.set_xlabel("Year", fontsize=20) ax.legend(prop={"size": 15}) ax.grid() ``` ``` from utilsforecast.evaluation import evaluate from utilsforecast.losses import mae, mse, rmse ``` ``` df_y_hat.loc[df_y_hat.step == 0] ``` ``` df_test ``` ``` df_eval_input = df_y_hat.loc[df_y_hat.step == 0].merge( df_test, on=["unique_id", "ds"], how="left" ) evaluation_df = evaluate( df_eval_input, metrics=[mse, mae, rmse], models=[ c for c in df_eval_input.columns if c not in ("unique_id", "ds", "y", "step", "index") ], ) evaluation_df.head() ``` # Transformer Forecaster with neuralforecast ``` import pandas as pd from ts_dl_utils.datasets.pendulum import Pendulum ``` ## Load Data ``` pen = Pendulum(length=100) df_pen = ( pd.DataFrame(pen(10, 400, initial_angle=1, beta=0.00001)) .reset_index() .rename(columns={"index": "ds", "theta": "y"})[["ds", "y"]] ) df_pen["unique_id"] = 1 df_pen.head() ``` ``` df_pen.plot(x="ds", y="y") ``` ``` df_pen_train = df_pen[:-3] df_pen_test = df_pen[-3:] horizon_pen = len(df_pen_test) ``` ## Prepare Data ## Baselines ``` from statsforecast import StatsForecast from statsforecast.models import AutoARIMA ``` ``` sf_pen = StatsForecast(models=[AutoARIMA(season_length=12)], freq=1) ``` ``` sf_pen.fit(df_pen_train) ``` ``` df_pen_y_hat_arima = sf_pen.predict(h=horizon_pen, level=[95]) df_pen_y_hat_arima ``` ``` _, ax = plt.subplots() df_pen_test.plot(x="ds", y="y", ax=ax) df_pen_y_hat_arima.plot(x="ds", y="AutoARIMA", ax=ax) ``` ## Transformers ``` from neuralforecast import NeuralForecast from neuralforecast.auto import AutoVanillaTransformer from neuralforecast.models import NBEATS, NHITS, VanillaTransformer, iTransformer history_length_pen = 10 ``` ``` models_pen = [ VanillaTransformer( input_size=history_length_pen, h=horizon_pen, n_head=1, conv_hidden_size=1, encoder_layers=6, max_steps=100, # early_stop_patience_steps=5, ), # iTransformer( # input_size=history_length, h=horizon, # # n_head=1, # # conv_hidden_size=1, # # encoder_layers=6, # max_steps=50, # n_series=1, # #early_stop_patience_steps=5, # ), # NBEATS(input_size=history_length, h=horizon, max_steps=100, #early_stop_patience_steps=5 # ), # NHITS(input_size=history_length, h=horizon, max_steps=100, #early_stop_patience_steps=5 # ) ] nf_pen = NeuralForecast(models=models_pen, freq=1) ``` ``` nf_pen.fit(df=df_pen_train) ``` ``` df_pen_y_hat = nf_pen.predict().reset_index() ``` ``` import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(20, 7)) df_chart = df_pen_test.merge(df_pen_y_hat, how="left", on=["unique_id", "ds"]) df_chart = pd.concat([df_pen_train, df_chart]).set_index("ds") df_chart[ [ "y", # 'NBEATS', "VanillaTransformer", # "iTransformer" # 'NHITS' ] ].plot(ax=ax, linewidth=2) ax.set_title("AirPassengers Forecast", fontsize=22) ax.set_ylabel("Monthly Passengers", fontsize=20) ax.set_xlabel("Timestamp [t]", fontsize=20) ax.legend(prop={"size": 15}) ax.grid() ``` # History of Transformer for Forecasting **This is a temporary notebook to produce figures for my book.** ``` import datetime import json ``` ``` from pathlib import Path import matplotlib.pyplot as plt import networkx as nx import numpy as np import pandas as pd data_path = Path("data/transformer-and-forecasting-papers.json") ``` ``` with open(data_path, "r") as fp: data = json.load(fp) ``` ``` tags = ( pd.read_csv("data/transformer-and-forecasting-papers.csv") .set_index("LitmapsId") .Tags.to_dict() ) ``` ``` # labels = { # i["id"]: { # "first_author_last": i.get("authorString", "").split(", ")[0].split(" ")[-1], # "arxiv_id": i.get("arxivIds", ""), # "year": datetime.datetime.strptime(i["publicationDate"], "%Y-%m-%dT%H:%M:%SZ").year # } # for i in # data["items"] # } ``` ``` data["items"][0] ``` ``` {'magIds': [2950075624, 2604847698], 'openAccessUrl': 'http://arxiv.org/pdf/1703.07015', 'forwardEdgeCount': 1155, 'arxivIds': ['1703.07015'], 'semanticScholarIds': ['5f6c1b0a780cbaae92f6169312b7441decc9d6ef'], 'abstract': 'Multivariate time series forecasting is an important machine learning problem across many domains, including predictions of solar plant energy output, electricity consumption, and traffic jam situation. Temporal data arise in these real-world applications often involves a mixture of long-term and short-term patterns, for which traditional approaches such as Autoregressive models and Gaussian Process may fail. In this paper, we proposed a novel deep learning framework, namely Long- and Short-term Time-series network (LSTNet), to address this open challenge. LSTNet uses the Convolution Neural Network (CNN) and the Recurrent Neural Network (RNN) to extract short-term local dependency patterns among variables and to discover long-term patterns for time series trends. Furthermore, we leverage traditional autoregressive model to tackle the scale insensitive problem of the neural network model. In our evaluation on real-world data with complex mixtures of repetitive patterns, LSTNet achieved significant performance improvements over that of several state-of-the-art baseline methods. All the data and experiment codes are available online.', 'createdAt': '2022-08-07T08:10:31Z', 'doctype': 'proceedings-article', 'updatedAt': '2023-04-07T04:34:50Z', 'backwardEdges': '261049465,5935507,261363334,261162486,157805404,260062840,218776176,38902622,54138891,261322489,109932487,141077332,56944353,186987285,3661079,156918705,260926259,82450983,193806104,226993850,151089196,262506487,200236775,261268342,99123768,81776371,34761083,229840453,231518444,11656072,1554017,236786244', 'title': 'Modeling Long- and Short-Term Temporal Patterns with Deep Neural Networks', 'authorString': 'Guokun Lai, Wei-Cheng Chang, Yiming Yang, Hanxiao Liu', 'forwardEdges': '221642619,6286900,80380256,262674364,252076917,239497520,261150996,254941680,265392483,253391742,265096386,106810315,230675472,207339745,252317180,263947205,142618366,266352624,79397206,262222458,93215932,182861623,228072741,110969273,262153954,125095652,109763200,261194615,244703752,255221595,231692199,203506478,235707813,182320543,262265481,265309030,251149404,262880262,270882613,268061560,95091786,154686065,234280352,60602649,274721954,175175152,119245249,21393228,2587812,267884388,252477673,261950227,249883370,24916588,265913734,17019162,247241424,254132436,253551086,235256328,242287182,254892712,258504154,194265399,250814422,209152201,252847711,231190433,253544128,167430063,254520070,180965237,19529456,32598082,67954905,228081358,110735604,33550925,246328067,5713308,9803235,241998679,252551779,77881512,12315090,53137846,52008830,266468869,271012849,272300227,254240641,42122221,36621371,237604573,112425268,252302772,266484941,258187014,71635849,257548491,107192796,220666655,244766020,206152189,250053673,241142841,265066879,274856422,237650736,74088895,272201550,273262955,261254941,252779090,261437229,251779312,254318374,251798790,193413518,264334015,270044962,209486409,201893552,270490993,23896072,125300430,122613716,84298626,108089670,239525085,123480765,248596988,3526387,58950698,274697207,251832286,262728895,266266074,274312722,265383336,252070573,270429190,253146655,255260085,230099702,261765479,24452496,255259985,125854482,220047187,253275678,264595987,264899613,107824225,252471420,232914184,244379417,261338829,274645015,241043988,271333934,86249841,42230671,91126049,260177699,270628502,263916257,255275208,91850631,143515848,261755471,275408968,275424307,263887586,265740713,252200438,266298914,235760608,103588300,257277176,260896247,39128538,9266606,273391670,235636988,145250090,994843,146472279,267434410,261795519,145682764,267525326,267255899,242754082,84993427,239507172,264974833,264303360,269470162,264115419,262297986,273538123,261978790,269848828,275011491,89210476,251160611,251622780,202508733,265613877,269750779,263201962,251481277,255751416,250630275,237728648,267778646,69522787,188561892,256257860,258899169,18369011,248288309,116692188,252736416,241038374,275361289,275196041,54883165,261340984,255439452,265861247,247443431,213827552,254931422,240286413,245749618,35478828,271443202,251644654,251473466,171133249,230214632,231828379,216258979,261980168,242837102,261836443,265388605,262675271,265959857,65819410,271960371,188464129,255233568,232739363,263855963,260874160,263470941,76568457,99933498,251439176,266362761,252459168,258955488,251697231,48084207,266961435,56242351,157234000,266235985,149448838,264978523,261334371,233401811,157618138,31203156,230822897,161651329,63373451,261949233,249724726,87992217,195701402,273979222,263823102,22476828,19277786,231008325,262371659,265235239,251626560,225831456,168325657,14556153,232194439,253144871,252465232,265212455,267886343,263323403,255078716,17104083,126648443,273929287,60402076,252611610,187433581,126446883,265223486,236764898,260497830,253369564,264203372,243716292,41775115,245243081,66039759,249666113,52018580,263595739,259236029,262925711,274277706,265964796,57627486,265719913,72796541,253844874,247706300,60906063,241772058,204896543,150555843,1789632,261179254,3561791,267633484,107814846,177389122,90524420,272112450,265635739,129369190,264832605,265793077,249954902,263160642,59387536,107465724,238937501,118125972,239619553,72701607,173521144,203311101,265575129,249718937,262982677,242427680,255616280,161512930,254180257,231784291,237734649,13660116,193793232,263318226,186166076,259857907,274221150,266191511,239331200,178021248,255416867,244372069,255107638,255230696,262337227,114559990,60405867,59135629,194486293,15704901,255497841,269747409,36147288,252197248,248141832,253794211,273423422,269682070,260779304,254559063,234332676,264540324,234919167,236418899,262352481,184142447,269609664,254130762,269225635,252881497,56370609,101743710,241097374,266441946,67983700,264733075,275253596,123804454,81111506,182947274,91428797,269211585,254662739,252182957,250052643,261084259,250573474,242915203,126676565,231920951,71555505,253560789,251777655,248283880,251394194,14934095,137880252,42573673,266482927,248479069,211014625,257932713,256110083,265024567,120073159,179543762,11347949,231349177,263199093,142540232,261868988,249822015,207749195,273627830,240661443,262977318,265318928,234497838,238764762,5101659,243304503,230478422,242346528,213413513,233689909,263143886,12490287,251508258,272778373,274543830,187111578,261954953,250574902,262215752,246250836,254193417,128175980,255070271,62177171,53695411,254171576,171594690,55577967,265907987,263061060,261498377,262185545,79995404,267825179,46159817,32918152,30314775,266567405,254011319,263553866,7920073,260973719,243612682,251097202,261641615,244875547,240202600,250011540,123521271,265201075,231773006,254427911,252641206,262967490,26067444,270832156,136926389,275438144,250751030,205157378,257155004,253173152,265681807,47757291,31360219,74997292,164635841,255264797,255193309,66632812,265582831,261654044,251909806,119619556,264813590,16087562,255763156,233339562,14224493,251954730,264979365,265458368,24824699,251378396,255037269,262021454,261781993,251473676,262250717,252536314,141779747,66473176,58600619,265386708,167779295,56511502,198637393,213373593,132550752,266333636,262744837,132818940,204973444,252808194,261088800,1193942,43720684,78873840,268184306,260774926,255539801,97096392,245233254,265014693,233016588,265445566,266579433,186859831,188063741,177905414,251016819,264294534,241003981,236004746,126947845,74558692,202723708,254487114,3787723,104764033,256417132,275477379,272689551,261756124,232023240,268751234,57011084,261041518,264763373,60181455,144338145,266551342,182988547,62239207,265968709,266577912,43745177,211630216,197299271,153675230,120707123,243573595,273987688,247331871,275295677,253725407,153169482,191888775,253723375,263365672,266424366,235400352,225997466,152047879,262238697,198552234,266357126,261989656,112101471,250638532,266133806,265472365,83288133,263898320,38897726,255883745,250089832,251392680,243596106,32524570,9978258,134736326,275329388,265503695,268913758,234000709,254427532,271692696,254833761,254193618,21527043,264874046,265232894,15275893,271923223,261994746,19675305,157718130,272792298,185655375,249272101,263848656,261057001,251351978,261480014,263822938,263836913,48611806,215476993,265318868,523776,252737620,184868594,253451539,251839056,246561320,255748671,111585364,265206373,216313283,261647409,240767488,128181995,265599601,264949622,26596432,159688352,253542174,66593623,265183299,112783115,227454800,234908898,223508723,105242686,265170794,253565669,262130554,249778931,242662433,266222232,213043614,77197275,254176086,255102665,246765648,109971251,274149418,237645496,232729923,65640920,254970998,135510400,34659873,264090950,168003899,233503231,262041504,247305660,106303313,253817740,154647613,266203381,215132465,254046922,173176925,236050855,252789766,266624237,128204893,274917569,261647514,269777418,128959747,249821301,271835220,34268767,91263777,262669844,230713698,244939290,169186426,53234892,190217030,258913634,251293801,254310811,261721761,265923415,255071524,270308802,261975618,252397892,262670852,275386127,115279283,264824911,81566448,163146662,224670538,230415865,269307479,36126463,216801127,249249015,232245643,261647513,274084193,169088779,262543639,208043700,230830737,255238844,270020836,275118747,253576948,249825208,132497081,251757970,89736250,234591351,264923958,191807908,245497390,240120085,158968181,77500312,11330721,248897530,34778175,270564625,87950297,183579980,274987557,205762618,272690244,246244640,254906531,218054861,251648565,268505112,272003803,124229410,263558711,251585077,255256595,261314282,103918353,254734831,133695824,265613944,272379479,231034328,199738730,267506854,263885751,268440525,230567670,2796538,249074601,1930634,255600756,170925467,261072186,274140016,238013596,273839424,275472081,217448095,251143609,260910409,87845742,42270254,137691725,272052438,253121626,250064327,8424213,69566710,204809087,266405556,255749185,271222403,132669872,262882086,62275312,173384999,249455870,251090072,244490041,251691365,261185298,227694634,266857982,127371193,253467953,168678780,270110295,255298418,249062707,257586376,267358679,255179833,265438331,104528272,17145820,179627892,154013406,275336236,248627991,270570110,149296187,237918942,62748911,26224584,255586689,265133556,264653626,272837082,265869906,252039880,266022359,263276446,72103548,233484588,252819553,265425214,263296701,265555932,178600651,269841098,255600960,189527501,265437297,265889418,255298317,253541266,4000773,142275761,244065818,235668288,41000170,250567248,262343642,255724133,268181655,251790361,175042108,261888365,256748570,265818672,191497623,254557512,255215541,139938530,250881218,271110639,274065154,269158168,269072524,160852144,39479851,255174921,252395421,259407284,269137803,253739073,99299541,212336312,117263822,248568063,211488550,274694140,263526284,273862485,265980448,99442779,268080340,255214457,246864439,252458106,236743576,131584116,8199357,248551344,139604581,269536337,265092884,240857766,88343517,187988864,44356795,84259012,116959493,273986426,90207875,261709422,232299255,265069454,250424445,240361042,248895605,25983185,249828043,38536087,265562928,255206662,240543570,273005077,144464847,253810441,259658908,176191006,261713495,258238193,254887135,196054983,254236794,232072660,265084577,253197901,253822524,263122476,251654028,224829998,231910215,265453713,107621714,250495954,254319082,243663991,225399199,25784830,245104393,251061016,2122047,273976514,247120261,259898699,265416458,235966976,267079518,248068484,243810584,165243890,30523140,254576912,260704155,240556526,275294017,118071564,275359206,103982468,96756871,47423297,59138429,251908240,238324461,252172195,265007575,251414185,37140476,72017013,275428783,255583029,265967279,245354934,183302998,249353308,261426024,255288146,108793908,250861702,192159622,186997315,251957618,251304293,271984942,240771011,250818048,94128815,232868569,255241792,255222751,172167480,261974392,253219765,178373821,255641656,152236990,266947244,9309766,191432817,230635040,246736146,181224946,56649553,107963401,38164872,253544854,254176881,101749896,268273325,255659011,262971110,172138793,95022518,264795847,165841545,261546724,248376678,269965939,236300029,234559116,274960479,249713138,132217931,256651175,269218623,228057580,221696167,82551623,265476213,115223533,230331157,18082250,48071248,30350873,7083063,263437817,252019219,263181603,263864613,231754113,118177857,236800941,33429054,252788419,253437505,253257324,273809106,255277094,58442612,133878487,255280094,261188362,221466276,270173407,124304669,132446472,233471446,191873621,254287052,261861530,254289209,262579020,268526213,264489351,252878723,159618840,274912635,231104324,254032046,265464344,71528212,247529798,26370465,264873333,194225784,261730877,271049614,104323748,211546170,108408072,251914127,249726384,265265668,270347363,109658732,254439164,53916720,260433482,254900459,252464743,34482798,267242190,255755188,237526496,85580415,263155915,255748742,264024834,237979781,264428906,264557954,227076626,257674958,265414278,70502772,239412092,46993775,205287681,250936845,33185724,10294002,249534665', 'dois': ['10.1145/3209978.3210006'], 'url': 'https://doi.org/10.1145/3209978.3210006', 'backwardEdgeCount': 32, 'id': 123919995, 'publicationDate': '2018-06-27T00:00:00Z', 'openAlexIds': ['W2604847698'], 'semanticScholarCorpusIds': [4922476, 4922476]} ``` ``` min_date = min( [ datetime.datetime.strptime( i["publicationDate"], "%Y-%m-%dT%H:%M:%SZ" ).toordinal() for i in data["items"] ] ) ``` ``` rng = np.random.default_rng(42) coordinate_calculator = lambda i: np.array( [ np.log( datetime.datetime.strptime( i["publicationDate"], "%Y-%m-%dT%H:%M:%SZ" ).toordinal() ), ( np.log(1 + i.get("forwardEdgeCount", 0)) * (1 + rng.random() * 0.2) if i.get("forwardEdgeCount", 0) > 50 else np.log(1 + i.get("forwardEdgeCount", 0)) + rng.random() * 3 ), ] ) coordinates = {i["id"]: coordinate_calculator(i) for i in data["items"]} color_calculator = lambda i: "black" if "Foundation Model" in tags[i["id"]] else "red" marker_calculator = lambda i: "s" if "Foundation Model" in tags[i["id"]] else "o" node_size_calculator = lambda x: 10 + 30 * np.log(1 + x) ``` ``` G = nx.Graph() for i in data["items"]: G.add_node( i["id"], forwardEdgeCount=i.get("forwardEdgeCount", 0), coordinate=coordinates[i["id"]], color=color_calculator(i), marker=marker_calculator(i), size=node_size_calculator(i.get("forwardEdgeCount", 0)), first_author_last=i.get("authorString", "").split(", ")[0].split(" ")[-1], arxiv_id=i.get("arxivIds", ""), year=datetime.datetime.strptime( i["publicationDate"], "%Y-%m-%dT%H:%M:%SZ" ).year, title=i["title"], ) for b in i.get("backwardEdges", "").split(","): try: if int(b) in data["ids"]: G.add_edge(i["id"], int(b)) except ValueError as e: print(f"{b}: {e}") ``` ``` : invalid literal for int() with base 10: '' ``` ``` transformer_origin_id = 261105339 # title_labels = { # i["id"]: i["title"] # for i in # data["items"] # if i.get("forwardEdgeCount",0) >= 1000 # } ``` ``` fig, ax = plt.subplots(figsize=(25, 25)) node_size_calculator = lambda x: 10 + 30 * np.log(1 + x) nx.draw_networkx_edges(G, coordinates, edge_color="lightgray") # Draw the nodes with different markers effective_nodes = [] for node in G.nodes: try: nx.draw_networkx_nodes( G, pos=coordinates, nodelist=[node], node_size=G.nodes.get(node).get("size"), node_shape=G.nodes.get(node).get("marker"), node_color=G.nodes.get(node).get("color"), ) effective_nodes.append(node) except IndexError as e: print(f"{node}: {e}") for node in effective_nodes: x, y = G.nodes.get(node).get("coordinate") first_author_last = G.nodes.get(node).get("first_author_last") year = G.nodes.get(node).get("year") plt.text(x, y + 0.1, f"{first_author_last} {year}", horizontalalignment="center") for node in effective_nodes: node_citations = G.nodes.get(node).get("forwardEdgeCount") if node_citations >= 1000: node_title = G.nodes.get(node).get("title") plt.text( coordinates[node][0], coordinates[node][1] - 0.3, node_title, horizontalalignment="center", ) plt.axis("off") fig.savefig( "results/transformer_history/transformer_ts_papers.png", bbox_inches="tight", pad_inches=-0.5, # transparent=True ) ``` ![output]() We need a version that is easier to read on print outs ``` fig, ax = plt.subplots(figsize=(25, 25)) node_size_calculator = lambda x: 10 + 30 * np.log(1 + x) nx.draw_networkx_edges(G, coordinates, edge_color="lightgray") # Draw the nodes with different markers effective_nodes = [] for node in G.nodes: try: nx.draw_networkx_nodes( G, pos=coordinates, nodelist=[node], node_size=G.nodes.get(node).get("size"), node_shape=G.nodes.get(node).get("marker"), node_color=G.nodes.get(node).get("color"), ) effective_nodes.append(node) except IndexError as e: print(f"{node}: {e}") for node in effective_nodes: x, y = G.nodes.get(node).get("coordinate") first_author_last = G.nodes.get(node).get("first_author_last") year = G.nodes.get(node).get("year") # plt.text(x, y + 0.1, f"{first_author_last} {year}", horizontalalignment="center") for node in effective_nodes: node_citations = G.nodes.get(node).get("forwardEdgeCount") if node_citations >= 1000: node_title = G.nodes.get(node).get("title") plt.text( coordinates[node][0], coordinates[node][1] - 0.3, node_title, horizontalalignment="center", fontdict={"size": 30}, ) plt.axis("off") fig.savefig( "results/transformer_history/transformer_ts_papers_no_labels.png", bbox_inches="tight", pad_inches=-0.5, # transparent=True ) ``` ![output]() ## Table ``` df = pd.DataFrame(data["items"]).rename( columns={ "forwardEdgeCount": "citations", "authorString": "authors", } ) df["year"] = df.publicationDate.apply( lambda x: datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%SZ").year ) df.fillna({"citations": 0}, inplace=True) df = df.astype(dtype={"citations": int})[["title", "authors", "citations", "year"]] df.sort_values(by="year", inplace=True) ``` ``` print(df.to_markdown()) ``` > [!NOTE] > > **Output (47 lines)** > > ``` > | | title | authors | citations | year | > |---:|:------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------|------------:|-------:| > | 19 | Attention is All you Need | Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin | 52657 | 2017 | > | 0 | Modeling Long- and Short-Term Temporal Patterns with Deep Neural Networks | Guokun Lai, Wei-Cheng Chang, Yiming Yang, Hanxiao Liu | 1155 | 2018 | > | 18 | Enhancing the Locality and Breaking the Memory Bottleneck of Transformer on Time Series Forecasting. | Shiyang Li, Xiaoyong Jin, Yao Xuan, Xiyou Zhou, Wenhu Chen, Yu-Xiang Wang, Xifeng Yan | 501 | 2019 | > | 5 | Informer: Beyond Efficient Transformer for Long Sequence Time-Series Forecasting | Haoyi Zhou, Shanghang Zhang, J. Peng, Shuai Zhang, Jianxin Li, Hui Xiong, Wan Zhang | 1769 | 2020 | > | 6 | Spatial-Temporal Transformer Networks for Traffic Flow Forecasting | Mingxing Xu, Wenrui Dai, Chunmiao Liu, Xing Gao, Weiyao Lin, Guo-Jun Qi, Hongkai Xiong | 163 | 2020 | > | 1 | Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting | Haixu Wu, Jiehui Xu, Jianmin Wang, Mingsheng Long | 721 | 2021 | > | 2 | A Transformer-based Framework for Multivariate Time Series Representation Learning | George Zerveas, Srideepika Jayaraman, Dhaval Patel, Anuradha Bhamidipaty, Carsten Eickhoff | 542 | 2021 | > | 21 | Temporal Fusion Transformers for interpretable multi-horizon time series forecasting | Bryan Lim, Sercan O. Arik, Nicolas Loeff, Tomas Pfister | 634 | 2021 | > | 9 | Transformer Embeddings of Irregularly Spaced Events and Their Participants | Chenghao Yang, Hongyuan Mei, Jason Eisner | 32 | 2021 | > | 20 | Efficient Transformers: A Survey | Yi Tay, Mostafa Dehghani, Dara Bahri, Donald Metzler | 641 | 2022 | > | 16 | Earthformer: Exploring Space-Time Transformers for Earth System Forecasting | Zhihan Gao, Xingjian Shi, Hao Wang, Yi Zhu, Yuyang Wang, Mu Li, Dit-Yan Yeung | 69 | 2022 | > | 15 | Scaleformer: Iterative Multi-scale Refining Transformers for Time Series Forecasting | Amin Shabani, Amir Abdi, Li Meng, Tristan Sylvain | 31 | 2022 | > | 14 | Transformers in Time Series: A Survey | Qingsong Wen, Tian Zhou, Chao Zhang, Weiqiu Chen, Ziqing Ma, Junchi Yan, Liang Sun | 327 | 2022 | > | 13 | Non-stationary Transformers: Exploring the Stationarity in Time Series Forecasting | Yong Liu, Haixu Wu, Jianmin Wang, Mingsheng Long | 119 | 2022 | > | 12 | Probabilistic Decomposition Transformer for Time Series Forecasting | Junlong Tong, Liping Xie, Wankou Yang, Kanjian Zhang | 1 | 2022 | > | 11 | A Time Series is Worth 64 Words: Long-term Forecasting with Transformers | Yuqi Nie, Nam H. Nguyen, Phanwadee Sinthong, J. Kalagnanam | 360 | 2022 | > | 10 | ETSformer: Exponential Smoothing Transformers for Time-series Forecasting | Gerald Woo, Chenghao Liu, Doyen Sahoo, Akshat Kumar, S. Hoi | 81 | 2022 | > | 8 | Pyraformer: Low-Complexity Pyramidal Attention for Long-Range Time Series Modeling and Forecasting | Shizhan Liu, Hang Yu, Cong Liao, Jianguo Li, Weiyao Lin, Alex X. Liu, S. Dustdar | 251 | 2022 | > | 7 | Triformer: Triangular, Variable-Specific Attentions for Long Sequence Multivariate Time Series Forecasting-Full Version | Razvan-Gabriel Cirstea, Chenjuan Guo, B. Yang, Tung Kieu, Xuanyi Dong, Shirui Pan | 62 | 2022 | > | 4 | FEDformer: Frequency Enhanced Decomposed Transformer for Long-term Series Forecasting | Tian Zhou, Ziqing Ma, Qingsong Wen, Xue Wang, Liang Sun, Rong Jin | 533 | 2022 | > | 34 | Causalformer: Causal Discovery-based Transformer for Multivariate Time Series Forecasting | Chonghao Zhang, Linlin Zhao, Zhefeng Yin, Zhenguo Zhang | 0 | 2023 | > | 35 | Transformer Multivariate Forecasting: Less is More? | Jingjing Xu, Caesar Wu, Yuan-Fang Li, Pascal Bouvry | 0 | 2023 | > | 33 | Take an Irregular Route: Enhance the Decoder of Time-Series Forecasting Transformer | Li Shen, Yuning Wei, Yangzhu Wang, Huaxin Qiu | 1 | 2023 | > | 32 | MultiResFormer: Transformer with Adaptive Multi-Resolution Modeling for General Time Series Forecasting | Linfeng Du, Ji Xin, Alex Labach, S. Zuberi, M. Volkovs, Rahul G. Krishnan | 0 | 2023 | > | 31 | Multi-resolution Time-Series Transformer for Long-term Forecasting | Yitian Zhang, Liheng Ma, Soumyasundar Pal, Yingxue Zhang, Mark Coates | 5 | 2023 | > | 30 | TEMPO: Prompt-based Generative Pre-trained Transformer for Time Series Forecasting | Defu Cao, Furong Jia, Sercan Ö. Arik, Tomas Pfister, Yixiang Zheng, Wen Ye, Yan Liu | 26 | 2023 | > | 29 | iTransformer: Inverted Transformers Are Effective for Time Series Forecasting | Yong Liu, Tengge Hu, Haoran Zhang, Haixu Wu, Shiyu Wang, Lintao Ma, Mingsheng Long | 82 | 2023 | > | 28 | Time-LLM: Time Series Forecasting by Reprogramming Large Language Models | Ming Jin, Shiyu Wang, Lintao Ma, Zhixuan Chu, James Y. Zhang, X. Shi, Pin-Yu Chen, Yuxuan Liang, Yuan-Fang Li, Shirui Pan, Qingsong Wen | 3 | 2023 | > | 22 | One Fits All:Power General Time Series Analysis by Pretrained LM | Tian Zhou, Peisong Niu, Xue Wang, Liang Sun, Rong Jin | 110 | 2023 | > | 26 | DSformer: A Double Sampling Transformer for Multivariate Time Series Long-term Prediction | Chengqing Yu, Fei Wang, Zezhi Shao, Tao Sun, Lin Wu, Yongjun Xu | 23 | 2023 | > | 25 | Crossformer: Transformer Utilizing Cross-Dimension Dependency for Multivariate Time Series Forecasting | Yunhao Zhang, Junchi Yan | 135 | 2023 | > | 24 | Make Transformer Great Again for Time Series Forecasting: Channel Aligned Robust Dual Transformer | Xue Wang, Tian Zhou, Qingsong Wen, Jinyang Gao, Bolin Ding, Rong Jin | 1 | 2023 | > | 23 | A Survey on Time-Series Pre-Trained Models | Qianli Ma, Z. Liu, Zhenjing Zheng, Ziyang Huang, Siying Zhu, Zhongzhong Yu, J. Kwok | 24 | 2023 | > | 17 | Transformer models: an introduction and catalog | X. Amatriain | 17 | 2023 | > | 3 | Are Transformers Effective for Time Series Forecasting? | Ailing Zeng, Muxi Chen, Lei Zhang, Qiang Xu | 570 | 2023 | > | 27 | LLM4TS: Two-Stage Fine-Tuning for Time-Series Forecasting with Pre-Trained LLMs | Ching Chang, Wenjie Peng, Tien-Fu Chen | 9 | 2023 | > | 43 | Integrating Mamba and Transformer for Long-Short Range Time Series Forecasting | Xiongxiao Xu, Yueqing Liang, Baixiang Huang, Zhiling Lan, Kai Shu | 4 | 2024 | > | 36 | MSHyper: Multi-Scale Hypergraph Transformer for Long-Range Time Series Forecasting | Zongjiang Shang, Ling Chen | 1 | 2024 | > | 37 | HiMTM: Hierarchical Multi-Scale Masked Time Series Modeling for Long-Term Forecasting | Shubao Zhao, Ming Jin, Zhaoxiang Hou, Che-Sheng Yang, Zengxiang Li, Qingsong Wen, Yi Wang | 1 | 2024 | > | 38 | Attention as Robust Representation for Time Series Forecasting | Peisong Niu, Tian Zhou, Xue Wang, Liang Sun, Rong Jin | 1 | 2024 | > | 39 | MOMENT: A Family of Open Time-series Foundation Models | Mononito Goswami, Konrad Szafer, Arjun Choudhry, Yifu Cai, Shuo Li, Artur Dubrawski | 9 | 2024 | > | 40 | Generative Pretrained Hierarchical Transformer for Time Series Forecasting | Zhiding Liu, Jiqian Yang, Mingyue Cheng, Yucong Luo, Zhi Li | 1 | 2024 | > | 41 | tsGT: Stochastic Time Series Modeling With Transformer | Lukasz Kuci'nski, Witold Drzewakowski, Mateusz Olko, Piotr Kozakowski, Lukasz Maziarka, Marta Emilia Nowakowska, Lukasz Kaiser, Piotr Milo's | 0 | 2024 | > | 42 | Foundation Models for Time Series Analysis: A Tutorial and Survey | Yuxuan Liang, Haomin Wen, Yuqi Nie, Yushan Jiang, Ming Jin, Dongjin Song, Shirui Pan, Qingsong Wen | 11 | 2024 | > | 44 | Deep Time Series Forecasting Models: A Comprehensive Survey | Xinhe Liu, Wenmin Wang | 1 | 2024 | > ``` # Adversarial Models - [GAN]() - [f-GAN]()