├── .github └── workflows │ └── ponicode.yml ├── .gitignore ├── LICENSE ├── README.md ├── autoenc_architecture.png ├── examples ├── forecasting │ ├── config.yaml │ └── run_forecasting.py └── reconstruction │ ├── config.yaml │ └── run_reconstruction.py ├── pyproject.toml ├── requirements.txt └── tsa ├── __init__.py ├── dataset.py ├── eval.py ├── model.py ├── train.py └── utils.py /.github/workflows/ponicode.yml: -------------------------------------------------------------------------------- 1 | name: Ponicode DogString 2 | 3 | # Controls when the action will run. Triggers the workflow on push or pull request 4 | # events but only for the master branch 5 | on: 6 | push: 7 | branches: [master] 8 | 9 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 10 | jobs: 11 | # This workflow contains a single job called "build" 12 | build: 13 | # The type of runner that the job will run on 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | with: 18 | fetch-depth: 0 19 | - name: Get paths 20 | run: | 21 | git show --pretty="" --name-only ${{ github.sha }} > PATHS_TO_CHANGED_FILES.txt 22 | - uses: ponicode/docstrings-action@master 23 | with: 24 | repo_path: ./ 25 | auth_token: ${{ secrets.PONICODE_TOKEN }} 26 | all_repo: True 27 | # Creates pull request with all changes in file 28 | - name: Create Pull Request 29 | uses: peter-evans/create-pull-request@v2 30 | with: 31 | token: ${{ secrets.GITHUB_TOKEN }} 32 | commit-message: "[ponicode-pull-request] Ponicode wrote new docstrings!" 33 | branch: ponicode-docstring 34 | title: "[Ponicode] Docstrings created" 35 | body: | 36 | ## ⭐️ Ponicode report ⭐️ 37 | Ponicode found **undocumented functions** in your code, and auto-generated docstrings for you. 38 |
39 | ### 🦄 We'd love to hear your feedback!🦄 40 | Send us an email at , open an issue on our Action, or join us on the [Ponicode Community Slack](https://ponicode-community.slack.com/join/shared_invite/zt-fiq4fhkg-DE~a_FkJ7xtiZxW7efyA4Q#/). 41 | Visit **[ponicode.com](https://ponicode.com)** to find out more about what we do. 42 |
43 | Ponicode Logo 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | .idea/ 131 | 132 | data/ 133 | output/ 134 | .DS_Store 135 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

LSTM-autoencoder with attentions for multivariate time series

2 | 3 |

4 | Hits 5 | 6 |

