├── .gitignore ├── LICENSE.txt ├── README.md ├── item sales forecasting.ipynb ├── torch_utils ├── __init__.py ├── cocob.py ├── predictor.py └── trainer.py ├── ts_models ├── __init__.py ├── decoders.py ├── encoder_decoder.py ├── encoders.py └── model_utils │ ├── __init__.py │ └── utils.py └── ts_utils └── sequence_builder.py /.gitignore: -------------------------------------------------------------------------------- 1 | # ignore data folders 2 | data 3 | sequence_data 4 | runs 5 | models 6 | results 7 | 8 | # Byte-compiled / optimized / DLL files 9 | __pycache__/ 10 | *.py[cod] 11 | *$py.class 12 | 13 | # C extensions 14 | *.so 15 | 16 | # Distribution / packaging 17 | .Python 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | wheels/ 30 | pip-wheel-metadata/ 31 | share/python-wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .nox/ 51 | .coverage 52 | .coverage.* 53 | .cache 54 | nosetests.xml 55 | coverage.xml 56 | *.cover 57 | *.py,cover 58 | .hypothesis/ 59 | .pytest_cache/ 60 | 61 | # Translations 62 | *.mo 63 | *.pot 64 | 65 | # Django stuff: 66 | *.log 67 | local_settings.py 68 | db.sqlite3 69 | db.sqlite3-journal 70 | 71 | # Flask stuff: 72 | instance/ 73 | .webassets-cache 74 | 75 | # Scrapy stuff: 76 | .scrapy 77 | 78 | # Sphinx documentation 79 | docs/_build/ 80 | 81 | # PyBuilder 82 | target/ 83 | 84 | # Jupyter Notebook 85 | .ipynb_checkpoints 86 | 87 | # IPython 88 | profile_default/ 89 | ipython_config.py 90 | 91 | # pyenv 92 | .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 102 | __pypackages__/ 103 | 104 | # Celery stuff 105 | celerybeat-schedule 106 | celerybeat.pid 107 | 108 | # SageMath parsed files 109 | *.sage.py 110 | 111 | # Environments 112 | .env 113 | .venv 114 | env/ 115 | venv/ 116 | ENV/ 117 | env.bak/ 118 | venv.bak/ 119 | 120 | # Spyder project settings 121 | .spyderproject 122 | .spyproject 123 | 124 | # Rope project settings 125 | .ropeproject 126 | 127 | # mkdocs documentation 128 | /site 129 | 130 | # mypy 131 | .mypy_cache/ 132 | .dmypy.json 133 | dmypy.json 134 | 135 | # Pyre type checker 136 | .pyre/ 137 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 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 | # pytorch-ts 2 | Framework for using seq2seq Encoder-decoder architecture for time series forecasting 3 | -------------------------------------------------------------------------------- /torch_utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gautham20/pytorch-ts/4c7ddcfa6fcd4ae3dcf3b84f55a13d16b1687738/torch_utils/__init__.py -------------------------------------------------------------------------------- /torch_utils/cocob.py: -------------------------------------------------------------------------------- 1 | # %load cocob.py 2 | import torch.optim as optim 3 | import torch 4 | 5 | ########################################################################### 6 | # Training Deep Networks without Learning Rates Through Coin Betting 7 | # Paper: https://arxiv.org/abs/1705.07795 8 | # 9 | # NOTE: This optimizer is hardcoded to run on GPU, needs to be parametrized 10 | ########################################################################### 11 | 12 | class COCOBBackprop(optim.Optimizer): 13 | 14 | def __init__(self, params, alpha=100, epsilon=1e-8, weight_decay=0): 15 | 16 | self._alpha = alpha 17 | self.epsilon = epsilon 18 | self.weight_decay = weight_decay 19 | defaults = dict(alpha=alpha, epsilon=epsilon, weight_decay=weight_decay) 20 | super(COCOBBackprop, self).__init__(params, defaults) 21 | 22 | @torch.no_grad() 23 | def step(self, closure=None): 24 | 25 | loss = None 26 | 27 | if closure is not None: 28 | loss = closure() 29 | 30 | for group in self.param_groups: 31 | for p in group['params']: 32 | if p.grad is None: 33 | continue 34 | 35 | grad = p.grad.data 36 | state = self.state[p] 37 | 38 | if len(state) == 0: 39 | state['gradients_sum'] = torch.zeros_like(p.data).cuda().float() 40 | state['grad_norm_sum'] = torch.zeros_like(p.data).cuda().float() 41 | state['L'] = self.epsilon * torch.ones_like(p.data).cuda().float() 42 | state['tilde_w'] = torch.zeros_like(p.data).cuda().float() 43 | state['reward'] = torch.zeros_like(p.data).cuda().float() 44 | 45 | gradients_sum = state['gradients_sum'] 46 | grad_norm_sum = state['grad_norm_sum'] 47 | tilde_w = state['tilde_w'] 48 | L = state['L'] 49 | reward = state['reward'] 50 | 51 | zero = torch.cuda.FloatTensor([0.]) 52 | 53 | if group['weight_decay'] != 0: 54 | grad = grad.add(p, alpha=group['weight_decay']) 55 | 56 | L_update = torch.max(L, torch.abs(grad)) 57 | gradients_sum_update = gradients_sum + grad 58 | grad_norm_sum_update = grad_norm_sum + torch.abs(grad) 59 | reward_update = torch.max(reward - grad * tilde_w, zero) 60 | new_w = -gradients_sum_update/(L_update * (torch.max(grad_norm_sum_update + L_update, self._alpha * L_update)))*(reward_update + L_update) 61 | p.data = p.data - tilde_w + new_w 62 | tilde_w_update = new_w 63 | 64 | state['gradients_sum'] = gradients_sum_update 65 | state['grad_norm_sum'] = grad_norm_sum_update 66 | state['L'] = L_update 67 | state['tilde_w'] = tilde_w_update 68 | state['reward'] = reward_update 69 | 70 | return loss -------------------------------------------------------------------------------- /torch_utils/predictor.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | import numpy as np 3 | import pandas as pd 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | torch.manual_seed(0) 8 | np.random.seed(0) 9 | 10 | class TorchPredictor(): 11 | def __init__(self, name, model, preprocessor=None, postprocessor=None, device='cpu', **kwargs): 12 | self.model = model 13 | self.device = device 14 | self.name = name 15 | self.checkpoint_path = pathlib.Path(kwargs.get('checkpoint_folder', f'./models/{name}_chkpts')) 16 | self.checkpoint_path.mkdir(parents=True, exist_ok=True) 17 | self.preprocessor = preprocessor 18 | self.postprocessor = postprocessor 19 | 20 | def _get_checkpoints(self, name=None): 21 | checkpoints = [] 22 | checkpoint_path = self.checkpoint_path if name is None else pathlib.Path(kwargs.get('checkpoint_folder', f'./models/{name}_chkpts')) 23 | for cp in self.checkpoint_path.glob('checkpoint_*'): 24 | checkpoint_name = str(cp).split('/')[-1] 25 | checkpoint_epoch = int(checkpoint_name.split('_')[-1]) 26 | checkpoints.append((cp, checkpoint_epoch)) 27 | checkpoints = sorted(checkpoints, key=lambda x: x[1], reverse=True) 28 | return checkpoints 29 | 30 | def _load_checkpoint(self, epoch=None, only_model=False, name=None): 31 | if name is None: 32 | checkpoints = self._get_checkpoints() 33 | else: 34 | checkpoints = self._get_checkpoints(name) 35 | if len(checkpoints) > 0: 36 | if not epoch: 37 | checkpoint_config = checkpoints[0] 38 | else: 39 | checkpoint_config = list(filter(lambda x: x[1] == epoch, checkpoints))[0] 40 | checkpoint = torch.load(checkpoint_config[0]) 41 | self.model.load_state_dict(checkpoint['model_state_dict']) 42 | print(f'loaded checkpoint for epoch - {checkpoint["epoch"]}') 43 | return checkpoint['epoch'] 44 | return None 45 | 46 | # pass single batch input, without batch axis 47 | def predict_one(self, x): 48 | self.model.eval() 49 | if self.preprocessor is not None: 50 | x = self.preprocessor(x) 51 | if type(x) is not torch.Tensor: 52 | x = torch.tensor(x, dtype=torch.float32) 53 | with torch.no_grad(): 54 | if type(x) is list: 55 | x = [xi.to(self.device).unsqueeze(0) for xi in x] 56 | else: 57 | x = x.to(self.device).unsqueeze(0) 58 | y_pred = self.model(x) 59 | if self.device == 'cuda': 60 | y_pred = y_pred.cpu() 61 | y_pred = y_pred.numpy() 62 | if self.postprocessor is not None: 63 | y_pred = self.postprocessor(y_pred) 64 | return y_pred 65 | -------------------------------------------------------------------------------- /torch_utils/trainer.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | import numpy as np 3 | import pandas as pd 4 | import torch 5 | from torch_lr_finder import LRFinder 6 | import torch.nn as nn 7 | import torch.nn.functional as F 8 | from torch.utils.tensorboard import SummaryWriter 9 | import tqdm 10 | from tqdm.notebook import tqdm 11 | import pickle 12 | 13 | def save_dict(path, name, _dict): 14 | with open(path/f'{name}.pickle', 'wb') as handle: 15 | pickle.dump(_dict, handle, protocol=pickle.HIGHEST_PROTOCOL) 16 | 17 | class TorchTrainer(): 18 | def __init__(self, name, model, optimizer, loss_fn, scheduler, device, **kwargs): 19 | self.model = model 20 | self.optimizer = optimizer 21 | self.scheduler = scheduler 22 | self.loss_fn = loss_fn 23 | self.device = device 24 | self.name = name 25 | self.checkpoint_path = pathlib.Path(kwargs.get('checkpoint_folder', f'./models/{name}_chkpts')) 26 | self.checkpoint_path.mkdir(parents=True, exist_ok=True) 27 | self.train_checkpoint_interval = kwargs.get('train_checkpoint_interval', 1) 28 | self.max_checkpoints = kwargs.get('max_checkpoints', 25) 29 | self.writer = SummaryWriter(f'runs/{name}') 30 | self.scheduler_batch_step = kwargs.get('scheduler_batch_step', False) 31 | self.additional_metric_fns = kwargs.get('additional_metric_fns', {}) 32 | self.additional_metric_fns = self.additional_metric_fns.items() 33 | self.pass_y = kwargs.get('pass_y', False) 34 | self.valid_losses = {} 35 | 36 | def _get_checkpoints(self, name=None): 37 | checkpoints = [] 38 | checkpoint_path = self.checkpoint_path if name is None else pathlib.Path(f'./models/{name}_chkpts') 39 | for cp in self.checkpoint_path.glob('checkpoint_*'): 40 | checkpoint_name = str(cp).split('/')[-1] 41 | checkpoint_epoch = int(checkpoint_name.split('_')[-1]) 42 | checkpoints.append((cp, checkpoint_epoch)) 43 | checkpoints = sorted(checkpoints, key=lambda x: x[1], reverse=True) 44 | #self.valid_losses = pd.read_pickle(self.checkpoint_path/'valid_losses.pickle') 45 | return checkpoints 46 | 47 | def _clean_outdated_checkpoints(self): 48 | checkpoints = self._get_checkpoints() 49 | if len(checkpoints) > self.max_checkpoints: 50 | checkpoints = sorted(checkpoints, key=lambda x: x[1], reverse=True) 51 | for delete_cp in checkpoints[self.max_checkpoints:]: 52 | delete_cp[0].unlink() 53 | print(f'removed checkpoint of epoch - {delete_cp[1]}') 54 | 55 | def _save_checkpoint(self, epoch, valid_loss=None): 56 | self._clean_outdated_checkpoints() 57 | checkpoint = { 58 | 'epoch': epoch, 59 | 'model_state_dict': self.model.state_dict(), 60 | 'optimizer_state_dict': [o.state_dict() for o in self.optimizer] if type(self.optimizer) is list else self.optimizer.state_dict(), 61 | } 62 | if self.scheduler is not None: 63 | checkpoint.update({ 64 | 'scheduler_state_dict': [o.state_dict() for o in self.scheduler] if type(self.scheduler) is list else self.scheduler.state_dict() 65 | }) 66 | if valid_loss: 67 | checkpoint.update({'loss': valid_loss}) 68 | torch.save(checkpoint, self.checkpoint_path/f'checkpoint_{epoch}') 69 | save_dict(self.checkpoint_path, 'valid_losses', self.valid_losses) 70 | print(f'saved checkpoint for epoch {epoch}') 71 | self._clean_outdated_checkpoints() 72 | 73 | def _load_checkpoint(self, epoch=None, only_model=False, name=None): 74 | if name is None: 75 | checkpoints = self._get_checkpoints() 76 | else: 77 | checkpoints = self._get_checkpoints(name) 78 | if len(checkpoints) > 0: 79 | if not epoch: 80 | checkpoint_config = checkpoints[0] 81 | else: 82 | checkpoint_config = list(filter(lambda x: x[1] == epoch, checkpoints))[0] 83 | checkpoint = torch.load(checkpoint_config[0]) 84 | self.model.load_state_dict(checkpoint['model_state_dict']) 85 | if not only_model: 86 | if type(self.optimizer) is list: 87 | for i in range(len(self.optimizer)): 88 | self.optimizer[i].load_state_dict(checkpoint['optimizer_state_dict'][i]) 89 | else: 90 | self.optimizer.load_state_dict(checkpoint['optimizer_state_dict']) 91 | if self.scheduler is not None: 92 | if type(self.scheduler) is list: 93 | for i in range(len(self.scheduler)): 94 | self.scheduler[i].load_state_dict(checkpoint['scheduler_state_dict'][i]) 95 | else: 96 | self.scheduler.load_state_dict(checkpoint['scheduler_state_dict']) 97 | print(f'loaded checkpoint for epoch - {checkpoint["epoch"]}') 98 | return checkpoint['epoch'] 99 | return None 100 | 101 | def _load_best_checkpoint(self): 102 | if self.valid_losses: 103 | best_epoch = sorted(self.valid_losses.items(), key=lambda x:x[1])[0][0] 104 | loaded_epoch = self._load_checkpoint(epoch=best_epoch, only_model=True) 105 | 106 | def _step_optim(self): 107 | if type(self.optimizer) is list: 108 | for i in range(len(self.optimizer)): 109 | self.optimizer[i].step() 110 | self.optimizer[i].zero_grad() 111 | else: 112 | self.optimizer.step() 113 | self.optimizer.zero_grad() 114 | 115 | def _step_scheduler(self, valid_loss=None): 116 | if type(self.scheduler) is list: 117 | for i in range(len(self.scheduler)): 118 | if self.scheduler[i].__class__.__name__ == 'ReduceLROnPlateau': 119 | self.scheduler[i].step(valid_loss) 120 | else: 121 | self.scheduler[i].step() 122 | else: 123 | if self.scheduler.__class__.__name__ == 'ReduceLROnPlateau': 124 | self.scheduler.step(valid_loss) 125 | else: 126 | self.scheduler.step() 127 | 128 | def _loss_batch(self, xb, yb, optimize, pass_y, additional_metrics=None): 129 | if type(xb) is list: 130 | xb = [xbi.to(self.device) for xbi in xb] 131 | else: 132 | xb = xb.to(self.device) 133 | yb = yb.to(self.device) 134 | if pass_y: 135 | y_pred = self.model(xb, yb) 136 | else: 137 | y_pred = self.model(xb) 138 | loss = self.loss_fn(y_pred, yb) 139 | if additional_metrics is not None: 140 | additional_metrics = [fn(y_pred, yb) for name, fn in additional_metrics] 141 | if optimize: 142 | loss.backward() 143 | self._step_optim() 144 | loss_value = loss.item() 145 | del xb 146 | del yb 147 | del y_pred 148 | del loss 149 | if additional_metrics is not None: 150 | return loss_value, additional_metrics 151 | return loss_value 152 | 153 | def evaluate(self, dataloader): 154 | self.model.eval() 155 | eval_bar = tqdm(dataloader, leave=False) 156 | with torch.no_grad(): 157 | loss_values = [self._loss_batch(xb, yb, False, False, self.additional_metric_fns) for xb, yb in eval_bar] 158 | if len(loss_values[0]) > 1: 159 | loss_value = np.mean([lv[0] for lv in loss_values]) 160 | additional_metrics = np.mean([lv[1] for lv in loss_values], axis=0) 161 | additional_metrics_result = {name: result for (name, fn), result in zip(self.additional_metric_fns, additional_metrics)} 162 | return loss_value, additional_metrics_result 163 | # eval_bar.set_description("evaluation loss %.2f" % loss_value) 164 | else: 165 | loss_value = np.mean(loss_values) 166 | return loss_value, None 167 | 168 | def predict(self, dataloader): 169 | self.model.eval() 170 | predictions = [] 171 | with torch.no_grad(): 172 | for xb, yb in tqdm(dataloader): 173 | if type(xb) is list: 174 | xb = [xbi.to(self.device) for xbi in xb] 175 | else: 176 | xb = xb.to(self.device) 177 | yb = yb.to(self.device) 178 | y_pred = self.model(xb) 179 | predictions.append(y_pred.cpu().numpy()) 180 | return np.concatenate(predictions) 181 | 182 | # pass single batch input, without batch axis 183 | def predict_one(self, x): 184 | self.model.eval() 185 | with torch.no_grad(): 186 | if type(x) is list: 187 | x = [xi.to(self.device).unsqueeze(0) for xi in x] 188 | else: 189 | x = x.to(self.device).unsqueeze(0) 190 | y_pred = self.model(x) 191 | if self.device == 'cuda': 192 | y_pred = y_pred.cpu() 193 | y_pred = y_pred.numpy() 194 | return y_pred 195 | 196 | def lr_find(self, dl, optimizer=None, start_lr=1e-7, end_lr=1e-2, num_iter=200): 197 | if optimizer is None: 198 | optimizer = torch.optim.SGD(self.model.parameters(), lr=1e-6, momentum=0.9) 199 | lr_finder = LRFinder(self.model, optimizer, self.loss_fn, device=self.device) 200 | lr_finder.range_test(dl, start_lr=start_lr, end_lr=end_lr, num_iter=num_iter) 201 | lr_finder.plot() 202 | 203 | def train(self, epochs, train_dataloader, valid_dataloader=None, resume=True, resume_only_model=False): 204 | start_epoch = 0 205 | if resume: 206 | loaded_epoch = self._load_checkpoint(only_model=resume_only_model) 207 | if loaded_epoch: 208 | start_epoch = loaded_epoch 209 | for i in tqdm(range(start_epoch, start_epoch + epochs), leave=True): 210 | self.model.train() 211 | training_losses = [] 212 | running_loss = 0 213 | training_bar = tqdm(train_dataloader, leave=False) 214 | for it, (xb, yb) in enumerate(training_bar): 215 | loss = self._loss_batch(xb, yb, True, self.pass_y) 216 | running_loss += loss 217 | training_bar.set_description("loss %.4f" % loss) 218 | if it % 100 == 99: 219 | self.writer.add_scalar('training loss', running_loss / 100, i * len(train_dataloader) + it) 220 | training_losses.append(running_loss / 100) 221 | running_loss = 0 222 | if self.scheduler is not None and self.scheduler_batch_step: 223 | self._step_scheduler() 224 | print(f'Training loss at epoch {i + 1} - {np.mean(training_losses)}') 225 | if valid_dataloader is not None: 226 | valid_loss, additional_metrics = self.evaluate(valid_dataloader) 227 | self.writer.add_scalar('validation loss', valid_loss, i) 228 | if additional_metrics is not None: 229 | print(additional_metrics) 230 | print(f'Valid loss at epoch {i + 1} - {valid_loss}') 231 | self.valid_losses[i+1] = valid_loss 232 | if self.scheduler is not None and not self.scheduler_batch_step: 233 | self._step_scheduler(valid_loss) 234 | if (i + 1) % self.train_checkpoint_interval == 0: 235 | self._save_checkpoint(i+1) 236 | 237 | -------------------------------------------------------------------------------- /ts_models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gautham20/pytorch-ts/4c7ddcfa6fcd4ae3dcf3b84f55a13d16b1687738/ts_models/__init__.py -------------------------------------------------------------------------------- /ts_models/decoders.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | class DecoderCell(nn.Module): 6 | def __init__(self, input_feature_len, hidden_size, dropout=0.2): 7 | super().__init__() 8 | self.decoder_rnn_cell = nn.GRUCell( 9 | input_size=input_feature_len, 10 | hidden_size=hidden_size, 11 | ) 12 | self.out = nn.Linear(hidden_size, 1) 13 | self.attention = False 14 | self.dropout = nn.Dropout(dropout) 15 | 16 | def forward(self, prev_hidden, y): 17 | rnn_hidden = self.decoder_rnn_cell(y, prev_hidden) 18 | output = self.out(rnn_hidden) 19 | return output, self.dropout(rnn_hidden) 20 | 21 | 22 | class AttentionDecoderCell(nn.Module): 23 | def __init__(self, input_feature_len, hidden_size, sequence_len, dropout=0.2): 24 | super().__init__() 25 | # attention - inputs - (decoder_inputs, prev_hidden) 26 | self.attention_linear = nn.Linear(hidden_size + input_feature_len, sequence_len) 27 | self.attention = True 28 | # attention_combine - inputs - (decoder_inputs, attention * encoder_outputs) 29 | self.decoder_rnn_cell = nn.GRUCell( 30 | input_size=hidden_size, 31 | hidden_size=hidden_size, 32 | ) 33 | self.dropout = nn.Dropout(dropout) 34 | self.out = nn.Linear(hidden_size, 1) 35 | 36 | def forward(self, encoder_output, prev_hidden, y): 37 | attention_input = torch.cat((prev_hidden, y), axis=1) 38 | attention_weights = F.softmax(self.attention_linear(attention_input)).unsqueeze(1) 39 | attention_combine = torch.bmm(attention_weights, encoder_output).squeeze(1) 40 | rnn_hidden = self.decoder_rnn_cell(attention_combine, prev_hidden) 41 | output = self.out(rnn_hidden) 42 | return output, self.dropout(rnn_hidden) 43 | -------------------------------------------------------------------------------- /ts_models/encoder_decoder.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | 5 | class EncoderDecoderWrapper(nn.Module): 6 | def __init__(self, encoder, decoder_cell, output_size=3, teacher_forcing=0.3, sequence_len=336, decoder_input=True, device='cpu'): 7 | super().__init__() 8 | self.encoder = encoder 9 | self.decoder_cell = decoder_cell 10 | self.output_size = output_size 11 | self.teacher_forcing = teacher_forcing 12 | self.sequence_length = sequence_len 13 | self.decoder_input = decoder_input 14 | self.device = device 15 | 16 | def forward(self, xb, yb=None): 17 | if self.decoder_input: 18 | decoder_input = xb[-1] 19 | input_seq = xb[0] 20 | if len(xb) > 2: 21 | encoder_output, encoder_hidden = self.encoder(input_seq, *xb[1:-1]) 22 | else: 23 | encoder_output, encoder_hidden = self.encoder(input_seq) 24 | else: 25 | if type(xb) is list and len(xb) > 1: 26 | input_seq = xb[0] 27 | encoder_output, encoder_hidden = self.encoder(*xb) 28 | else: 29 | input_seq = xb 30 | encoder_output, encoder_hidden = self.encoder(input_seq) 31 | prev_hidden = encoder_hidden 32 | outputs = torch.zeros(input_seq.size(0), self.output_size, device=self.device) 33 | y_prev = input_seq[:, -1, 0].unsqueeze(1) 34 | for i in range(self.output_size): 35 | step_decoder_input = torch.cat((y_prev, decoder_input[:, i]), axis=1) 36 | if (yb is not None) and (i > 0) and (torch.rand(1) < self.teacher_forcing): 37 | step_decoder_input = torch.cat((yb[:, i].unsqueeze(1), decoder_input[:, i]), axis=1) 38 | rnn_output, prev_hidden = self.decoder_cell(prev_hidden, step_decoder_input) 39 | y_prev = rnn_output 40 | outputs[:, i] = rnn_output.squeeze(1) 41 | return outputs 42 | -------------------------------------------------------------------------------- /ts_models/encoders.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | class RNNInitEncoder(nn.Module): 6 | def __init__(self, embed_sizes, rnn_num_layers=1, input_feature_len=1, sequence_len=168, hidden_size=100, bidirectional=False, device='cpu'): 7 | super().__init__() 8 | self.sequence_len = sequence_len 9 | self.hidden_size = hidden_size 10 | self.input_feature_len = input_feature_len 11 | self.num_layers = rnn_num_layers 12 | self.rnn_directions = 2 if bidirectional else 1 13 | self.embeds = nn.ModuleList([nn.Embedding(num_classes, output_size) for num_classes, output_size in embed_sizes]) 14 | self.embed_to_ht = nn.Linear(sum([s[1] for s in embed_sizes]), self.hidden_size) 15 | self.gru = nn.GRU( 16 | num_layers = rnn_num_layers, 17 | input_size=input_feature_len, 18 | hidden_size=hidden_size, 19 | batch_first=True, 20 | bidirectional=bidirectional 21 | ) 22 | self.device = device 23 | 24 | def forward(self, input_seq, input_cat): 25 | embeds = [e(input_cat[:, i]) for i, e in enumerate(self.embeds)] 26 | embeds = torch.cat(embeds, 1) 27 | ht = self.embed_to_ht(embeds) 28 | ht.unsqueeze_(0) 29 | if (self.num_layers * self.rnn_directions) > 1: 30 | ht = ht.repeat(self.rnn_directions * self.num_layers, 1, 1) 31 | if input_seq.ndim < 3: 32 | input_seq.unsqueeze_(2) 33 | gru_out, hidden = self.gru(input_seq, ht) 34 | if self.rnn_directions > 1: 35 | gru_out = gru_out.view(input_seq.size(0), self.sequence_len, self.rnn_directions, self.hidden_size) 36 | gru_out = torch.sum(gru_out, axis=2) 37 | return gru_out, hidden.squeeze(0) 38 | 39 | 40 | class RNNConcatEncoder(nn.Module): 41 | def __init__(self, embed_sizes, rnn_num_layers=1, input_feature_len=1, sequence_len=168, hidden_size=100, bidirectional=False, device='cpu'): 42 | super().__init__() 43 | self.sequence_len = sequence_len 44 | self.hidden_size = hidden_size 45 | self.embeds = nn.ModuleList([nn.Embedding(num_classes, output_size) for num_classes, output_size in embed_sizes]) 46 | self.input_feature_len = input_feature_len 47 | self.num_layers = rnn_num_layers 48 | self.rnn_directions = 2 if bidirectional else 1 49 | self.gru = nn.GRU( 50 | num_layers = rnn_num_layers, 51 | input_size=input_feature_len, 52 | hidden_size=hidden_size, 53 | batch_first=True, 54 | bidirectional=bidirectional 55 | ) 56 | self.output_linear = nn.Linear(hidden_size + sum([s[1] for s in embed_sizes]), hidden_size) 57 | self.device = device 58 | 59 | def forward(self, input_seq, input_cat): 60 | embeds = [e(input_cat[:, i]) for i, e in enumerate(self.embeds)] 61 | embeds = torch.cat(embeds, 1) 62 | ht = torch.zeros(self.num_layers * self.rnn_directions, input_seq.size(0) , self.hidden_size, device=self.device) 63 | if input_seq.ndim < 3: 64 | input_seq.unsqueeze_(2) 65 | gru_out, hidden = self.gru(input_seq, ht) 66 | if self.rnn_directions > 1: 67 | gru_out = gru_out.view(input_seq.size(0), self.sequence_len, self.rnn_directions, self.hidden_size) 68 | gru_out = torch.sum(gru_out, axis=2) 69 | encoder_concat_hidden = self.output_linear(torch.cat((hidden.squeeze(0), embeds), axis=1)) 70 | return gru_out, encoder_concat_hidden 71 | 72 | 73 | #output shape 74 | # bidirectional output is summed 75 | # gru_out - (batch, sequence_len, hidden_size) 76 | # hidden - (batch, hidden_size) only the last layer for multi-layer 77 | class RNNEncoder(nn.Module): 78 | def __init__(self, rnn_num_layers=1, input_feature_len=1, sequence_len=168, hidden_size=100, bidirectional=False, device='cpu', rnn_dropout=0.2): 79 | super().__init__() 80 | self.sequence_len = sequence_len 81 | self.hidden_size = hidden_size 82 | self.input_feature_len = input_feature_len 83 | self.num_layers = rnn_num_layers 84 | self.rnn_directions = 2 if bidirectional else 1 85 | self.gru = nn.GRU( 86 | num_layers=rnn_num_layers, 87 | input_size=input_feature_len, 88 | hidden_size=hidden_size, 89 | batch_first=True, 90 | bidirectional=bidirectional, 91 | dropout=rnn_dropout 92 | ) 93 | self.device = device 94 | 95 | def forward(self, input_seq): 96 | ht = torch.zeros(self.num_layers * self.rnn_directions, input_seq.size(0), self.hidden_size, device=self.device) 97 | if input_seq.ndim < 3: 98 | input_seq.unsqueeze_(2) 99 | gru_out, hidden = self.gru(input_seq, ht) 100 | print(gru_out.shape) 101 | print(hidden.shape) 102 | if self.rnn_directions * self.num_layers > 1: 103 | num_layers = self.rnn_directions * self.num_layers 104 | if self.rnn_directions > 1: 105 | gru_out = gru_out.view(input_seq.size(0), self.sequence_len, self.rnn_directions, self.hidden_size) 106 | gru_out = torch.sum(gru_out, axis=2) 107 | hidden = hidden.view(self.num_layers, self.rnn_directions, input_seq.size(0), self.hidden_size) 108 | if self.num_layers > 0: 109 | hidden = hidden[-1] 110 | else: 111 | hidden = hidden.squeeze(0) 112 | hidden = hidden.sum(axis=0) 113 | else: 114 | hidden.squeeze_(0) 115 | return gru_out, hidden 116 | -------------------------------------------------------------------------------- /ts_models/model_utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gautham20/pytorch-ts/4c7ddcfa6fcd4ae3dcf3b84f55a13d16b1687738/ts_models/model_utils/__init__.py -------------------------------------------------------------------------------- /ts_models/model_utils/utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | def is_listy(x): return isinstance(x, (tuple,list)) 5 | 6 | class Hook(): 7 | def __init__(self, m, hook_func, is_forward, detach): 8 | self.hook_func ,self.detach ,self.stored = hook_func, detach, None 9 | f = m.register_forward_hook if is_forward else m.register_backward_hook 10 | self.hook = f(self.hook_fn) 11 | self.removed = False 12 | 13 | def hook_fn(self, module, input, output): 14 | if self.detach: 15 | input = (o.detach() for o in input ) if is_listy(input) else input.detach() 16 | output = (o.detach() for o in output) if is_listy(output) else output.detach() 17 | self.stored = self.hook_func(module, input, output) 18 | 19 | def remove(self): 20 | if not self.removed: 21 | self.hook.remove() 22 | self.removed=True 23 | 24 | def __enter__(self, *args): return self 25 | def __exit__(self, *args): self.remove() 26 | 27 | def get_named_module_from_model(model, name): 28 | for n, m in model.named_modules(): 29 | if n == name: 30 | return m 31 | return None 32 | -------------------------------------------------------------------------------- /ts_utils/sequence_builder.py: -------------------------------------------------------------------------------- 1 | import traceback 2 | import tqdm 3 | import numpy as np 4 | import pandas as pd 5 | from functools import partial 6 | from tqdm.contrib.concurrent import process_map 7 | from collections import defaultdict 8 | 9 | tqdm.tqdm().pandas() 10 | 11 | def reduce_mem_usage(df, verbose=True): 12 | numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64'] 13 | start_mem = df.memory_usage().sum() / 1024**2 14 | for col in df.columns: 15 | col_type = df[col].dtypes 16 | if col_type in numerics: 17 | c_min = df[col].min() 18 | c_max = df[col].max() 19 | if str(col_type)[:3] == 'int': 20 | if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max: 21 | df[col] = df[col].astype(np.int8) 22 | elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max: 23 | df[col] = df[col].astype(np.int16) 24 | elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max: 25 | df[col] = df[col].astype(np.int32) 26 | elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max: 27 | df[col] = df[col].astype(np.int64) 28 | else: 29 | if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max: 30 | df[col] = df[col].astype(np.float16) 31 | elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max: 32 | df[col] = df[col].astype(np.float32) 33 | else: 34 | df[col] = df[col].astype(np.float64) 35 | end_mem = df.memory_usage().sum() / 1024**2 36 | if verbose: 37 | print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem)) 38 | return df 39 | 40 | 41 | def split_sequence_difference(group_data, n_steps_in, n_steps_out, x_cols, y_col, diff, additional_columns): 42 | try: 43 | X, y = list(), list() 44 | additional_col_map = defaultdict(list) 45 | group_data[y_col] = group_data[y_col].diff() 46 | additional_col_map['x_base'] = [] 47 | additional_col_map['y_base'] = [] 48 | additional_col_map['mean_traffic'] = [] 49 | for i in range(diff, len(group_data)): 50 | # find the end of this pattern 51 | x_base = group_data.iloc[i - 1]['unmod_y'] 52 | end_ix = i + n_steps_in 53 | out_end_ix = end_ix + n_steps_out 54 | # check if we are beyond the dataset 55 | if out_end_ix > len(group_data)-1: 56 | break 57 | y_base = group_data.iloc[end_ix - 1]['unmod_y'] 58 | # gather input and output parts of the pattern 59 | if len(x_cols) == 1: 60 | x_cols = x_cols[0] 61 | seq_x, seq_y = group_data.iloc[i:end_ix, :][x_cols].values, group_data.iloc[end_ix:out_end_ix, :][y_col].values 62 | for col in additional_columns: 63 | additional_col_map[col].append(group_data.iloc[end_ix][col]) 64 | additional_col_map['x_base'].append(x_base) 65 | additional_col_map['y_base'].append(y_base) 66 | additional_col_map['mean_traffic'] = group_data['unmod_y'].mean() 67 | X.append(seq_x) 68 | y.append(seq_y) 69 | additional_column_items = sorted(additional_col_map.items(), key=lambda x: x[0]) 70 | return (np.array(X), np.array(y), *[i[1] for i in additional_column_items]) 71 | except Exception as e: 72 | print(e) 73 | print(group_data.shape) 74 | traceback.print_exc() 75 | 76 | # split a multivariate sequence into samples 77 | def split_sequences(group_data, n_steps_in, n_steps_out, x_cols, y_cols, additional_columns, step=1, lag_fns=[]): 78 | X, y = list(), list() 79 | additional_col_map = defaultdict(list) 80 | group_data = group_data.sort_values('date') 81 | for i, lag_fn in enumerate(lag_fns): 82 | group_data[f'lag_{i}'] = lag_fn(group_data[y_cols[0]]) 83 | steps = list(range(0, len(group_data), step)) 84 | if step != 1 and steps[-1] != (len(group_data) - 1): 85 | steps.append((len(group_data) - 1)) 86 | for i in steps: 87 | # find the end of this pattern 88 | end_ix = i + n_steps_in 89 | out_end_ix = end_ix + n_steps_out 90 | # check if we are beyond the dataset 91 | if out_end_ix > len(group_data): 92 | break 93 | # gather input and output parts of the pattern 94 | if len(x_cols) == 1: 95 | x_cols = x_cols[0] 96 | seq_x, seq_y = group_data.iloc[i:end_ix, :][x_cols].values, group_data.iloc[end_ix:out_end_ix, :][y_cols + [f'lag_{i}' for i in range(len(lag_fns))]].values 97 | for col in additional_columns: 98 | additional_col_map[col].append(group_data.iloc[end_ix][col]) 99 | X.append(seq_x) 100 | y.append(seq_y) 101 | additional_column_items = sorted(additional_col_map.items(), key=lambda x: x[0]) 102 | return (np.array(X), np.array(y), *[i[1] for i in additional_column_items]) 103 | 104 | def _apply_df(args): 105 | df, func, key_column = args 106 | result = df.groupby(key_column).progress_apply(func) 107 | return result 108 | 109 | def almost_equal_split(seq, num): 110 | avg = len(seq) / float(num) 111 | out = [] 112 | last = 0.0 113 | while last < len(seq): 114 | out.append(seq[int(last):int(last + avg)]) 115 | last += avg 116 | return out 117 | 118 | 119 | def mp_apply(df, func, key_column): 120 | workers = 6 121 | # pool = mp.Pool(processes=workers) 122 | key_splits = almost_equal_split(df[key_column].unique(), workers) 123 | split_dfs = [df[df[key_column].isin(key_list)] for key_list in key_splits] 124 | result = process_map(_apply_df, [(d, func, key_column) for d in split_dfs], max_workers=workers) 125 | return pd.concat(result) 126 | 127 | def sequence_builder(data, n_steps_in, n_steps_out, key_column, x_cols, y_col, y_cols, additional_columns, diff=False, lag_fns=[], step=1): 128 | if diff: 129 | # multiple y_cols not supported yet 130 | sequence_fn = partial( 131 | split_sequence_difference, 132 | n_steps_in=n_steps_in, 133 | n_steps_out=n_steps_out, 134 | x_cols=x_cols, 135 | y_col=y_col, 136 | diff=diff, 137 | additional_columns=list(set([key_column] + additional_columns)) 138 | ) 139 | data['unmod_y'] = data[y_col] 140 | sequence_data = mp_apply( 141 | data[list(set([key_column] + x_cols + [y_col, 'unmod_y'] + y_cols + additional_columns))], 142 | sequence_fn, 143 | key_column 144 | ) 145 | else: 146 | # first entry in y_cols should be the target variable 147 | sequence_fn = partial( 148 | split_sequences, 149 | n_steps_in=n_steps_in, 150 | n_steps_out=n_steps_out, 151 | x_cols=x_cols, 152 | y_cols=y_cols, 153 | additional_columns=list(set([key_column] + additional_columns)), 154 | lag_fns=lag_fns, 155 | step=step 156 | ) 157 | sequence_data = mp_apply( 158 | data[list(set([key_column] + x_cols + y_cols + additional_columns))], 159 | sequence_fn, 160 | key_column 161 | ) 162 | sequence_data = pd.DataFrame(sequence_data, columns=['result']) 163 | s = sequence_data.apply(lambda x: pd.Series(zip(*[col for col in x['result']])), axis=1).stack().reset_index(level=1, drop=True) 164 | s.name = 'result' 165 | sequence_data = sequence_data.drop('result', axis=1).join(s) 166 | sequence_data['result'] = pd.Series(sequence_data['result']) 167 | if diff: 168 | sequence_data[['x_sequence', 'y_sequence'] + sorted(set([key_column] + additional_columns + ['x_base', 'y_base', 'mean_traffic']))] = pd.DataFrame(sequence_data.result.values.tolist(), index=sequence_data.index) 169 | else: 170 | sequence_data[['x_sequence', 'y_sequence'] + sorted(set([key_column] + additional_columns))] = pd.DataFrame(sequence_data.result.values.tolist(), index=sequence_data.index) 171 | sequence_data.drop('result', axis=1, inplace=True) 172 | if key_column in sequence_data.columns: 173 | sequence_data.drop(key_column, axis=1, inplace=True) 174 | sequence_data = sequence_data.reset_index() 175 | print(sequence_data.shape) 176 | sequence_data = sequence_data[~sequence_data['x_sequence'].isnull()] 177 | return sequence_data 178 | 179 | 180 | def last_year_lag(col): return (col.shift(364) * 0.25) + (col.shift(365) * 0.5) + (col.shift(366) * 0.25) 181 | 182 | if __name__ == '__main__': 183 | data = reduce_mem_usage(pd.read_pickle('../data/processed_data_test_stdscaler.pkl')) 184 | sequence_data = sequence_builder(data, 180, 90, 185 | 'store_item_id', 186 | ['sales', 'dayofweek_sin', 'dayofweek_cos', 'month_sin', 'month_cos', 'year_mod', 'day_sin', 'day_cos'], 187 | 'sales', 188 | ['sales', 'dayofweek_sin', 'dayofweek_cos', 'month_sin', 'month_cos', 'year_mod', 'day_sin', 'day_cos'], 189 | ['item', 'store', 'date', 'yearly_corr'], 190 | lag_fns=[last_year_lag] 191 | ) 192 | sequence_data.to_pickle('../sequence_data/sequence_data_stdscaler_test.pkl') 193 | --------------------------------------------------------------------------------