7 | 8 | This repository contains an autoencoder for multivariate time series forecasting. 9 | It features two attention mechanisms described 10 | in *[A Dual-Stage Attention-Based Recurrent Neural Network for Time Series Prediction](https://arxiv.org/abs/1704.02971)* 11 | and was inspired by [Seanny123's repository](https://github.com/Seanny123/da-rnn). 12 | 13 | ![Autoencoder architecture](autoenc_architecture.png) 14 | 15 | ## Download and dependencies 16 | 17 | To clone the repository please run: 18 | 19 | ``` 20 | git clone https://github.com/JulesBelveze/time-series-autoencoder.git 21 | ``` 22 | 23 |
24 | 25 | Use uv 26 | 27 | Then install `uv` 28 | ```shell 29 | # install uv 30 | curl -LsSf https://astral.sh/uv/install.sh | sh # linux/mac 31 | # or 32 | brew install uv # mac with homebrew 33 | ``` 34 | 35 | # setup environment and install dependencies 36 | ```bash 37 | cd time-series-autoencoder 38 | uv venv 39 | uv pip sync pyproject.toml 40 | ``` 41 | 42 |
43 | 44 |
45 | Install directly from requirements.txt 46 | 47 | ```shell 48 | pip install -r requirements.txt 49 | ``` 50 | 51 |
52 | 53 | ## Usage 54 | 55 | The project uses [Hydra](https://hydra.cc/docs/intro/) as a configuration parser. You can simply change the parameters 56 | directly within your `.yaml` file or you can override/set parameter using flags (for a complete guide please refer to 57 | the docs). 58 | 59 | ``` 60 | python3 main.py -cn=[PATH_TO_FOLDER_CONFIG] -cp=[CONFIG_NAME] 61 | ``` 62 | 63 | Optional arguments: 64 | 65 | ``` 66 | -h, --help show this help message and exit 67 | --batch-size BATCH_SIZE 68 | batch size 69 | --output-size OUTPUT_SIZE 70 | size of the ouput: default value to 1 for forecasting 71 | --label-col LABEL_COL 72 | name of the target column 73 | --input-att INPUT_ATT 74 | whether or not activate the input attention mechanism 75 | --temporal-att TEMPORAL_ATT 76 | whether or not activate the temporal attention 77 | mechanism 78 | --seq-len SEQ_LEN window length to use for forecasting 79 | --hidden-size-encoder HIDDEN_SIZE_ENCODER 80 | size of the encoder's hidden states 81 | --hidden-size-decoder HIDDEN_SIZE_DECODER 82 | size of the decoder's hidden states 83 | --reg-factor1 REG_FACTOR1 84 | contribution factor of the L1 regularization if using 85 | a sparse autoencoder 86 | --reg-factor2 REG_FACTOR2 87 | contribution factor of the L2 regularization if using 88 | a sparse autoencoder 89 | --reg1 REG1 activate/deactivate L1 regularization 90 | --reg2 REG2 activate/deactivate L2 regularization 91 | --denoising DENOISING 92 | whether or not to use a denoising autoencoder 93 | --do-train DO_TRAIN whether or not to train the model 94 | --do-eval DO_EVAL whether or not evaluating the mode 95 | --data-path DATA_PATH 96 | path to data file 97 | --output-dir OUTPUT_DIR 98 | name of folder to output files 99 | --ckpt CKPT checkpoint path for evaluation 100 | ``` 101 | 102 | ## Features 103 | 104 | * handles multivariate time series 105 | * attention mechanisms 106 | * denoising autoencoder 107 | * sparse autoencoder 108 | 109 | ## Examples 110 | 111 | You can find under the `examples` scripts to train the model in both cases: 112 | 113 | * reconstruction: the dataset can be found [here](https://gist.github.com/JulesBelveze/99ecdbea62f81ce647b131e7badbb24a) 114 | * forecasting: the dataset can be found [here](https://gist.github.com/JulesBelveze/e9997b9b0b68101029b461baf698bd72) 115 | 116 | 117 | -------------------------------------------------------------------------------- /autoenc_architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesBelveze/time-series-autoencoder/81210d66083e8e4f39282a55b96c415417d4b490/autoenc_architecture.png -------------------------------------------------------------------------------- /examples/forecasting/config.yaml: -------------------------------------------------------------------------------- 1 | data: 2 | _target_: tsa.dataset.TimeSeriesDataset 3 | batch_size: 16 4 | categorical_cols: [ ] 5 | index_col: "Date_Time" 6 | target_col: [ "AH" ] 7 | data_path: "../data/AirQualityUCI.csv" 8 | prediction_window: 1 9 | seq_length: 3 10 | task: 11 | _target_: tsa.dataset.Tasks 12 | value: prediction 13 | 14 | training: 15 | batch_size: ${data.batch_size} 16 | denoising: False 17 | directions: 1 18 | gradient_accumulation_steps: 1 19 | hidden_size_encoder: 64 20 | hidden_size_decoder: 64 21 | input_att: True 22 | lr: 1e-5 23 | lrs_step_size: 5000 24 | max_grad_norm: 0.1 25 | num_epochs: 100 26 | output_size: 1 27 | reg1: True 28 | reg2: False 29 | reg_factor1: 1e-4 30 | reg_factor2: 1e-4 31 | seq_len: ${data.seq_length} 32 | temporal_att: True 33 | 34 | general: 35 | do_eval: True 36 | do_train: True 37 | logging_steps: 100 38 | 39 | output_dir: "output" 40 | save_steps: 5000 41 | eval_during_training: True -------------------------------------------------------------------------------- /examples/forecasting/run_forecasting.py: -------------------------------------------------------------------------------- 1 | import hydra 2 | import torch 3 | import torch.nn as nn 4 | from hydra.utils import instantiate 5 | 6 | from tsa import AutoEncForecast, train, evaluate 7 | from tsa.utils import load_checkpoint 8 | 9 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 10 | 11 | 12 | @hydra.main(config_path="./", config_name="config") 13 | def run(cfg): 14 | ts = instantiate(cfg.data) 15 | train_iter, test_iter, nb_features = ts.get_loaders() 16 | 17 | model = AutoEncForecast(cfg.training, input_size=nb_features).to(device) 18 | criterion = nn.MSELoss() 19 | optimizer = torch.optim.Adam(model.parameters(), lr=cfg.training.lr) 20 | 21 | if cfg.general.do_train: 22 | train(train_iter, test_iter, model, criterion, optimizer, cfg, ts) 23 | if cfg.general.do_eval and cfg.general.get("ckpt", False): 24 | model, _, loss, epoch = load_checkpoint(cfg.general.ckpt, model, optimizer, device) 25 | evaluate(test_iter, loss, model, cfg, ts) 26 | 27 | 28 | if __name__ == "__main__": 29 | run() 30 | -------------------------------------------------------------------------------- /examples/reconstruction/config.yaml: -------------------------------------------------------------------------------- 1 | data: 2 | _target_: tsa.dataset.TimeSeriesDataset 3 | batch_size: 16 4 | categorical_cols: [ ] 5 | index_col: "Date_Time" 6 | target_col: [ ] 7 | data_path: "../data/AirQualityUCI.csv" 8 | prediction_window: 1 9 | seq_length: 3 10 | task: 11 | _target_: tsa.dataset.Tasks 12 | value: reconstruction 13 | 14 | training: 15 | denoising: False 16 | directions: 1 17 | gradient_accumulation_steps: 1 18 | hidden_size_encoder: 64 19 | hidden_size_decoder: 64 20 | input_att: True 21 | lr: 1e-5 22 | lrs_step_size: 5000 23 | max_grad_norm: 0.1 24 | num_epochs: 100 25 | output_size: 13 26 | reg1: True 27 | reg2: False 28 | reg_factor1: 1e-4 29 | reg_factor2: 1e-4 30 | seq_len: ${data.seq_length} 31 | temporal_att: True 32 | 33 | general: 34 | do_eval: True 35 | do_train: True 36 | logging_steps: 100 37 | 38 | output_dir: "output" 39 | save_steps: 5000 40 | eval_during_training: True 41 | -------------------------------------------------------------------------------- /examples/reconstruction/run_reconstruction.py: -------------------------------------------------------------------------------- 1 | import hydra 2 | import torch 3 | import torch.nn as nn 4 | from hydra.utils import instantiate 5 | 6 | from tsa import AutoEncForecast, train, evaluate 7 | from tsa.utils import load_checkpoint 8 | 9 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 10 | 11 | 12 | @hydra.main(config_path="./", config_name="config") 13 | def run(cfg): 14 | ts = instantiate(cfg.data) 15 | train_iter, test_iter, nb_features = ts.get_loaders() 16 | 17 | model = AutoEncForecast(cfg.training, input_size=nb_features).to(device) 18 | criterion = nn.MSELoss() 19 | optimizer = torch.optim.Adam(model.parameters(), lr=cfg.training.lr) 20 | 21 | if cfg.general.do_eval and cfg.general.get("ckpt", False): 22 | model, _, loss, epoch = load_checkpoint(cfg.general.ckpt, model, optimizer, device) 23 | evaluate(test_iter, loss, model, cfg, ts) 24 | elif cfg.general.do_train: 25 | train(train_iter, test_iter, model, criterion, optimizer, cfg, ts) 26 | 27 | 28 | if __name__ == "__main__": 29 | run() 30 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "tsa" 3 | version = "0.1.0" 4 | description = "" 5 | requires-python = ">=3.10" 6 | dependencies = [ 7 | "torch>=2.2.0", 8 | "matplotlib>=3.3.4", 9 | "tensorboardX>=2.1", 10 | "tqdm>=4.59.0", 11 | "hydra-core>=1.2.0", 12 | "scikit-learn>=1.5.2", 13 | "pandas>=2.2.3" 14 | ] 15 | 16 | [build-system] 17 | requires = ["hatchling"] 18 | build-backend = "hatchling.build" -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # This file was autogenerated by uv via the following command: 2 | # uv pip compile pyproject.toml -o requirements.txt 3 | antlr4-python3-runtime==4.9.3 4 | # via 5 | # hydra-core 6 | # omegaconf 7 | contourpy==1.3.0 8 | # via matplotlib 9 | cycler==0.12.1 10 | # via matplotlib 11 | filelock==3.16.1 12 | # via torch 13 | fonttools==4.54.1 14 | # via matplotlib 15 | fsspec==2024.10.0 16 | # via torch 17 | hydra-core==1.3.2 18 | # via tsa (pyproject.toml) 19 | jinja2==3.1.4 20 | # via torch 21 | joblib==1.4.2 22 | # via scikit-learn 23 | kiwisolver==1.4.7 24 | # via matplotlib 25 | markupsafe==3.0.2 26 | # via jinja2 27 | matplotlib==3.9.2 28 | # via tsa (pyproject.toml) 29 | mpmath==1.3.0 30 | # via sympy 31 | networkx==3.4.2 32 | # via torch 33 | numpy==2.1.2 34 | # via 35 | # contourpy 36 | # matplotlib 37 | # pandas 38 | # scikit-learn 39 | # scipy 40 | # tensorboardx 41 | omegaconf==2.3.0 42 | # via hydra-core 43 | packaging==24.1 44 | # via 45 | # hydra-core 46 | # matplotlib 47 | # tensorboardx 48 | pandas==2.2.3 49 | # via tsa (pyproject.toml) 50 | pillow==11.0.0 51 | # via matplotlib 52 | protobuf==5.28.3 53 | # via tensorboardx 54 | pyparsing==3.2.0 55 | # via matplotlib 56 | python-dateutil==2.9.0.post0 57 | # via 58 | # matplotlib 59 | # pandas 60 | pytz==2024.2 61 | # via pandas 62 | pyyaml==6.0.2 63 | # via omegaconf 64 | scikit-learn==1.5.2 65 | # via tsa (pyproject.toml) 66 | scipy==1.14.1 67 | # via scikit-learn 68 | setuptools==75.2.0 69 | # via torch 70 | six==1.16.0 71 | # via python-dateutil 72 | sympy==1.13.1 73 | # via torch 74 | tensorboardx==2.6.2.2 75 | # via tsa (pyproject.toml) 76 | threadpoolctl==3.5.0 77 | # via scikit-learn 78 | torch==2.5.0 79 | # via tsa (pyproject.toml) 80 | tqdm==4.66.5 81 | # via tsa (pyproject.toml) 82 | typing-extensions==4.12.2 83 | # via torch 84 | tzdata==2024.2 85 | # via pandas 86 | -------------------------------------------------------------------------------- /tsa/__init__.py: -------------------------------------------------------------------------------- 1 | from .dataset import TimeSeriesDataset 2 | from .eval import evaluate 3 | from .train import train 4 | from .model import * -------------------------------------------------------------------------------- /tsa/dataset.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from typing import List 3 | 4 | import pandas as pd 5 | import pkg_resources 6 | import torch 7 | from sklearn.compose import ColumnTransformer 8 | from sklearn.model_selection import train_test_split 9 | from sklearn.preprocessing import StandardScaler, OneHotEncoder 10 | from torch.utils.data import TensorDataset, DataLoader 11 | 12 | 13 | class Tasks(Enum): 14 | prediction = "prediction" 15 | reconstruction = "reconstruction" 16 | 17 | 18 | class TimeSeriesDataset(object): 19 | def __init__(self, task: Tasks, data_path: str, categorical_cols: List[str], index_col: str, target_col: str, 20 | seq_length: int, batch_size: int, prediction_window: int = 1): 21 | """ 22 | :param task: name of the task 23 | :param data_path: path to datafile 24 | :param categorical_cols: name of the categorical columns, if None pass empty list 25 | :param index_col: column to use as index 26 | :param target_col: name of the targeted column 27 | :param seq_length: window length to use 28 | :param batch_size: 29 | :param prediction_window: window length to predict 30 | """ 31 | self.task = task.value 32 | 33 | data_path = pkg_resources.resource_filename("tsa", data_path) 34 | self.data = pd.read_csv(data_path, index_col=index_col) 35 | self.categorical_cols = categorical_cols 36 | self.numerical_cols = list(set(self.data.columns) - set(categorical_cols) - set(target_col)) 37 | self.target_col = target_col 38 | 39 | self.seq_length = seq_length 40 | self.prediction_window = prediction_window 41 | self.batch_size = batch_size 42 | 43 | transformations = [("scaler", StandardScaler(), self.numerical_cols)] 44 | if len(self.categorical_cols) > 0: 45 | transformations.append(("encoder", OneHotEncoder(), self.categorical_cols)) 46 | self.preprocessor = ColumnTransformer(transformations, remainder="passthrough") 47 | 48 | if self.task == "prediction": 49 | self.y_scaler = StandardScaler() 50 | 51 | def preprocess_data(self): 52 | """Preprocessing function""" 53 | X = self.data.drop(self.target_col, axis=1) 54 | y = self.data[self.target_col] 55 | 56 | X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, shuffle=False) 57 | X_train = self.preprocessor.fit_transform(X_train) 58 | X_test = self.preprocessor.transform(X_test) 59 | 60 | if self.task == "prediction": 61 | y_train = self.y_scaler.fit_transform(y_train) 62 | y_test = self.y_scaler.transform(y_test) 63 | return X_train, X_test, y_train, y_test 64 | return X_train, X_test, None, None 65 | 66 | def frame_series(self, X, y=None): 67 | """ 68 | Function used to prepare the data for time series prediction 69 | :param X: set of features 70 | :param y: targeted value to predict 71 | :return: TensorDataset 72 | """ 73 | nb_obs, nb_features = X.shape 74 | features, target, y_hist = [], [], [] 75 | 76 | for i in range(1, nb_obs - self.seq_length - self.prediction_window): 77 | features.append(torch.FloatTensor(X[i:i + self.seq_length, :]).unsqueeze(0)) 78 | 79 | if self.task == "prediction": 80 | # lagged output used for prediction 81 | y_hist.append(torch.FloatTensor(y[i - 1:i + self.seq_length - 1]).unsqueeze(0)) 82 | # shifted target 83 | target.append(torch.FloatTensor(y[i + self.seq_length:i + self.seq_length + self.prediction_window])) 84 | else: 85 | y_hist.append(torch.FloatTensor(X[i - 1: i + self.seq_length - 1, :]).unsqueeze(0)) 86 | target.append( 87 | torch.FloatTensor(X[i + self.seq_length:i + self.seq_length + self.prediction_window, :])) 88 | 89 | features_var = torch.cat(features) 90 | y_hist_var = torch.cat(y_hist) 91 | target_var = torch.cat(target) 92 | 93 | return TensorDataset(features_var, y_hist_var, target_var) 94 | 95 | def get_loaders(self): 96 | """ 97 | Preprocess and frame the dataset 98 | 99 | :return: DataLoaders associated to training and testing data 100 | """ 101 | X_train, X_test, y_train, y_test = self.preprocess_data() 102 | nb_features = X_train.shape[1] 103 | 104 | train_dataset = self.frame_series(X_train, y_train) 105 | test_dataset = self.frame_series(X_test, y_test) 106 | 107 | train_iter = DataLoader(train_dataset, batch_size=self.batch_size, shuffle=False, drop_last=True) 108 | test_iter = DataLoader(test_dataset, batch_size=self.batch_size, shuffle=False, drop_last=True) 109 | return train_iter, test_iter, nb_features 110 | 111 | def invert_scale(self, predictions): 112 | """ 113 | Inverts the scale of the predictions 114 | """ 115 | if isinstance(predictions, torch.Tensor): 116 | predictions = predictions.numpy() 117 | 118 | if predictions.ndim == 1: 119 | predictions = predictions.reshape(-1, 1) 120 | 121 | if self.task == "prediction": 122 | unscaled = self.y_scaler.inverse_transform(predictions) 123 | else: 124 | unscaled = self.preprocessor.named_transformers_["scaler"].inverse_transform(predictions) 125 | return torch.Tensor(unscaled) 126 | -------------------------------------------------------------------------------- /tsa/eval.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | import torch 6 | import torch.nn.functional as F 7 | from tqdm import tqdm 8 | 9 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 10 | 11 | 12 | def evaluate(test_iter, criterion, model, config, ts): 13 | """ 14 | Evaluate the model on the given test set. 15 | 16 | Args: 17 | test_iter: (DataLoader): test dataset iterator 18 | criterion: loss function 19 | model: model to use 20 | config: config 21 | """ 22 | predictions, targets, attentions = [], [], [] 23 | eval_loss = 0.0 24 | 25 | model.eval() 26 | for i, batch in tqdm(enumerate(test_iter), total=len(test_iter), desc="Evaluating"): 27 | with torch.no_grad(): 28 | feature, y_hist, target = batch 29 | output, att = model(feature.to(device), y_hist.to(device), return_attention=True) 30 | 31 | loss = criterion(output.to(device), target.to(device)).item() 32 | if config.training.reg1: 33 | params = torch.cat([p.view(-1) for name, p in model.named_parameters() if 'bias' not in name]) 34 | loss += config.training.reg_factor1 * torch.norm(params, 1) 35 | if config.training.reg2: 36 | params = torch.cat([p.view(-1) for name, p in model.named_parameters() if 'bias' not in name]) 37 | loss += config.training.reg_factor2 * torch.norm(params, 2) 38 | eval_loss += loss 39 | 40 | predictions.append(output.squeeze(1).cpu()) 41 | targets.append(target.squeeze(1).cpu()) 42 | attentions.append(att.cpu()) 43 | 44 | predictions, targets = torch.cat(predictions), torch.cat(targets) 45 | 46 | if config.general.do_eval: 47 | preds, targets = ts.invert_scale(predictions), ts.invert_scale(targets) 48 | 49 | plt.figure() 50 | plt.plot(preds, linewidth=.3) 51 | plt.plot(targets, linewidth=.3) 52 | plt.savefig("{}/preds.png".format(config.general.output_dir)) 53 | plt.close() 54 | 55 | torch.save(targets, os.path.join(config.general.output_dir, "targets.pt")) 56 | torch.save(predictions, os.path.join(config.general.output_dir, "predictions.pt")) 57 | torch.save(attentions, os.path.join(config.general.output_dir, "attentions.pt")) 58 | 59 | results = get_eval_report(eval_loss / len(test_iter), predictions, targets) 60 | file_eval = os.path.join(config.general.output_dir, "eval_results.txt") 61 | with open(file_eval, "w") as f: 62 | f.write("********* EVAL REPORT ********\n") 63 | for key, val in results.items(): 64 | f.write(" %s = %s\n" % (key, str(val))) 65 | 66 | return results 67 | 68 | 69 | def get_eval_report(eval_loss: float, predictions: torch.Tensor, targets: torch.Tensor): 70 | """ 71 | Evaluates the accuracy. 72 | 73 | Args: 74 | eval_loss: (float): loss vlue 75 | predictions: (torch.Tensor): tensor of predictions 76 | targets: (torch.Tensor): tensor of targets 77 | """ 78 | residuals = np.mean(predictions.numpy() - targets.numpy()) 79 | MSE = F.mse_loss(targets.squeeze(), predictions.squeeze()).item() 80 | return {"MSE": MSE, "residuals": residuals, "loss": eval_loss} 81 | -------------------------------------------------------------------------------- /tsa/model.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | from torch import nn 4 | from torch.autograd import Variable 5 | from torch.nn import functional as tf 6 | 7 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 8 | 9 | 10 | def init_hidden(x: torch.Tensor, hidden_size: int, num_dir: int = 1, xavier: bool = True): 11 | """ 12 | Initialize hidden. 13 | 14 | Args: 15 | x: (torch.Tensor): input tensor 16 | hidden_size: (int): 17 | num_dir: (int): number of directions in LSTM 18 | xavier: (bool): wether or not use xavier initialization 19 | """ 20 | if xavier: 21 | return nn.init.xavier_normal_(torch.zeros(num_dir, x.size(0), hidden_size)).to(device) 22 | return Variable(torch.zeros(num_dir, x.size(0), hidden_size)).to(device) 23 | 24 | 25 | ########################################################################### 26 | ################################ ENCODERS ################################# 27 | ########################################################################### 28 | 29 | class Encoder(nn.Module): 30 | def __init__(self, config, input_size: int): 31 | """ 32 | Initialize the model. 33 | 34 | Args: 35 | config: 36 | input_size: (int): size of the input 37 | """ 38 | super(Encoder, self).__init__() 39 | self.input_size = input_size 40 | self.hidden_size = config['hidden_size_encoder'] 41 | self.seq_len = config['seq_len'] 42 | self.lstm = nn.LSTM(input_size=input_size, hidden_size=config['hidden_size_encoder']) 43 | 44 | def forward(self, input_data: torch.Tensor): 45 | """ 46 | Run forward computation. 47 | 48 | Args: 49 | input_data: (torch.Tensor): tensor of input daa 50 | """ 51 | h_t, c_t = (init_hidden(input_data, self.hidden_size), 52 | init_hidden(input_data, self.hidden_size)) 53 | input_encoded = Variable(torch.zeros(input_data.size(0), self.seq_len, self.hidden_size)) 54 | 55 | for t in range(self.seq_len): 56 | _, (h_t, c_t) = self.lstm(input_data[:, t, :].unsqueeze(0), (h_t, c_t)) 57 | input_encoded[:, t, :] = h_t 58 | return _, input_encoded 59 | 60 | 61 | class AttnEncoder(nn.Module): 62 | def __init__(self, config, input_size: int): 63 | """ 64 | Initialize the network. 65 | 66 | Args: 67 | config: 68 | input_size: (int): size of the input 69 | """ 70 | super(AttnEncoder, self).__init__() 71 | self.input_size = input_size 72 | self.hidden_size = config['hidden_size_encoder'] 73 | self.seq_len = config['seq_len'] 74 | self.add_noise = config['denoising'] 75 | self.directions = config['directions'] 76 | self.lstm = nn.LSTM( 77 | input_size=self.input_size, 78 | hidden_size=self.hidden_size, 79 | num_layers=1 80 | ) 81 | self.attn = nn.Linear( 82 | in_features=2 * self.hidden_size + self.seq_len, 83 | out_features=1 84 | ) 85 | self.softmax = nn.Softmax(dim=1) 86 | 87 | @staticmethod 88 | def _get_noise(input_data: torch.Tensor, sigma=0.01, p=0.1): 89 | """ 90 | Get noise. 91 | 92 | Args: 93 | input_data: (torch.Tensor): tensor of input data 94 | sigma: (float): variance of the generated noise 95 | p: (float): probability to add noise 96 | """ 97 | normal = sigma * torch.randn(input_data.shape) 98 | mask = np.random.uniform(size=(input_data.shape)) 99 | mask = (mask < p).astype(int) 100 | noise = normal * torch.tensor(mask) 101 | return noise 102 | 103 | def forward(self, input_data: torch.Tensor): 104 | """ 105 | Forward computation. 106 | 107 | Args: 108 | input_data: (torch.Tensor): tensor of input data 109 | """ 110 | h_t, c_t = (init_hidden(input_data, self.hidden_size, num_dir=self.directions), 111 | init_hidden(input_data, self.hidden_size, num_dir=self.directions)) 112 | 113 | attentions, input_encoded = (Variable(torch.zeros(input_data.size(0), self.seq_len, self.input_size)), 114 | Variable(torch.zeros(input_data.size(0), self.seq_len, self.hidden_size))) 115 | 116 | if self.add_noise and self.training: 117 | input_data += self._get_noise(input_data).to(device) 118 | 119 | for t in range(self.seq_len): 120 | x = torch.cat((h_t.repeat(self.input_size, 1, 1).permute(1, 0, 2), 121 | c_t.repeat(self.input_size, 1, 1).permute(1, 0, 2), 122 | input_data.permute(0, 2, 1).to(device)), dim=2).to( 123 | device) # bs * input_size * (2 * hidden_dim + seq_len) 124 | 125 | e_t = self.attn(x.view(-1, self.hidden_size * 2 + self.seq_len)) # (bs * input_size) * 1 126 | a_t = self.softmax(e_t.view(-1, self.input_size)).to(device) # (bs, input_size) 127 | 128 | weighted_input = torch.mul(a_t, input_data[:, t, :].to(device)) # (bs * input_size) 129 | self.lstm.flatten_parameters() 130 | _, (h_t, c_t) = self.lstm(weighted_input.unsqueeze(0), (h_t, c_t)) 131 | 132 | input_encoded[:, t, :] = h_t 133 | attentions[:, t, :] = a_t 134 | 135 | return attentions, input_encoded 136 | 137 | 138 | ########################################################################### 139 | ################################ DECODERS ################################# 140 | ########################################################################### 141 | 142 | class Decoder(nn.Module): 143 | def __init__(self, config): 144 | """ 145 | Initialize the network. 146 | 147 | Args: 148 | config: 149 | """ 150 | super(Decoder, self).__init__() 151 | self.seq_len = config['seq_len'] 152 | self.hidden_size = config['hidden_size_decoder'] 153 | self.lstm = nn.LSTM(1, config['hidden_size_decoder'], bidirectional=False) 154 | self.fc = nn.Linear(config['hidden_size_decoder'], config['output_size']) 155 | 156 | def forward(self, _, y_hist: torch.Tensor): 157 | """ 158 | Forward pass 159 | 160 | Args: 161 | _: 162 | y_hist: (torch.Tensor): shifted target 163 | """ 164 | h_t, c_t = (init_hidden(y_hist, self.hidden_size), 165 | init_hidden(y_hist, self.hidden_size)) 166 | 167 | for t in range(self.seq_len): 168 | inp = y_hist[:, t].unsqueeze(0).unsqueeze(2) 169 | lstm_out, (h_t, c_t) = self.lstm(inp, (h_t, c_t)) 170 | return self.fc(lstm_out.squeeze(0)) 171 | 172 | 173 | class AttnDecoder(nn.Module): 174 | def __init__(self, config): 175 | """ 176 | Initialize the network. 177 | 178 | Args: 179 | config: 180 | """ 181 | super(AttnDecoder, self).__init__() 182 | self.seq_len = config['seq_len'] 183 | self.encoder_hidden_size = config['hidden_size_encoder'] 184 | self.decoder_hidden_size = config['hidden_size_decoder'] 185 | self.out_feats = config['output_size'] 186 | 187 | self.attn = nn.Sequential( 188 | nn.Linear(2 * self.decoder_hidden_size + self.encoder_hidden_size, self.encoder_hidden_size), 189 | nn.Tanh(), 190 | nn.Linear(self.encoder_hidden_size, 1) 191 | ) 192 | self.lstm = nn.LSTM(input_size=self.out_feats, hidden_size=self.decoder_hidden_size) 193 | self.fc = nn.Linear(self.encoder_hidden_size + self.out_feats, self.out_feats) 194 | self.fc_out = nn.Linear(self.decoder_hidden_size + self.encoder_hidden_size, self.out_feats) 195 | self.fc.weight.data.normal_() 196 | 197 | def forward(self, input_encoded: torch.Tensor, y_history: torch.Tensor): 198 | """ 199 | Perform forward computation. 200 | 201 | Args: 202 | input_encoded: (torch.Tensor): tensor of encoded input 203 | y_history: (torch.Tensor): shifted target 204 | """ 205 | h_t, c_t = ( 206 | init_hidden(input_encoded, self.decoder_hidden_size), init_hidden(input_encoded, self.decoder_hidden_size)) 207 | context = Variable(torch.zeros(input_encoded.size(0), self.encoder_hidden_size)) 208 | 209 | for t in range(self.seq_len): 210 | x = torch.cat((h_t.repeat(self.seq_len, 1, 1).permute(1, 0, 2), 211 | c_t.repeat(self.seq_len, 1, 1).permute(1, 0, 2), 212 | input_encoded.to(device)), dim=2) 213 | 214 | x = tf.softmax( 215 | self.attn( 216 | x.view(-1, 2 * self.decoder_hidden_size + self.encoder_hidden_size) 217 | ).view(-1, self.seq_len), 218 | dim=1) 219 | 220 | context = torch.bmm(x.unsqueeze(1), input_encoded.to(device))[:, 0, :] # (batch_size, encoder_hidden_size) 221 | 222 | y_tilde = self.fc(torch.cat((context.to(device), y_history[:, t].to(device)), 223 | dim=1)) # (batch_size, out_size) 224 | 225 | self.lstm.flatten_parameters() 226 | _, (h_t, c_t) = self.lstm(y_tilde.unsqueeze(0), (h_t, c_t)) 227 | 228 | return self.fc_out(torch.cat((h_t[0], context.to(device)), dim=1)) # predicting value at t=self.seq_length+1 229 | 230 | 231 | class AutoEncForecast(nn.Module): 232 | def __init__(self, config, input_size): 233 | """ 234 | Initialize the network. 235 | 236 | Args: 237 | config: 238 | input_size: (int): size of the input 239 | """ 240 | super(AutoEncForecast, self).__init__() 241 | self.encoder = AttnEncoder(config, input_size).to(device) if config['input_att'] else \ 242 | Encoder(config, input_size).to(device) 243 | self.decoder = AttnDecoder(config).to(device) if config['temporal_att'] else Decoder(config).to(device) 244 | 245 | def forward(self, encoder_input: torch.Tensor, y_hist: torch.Tensor, return_attention: bool = False): 246 | """ 247 | Forward computation. encoder_input_inputs. 248 | 249 | Args: 250 | encoder_input: (torch.Tensor): tensor of input data 251 | y_hist: (torch.Tensor): shifted target 252 | return_attention: (bool): whether to return the attention 253 | """ 254 | attentions, encoder_output = self.encoder(encoder_input) 255 | outputs = self.decoder(encoder_output, y_hist.float()) 256 | 257 | if return_attention: 258 | return outputs, attentions 259 | return outputs 260 | -------------------------------------------------------------------------------- /tsa/train.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import torch 4 | from tensorboardX import SummaryWriter 5 | from tqdm import tqdm 6 | 7 | from .eval import evaluate 8 | 9 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 10 | 11 | 12 | def train(train_iter, test_iter, model, criterion, optimizer, config, ts): 13 | """ 14 | Training function. 15 | 16 | Args: 17 | train_iter: (DataLoader): train data iterator 18 | test_iter: (DataLoader): test data iterator 19 | model: model 20 | criterion: loss to use 21 | optimizer: optimizer to use 22 | config: 23 | """ 24 | tb_writer_train = SummaryWriter(logdir=config.general.output_dir, filename_suffix="train") 25 | tb_writer_test = SummaryWriter(logdir=config.general.output_dir, filename_suffix="test") 26 | 27 | if not os.path.exists(config.general.output_dir): 28 | os.makedirs(config.general.output_dir) 29 | 30 | scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=config.training.lrs_step_size, gamma=0.5) 31 | 32 | global_step, logging_loss = 0, 0.0 33 | train_loss = 0.0 34 | for epoch in tqdm(range(config.training.num_epochs), unit="epoch"): 35 | for i, batch in tqdm(enumerate(train_iter), total=len(train_iter), unit="batch"): 36 | model.train() 37 | optimizer.zero_grad() 38 | 39 | feature, y_hist, target = batch 40 | output = model(feature.to(device), y_hist.to(device)) 41 | loss = criterion(output.to(device), target.to(device)) 42 | 43 | if config.training.reg1: 44 | params = torch.cat([p.view(-1) for name, p in model.named_parameters() if "bias" not in name]) 45 | loss += config.training.reg_factor1 * torch.norm(params, 1) 46 | if config.training.reg2: 47 | params = torch.cat([p.view(-1) for name, p in model.named_parameters() if "bias" not in name]) 48 | loss += config.training.reg_factor2 * torch.norm(params, 2) 49 | 50 | if config.training.gradient_accumulation_steps > 1: 51 | loss = loss / config.training.gradient_accumulation_steps 52 | 53 | loss.backward() 54 | torch.nn.utils.clip_grad_norm_(model.parameters(), config.training.max_grad_norm) 55 | train_loss += loss.item() 56 | 57 | if (i + 1) % config.training.gradient_accumulation_steps == 0: 58 | optimizer.step() 59 | scheduler.step() 60 | global_step += 1 61 | 62 | if global_step % config.general.logging_steps == 0: 63 | if config.general.eval_during_training: 64 | results = evaluate(test_iter, criterion, model, config, ts) 65 | for key, val in results.items(): 66 | tb_writer_test.add_scalar("eval_{}".format(key), val, global_step) 67 | 68 | tb_writer_train.add_scalar("train_loss", (train_loss - logging_loss) / config.general.logging_steps, 69 | global_step) 70 | tb_writer_train.add_scalar("lr", scheduler.get_last_lr()[0], global_step) 71 | logging_loss = train_loss 72 | 73 | if global_step % config.general.save_steps == 0: 74 | torch.save({ 75 | "epoch": epoch + 1, 76 | "encoder_state_dict": model.encoder.state_dict(), 77 | "decoder_state_dict": model.decoder.state_dict(), 78 | "optimizer_state_dict": optimizer.state_dict(), 79 | "loss": criterion 80 | }, "{}/checkpoint-{}.ckpt".format(config.general.output_dir, global_step)) 81 | -------------------------------------------------------------------------------- /tsa/utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | 4 | def load_checkpoint(checkpoint_path, model, optimizer, device): 5 | """Load model state from checkpoint file""" 6 | checkpoint = torch.load(checkpoint_path, map_location=device) 7 | 8 | model.encoder.load_state_dict(checkpoint["encoder_state_dict"]) 9 | model.decoder.load_state_dict(checkpoint["decoder_state_dict"]) 10 | 11 | optimizer.load_state_dict(checkpoint["optimizer_state_dict"]) 12 | loss = checkpoint["loss"] 13 | epoch = checkpoint["epoch"] 14 | return model, optimizer, loss, epoch 15 | --------------------------------------------------------------------------------