├── LICENSE ├── README.md ├── model └── params.yaml ├── notebook └── forecast.ipynb ├── requirements.txt └── scripts ├── inference.py ├── interpret.py ├── preprocess.py └── train.py /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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Multivariate Time Series Forecasting with Deep Learning 2 | 3 | Forecasting, making predictions about the future, plays a key role in the decision-making process of any company that wants to maintain a successful business. This is due to the fact that success tomorrow is determined by the decisions made today, which are based on forecasts. Hence, good forecasts are crucial, for example, for predicting sales to better plan inventory, forecasting economic activity to inform business development decisions, or even predicting the movement of people across an organization to improve personnel planning. 4 | 5 | Here, we demonstrate how to leverage multiple historical time series in conjunction with Recurrent Neural Networks (RNN), specifically Long Short-Term Memory (LSTM) networks, to make predictions about the future. Furthermore, we use a method based on DeepLIFT to interpret the results. 6 | 7 | We choose this modeling approach because it delivers state-of-the-art performance in settings where traditional methods are not suitable. In particular, when the time series data is complex, meaning trends and patterns change over time, and along with seasonal components, if existent, are not easily identifiable, deep learning methods like LSTM networks achieve better results than traditional methods such as ARMA (Auto-Regressive Moving Average). Originally developed for Natural Language Processing (NLP) tasks, LSTM models have made their way into the time series forecasting domain because, as with text, time series data occurs in sequence and temporal relationships between different parts of the sequence matter for determining a prediction outcome. 8 | 9 | Additionally, we want to shed some light on the trained neural network by finding the important features that contribute most to the predictions. 10 | 11 | The example we use is to forecast the future price of Bitcoin based on historical times series of Bitcoin itself, as well as other features such as trading volume and date-derived features. We choose the price of Bitcoin because it exemplifies the dynamically changing, behavioral aspects of decisions made by individual Bitcoin investors when they decide to buy or sell the asset. These aspects do also appear in other forecasting problems such as those mentioned in the introduction. 12 | 13 | ## Blog Post 14 | 15 | [Medium / Towards Data Science blog post](https://towardsdatascience.com/multivariate-time-series-forecasting-with-deep-learning-3e7b3e2d2bcf) 16 | 17 | ## Installation 18 | 19 | ``` 20 | git clone https://github.com/danielhkt/deep-forecasting.git 21 | conda create -n py39 python=3.9 22 | conda activate py39 23 | cd deep-forecasting 24 | pip install -r requirements.txt 25 | ``` 26 | 27 | ## Download Data 28 | 29 | Download the [data](https://finance.yahoo.com/quote/BTC-USD/history?p=BTC-USD) and create a 'data' folder for the downloaded file. 30 | 31 | ## Run in Notebook 32 | 33 | An example notebook to run the entire pipeline and print/visualize the results in included in ../notebook. 34 | Update the parameters in /model/params.yaml if necessary. 35 | 36 | ## Run in Terminal 37 | 38 | The python scripts to prepare the data, train and evaluate the model, as well as interpret the model, 39 | are stored in ../scripts. The parameters used for training and interpreting the model are stored in 40 | ../model/params.yaml. The data and model outputs are stored in the /data and /model folders, respectively. 41 | Update the parameters in /model/params.yaml if necessary. 42 | 43 | 1. Prepare the data: 44 | ``` 45 | python preprocess.py 46 | ``` 47 | 2. Train the model: 48 | ``` 49 | python train.py 50 | ``` 51 | 3. Evaluate the model: 52 | ``` 53 | python inference.py 54 | ``` 55 | 4. Interpret the trained model: 56 | ``` 57 | python interpret.py 58 | ``` 59 | 60 | ## Credits 61 | 62 | * Packages: 63 | * [PyTorch](https://pytorch.org/) 64 | * [SHAP](https://shap-lrjball.readthedocs.io/en/latest/generated/shap.DeepExplainer.html) 65 | 66 | * Datasets: 67 | * [Bitcoin prices](https://finance.yahoo.com/quote/BTC-USD/history?p=BTC-USD) 68 | 69 | 70 | * Models: 71 | * LSTM (Hochreiter and Schmidhuber. “Long Short-term Memory”. 1997) 72 | * DeepLIFT (Shrikumar, Greenside, and Kundaje. “Learning Important Features Through Propagating Activation Differences”. 2017) 73 | 74 | ## License 75 | 76 | This project is licensed under the Apache-2.0 License. 77 | -------------------------------------------------------------------------------- /model/params.yaml: -------------------------------------------------------------------------------- 1 | { 2 | 'file_name' : 'BTC-USD.csv', 3 | 'data_dir' : '../data', 4 | 'model_dir' : '../model', 5 | 'label_name' : 'Close', 6 | 'train_frac' : 0.5, 7 | 'sequence_length' : 30, 8 | 'batch_size' : 8, 9 | 'n_epochs' : 20, 10 | 'n_epochs_stop' : 5, 11 | 'background_data_size' : 900, 12 | 'test_sample_size' : 100 13 | } -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | joblib 2 | torch 3 | scikit-learn==0.21.3 4 | pyyaml 5 | shap -------------------------------------------------------------------------------- /scripts/inference.py: -------------------------------------------------------------------------------- 1 | """ Module for model inference. """ 2 | 3 | 4 | import yaml 5 | import argparse 6 | import joblib 7 | import numpy as np 8 | from pathlib import Path 9 | from sklearn import metrics 10 | from sklearn.preprocessing import MinMaxScaler 11 | import torch 12 | from torch.utils.data import DataLoader 13 | from train import TimeSeriesDataset, TSModel 14 | import preprocess 15 | 16 | 17 | with open("../model/params.yaml", "r") as params_file: 18 | params = yaml.safe_load(params_file) 19 | 20 | model_dir = params['model_dir'] 21 | 22 | 23 | def descale( 24 | descaler, 25 | values 26 | ): 27 | values_2d = np.array(values)[:, np.newaxis] 28 | return descaler.inverse_transform(values_2d).flatten() 29 | 30 | 31 | def predict( 32 | df, 33 | label_name, 34 | sequence_length 35 | ): 36 | """Make predictions.""" 37 | 38 | model = TSModel(df.shape[1]) 39 | model.load_state_dict(torch.load(Path(model_dir, 'model.pt'))) 40 | model.eval() 41 | 42 | test_dataset = TimeSeriesDataset(np.array(df), np.array(df[label_name]), seq_len=sequence_length) 43 | test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False) 44 | 45 | predictions = [] 46 | labels = [] 47 | with torch.no_grad(): 48 | for features, target in test_loader: 49 | features = torch.Tensor(np.array(features)) 50 | output = model(features) 51 | predictions.append(output.item()) 52 | labels.append(target.item()) 53 | 54 | # bring predictions back to original scale 55 | scaler = joblib.load(Path(model_dir, 'scaler.gz')) 56 | descaler = MinMaxScaler() 57 | descaler.min_, descaler.scale_ = scaler.min_[0], scaler.scale_[0] 58 | predictions_descaled = descale(descaler, predictions) 59 | labels_descaled = descale(descaler, labels) 60 | 61 | return predictions_descaled, labels_descaled 62 | 63 | 64 | def print_loss_metrics( 65 | y_true, 66 | y_pred, 67 | ): 68 | print('RMSE: ', round(np.sqrt(metrics.mean_squared_error(y_true, y_pred)), 2)) 69 | print('MAE: ', round(metrics.mean_absolute_error(y_true, y_pred), 2)) 70 | 71 | return None 72 | 73 | 74 | if __name__ == "__main__": 75 | parser = argparse.ArgumentParser() 76 | parser.add_argument("--sequence-length", type=int, default=params['sequence_length']) 77 | parser.add_argument("--eval-size", type=int, default=30) 78 | args = parser.parse_args() 79 | 80 | test_df = preprocess.load_data('test.csv') 81 | label_name = params['label_name'] 82 | 83 | predictions_descaled, labels_descaled = predict(test_df, 84 | label_name, 85 | args.sequence_length) 86 | 87 | # print('Error on all test data:') 88 | # print_loss_metrics(labels_descaled, predictions_descaled) 89 | 90 | print('Error on partial test data:') 91 | print_loss_metrics(labels_descaled[:args.eval_size], predictions_descaled[:args.eval_size]) 92 | -------------------------------------------------------------------------------- /scripts/interpret.py: -------------------------------------------------------------------------------- 1 | """ Module for model interpretation. """ 2 | 3 | 4 | import yaml 5 | import argparse 6 | import numpy as np 7 | import pandas as pd 8 | from pathlib import Path 9 | import shap 10 | import torch 11 | from torch.utils.data import DataLoader 12 | from train import TimeSeriesDataset, TSModel 13 | import preprocess 14 | 15 | 16 | with open("../model/params.yaml", "r") as params_file: 17 | params = yaml.safe_load(params_file) 18 | 19 | data_dir = params['data_dir'] 20 | model_dir = params['model_dir'] 21 | 22 | 23 | def get_important_features( 24 | background_data_size, 25 | test_sample_size, 26 | sequence_length 27 | ): 28 | # load data 29 | train_df = preprocess.load_data('train.csv') 30 | test_df = preprocess.load_data('test.csv') 31 | label_name = params['label_name'] 32 | 33 | # load trained model 34 | model = TSModel(train_df.shape[1]) 35 | model.load_state_dict(torch.load(Path(model_dir, 'model.pt'))) 36 | model.eval() 37 | 38 | # get background dataset 39 | train_dataset = TimeSeriesDataset(np.array(train_df), np.array(train_df[label_name]), seq_len=sequence_length) 40 | train_loader = DataLoader(train_dataset, batch_size=background_data_size, shuffle=False) 41 | background_data, _ = next(iter(train_loader)) 42 | 43 | # get test data samples on which to explain the model’s output 44 | test_dataset = TimeSeriesDataset(np.array(test_df), np.array(test_df[label_name]), seq_len=sequence_length) 45 | test_loader = DataLoader(test_dataset, batch_size=test_sample_size, shuffle=False) 46 | test_sample_data, _ = next(iter(test_loader)) 47 | 48 | # integrate out feature importances based on background dataset 49 | e = shap.DeepExplainer(model, torch.Tensor(np.array(background_data))) 50 | 51 | # explain the model's outputs on some data samples 52 | shap_values = e.shap_values(torch.Tensor(np.array(test_sample_data))) 53 | shap_values = np.absolute(shap_values) 54 | shap_values = np.mean(shap_values, axis=0) 55 | 56 | # save output 57 | pd.DataFrame(shap_values).to_csv(Path(data_dir, "shap_values.csv"), index=False) 58 | 59 | return shap_values 60 | 61 | 62 | if __name__ == "__main__": 63 | parser = argparse.ArgumentParser() 64 | parser.add_argument("--background-data-size", type=int, default=params['background_data_size']) 65 | parser.add_argument("--test-sample-size", type=int, default=params['test_sample_size']) 66 | parser.add_argument("--sequence-length", type=int, default=params['sequence_length']) 67 | args = parser.parse_args() 68 | 69 | print("Getting important features...") 70 | get_important_features( 71 | args.background_data_size, 72 | args.test_sample_size, 73 | args.sequence_length 74 | ) 75 | print("Completed.") 76 | -------------------------------------------------------------------------------- /scripts/preprocess.py: -------------------------------------------------------------------------------- 1 | """ Module for data preparation. """ 2 | 3 | 4 | import yaml 5 | import joblib 6 | import argparse 7 | import pandas as pd 8 | from pathlib import Path 9 | from sklearn.preprocessing import MinMaxScaler 10 | 11 | 12 | with open("../model/params.yaml", "r") as params_file: 13 | params = yaml.safe_load(params_file) 14 | 15 | data_dir = params['data_dir'] 16 | model_dir = params['model_dir'] 17 | 18 | 19 | def load_data( 20 | file_name 21 | ): 22 | data = pd.read_csv(Path(data_dir, file_name)) 23 | return data 24 | 25 | 26 | def save_data( 27 | df, 28 | file_name 29 | ): 30 | df.to_csv(Path(data_dir, file_name), index=False) 31 | return None 32 | 33 | 34 | def clean_data( 35 | df 36 | ): 37 | """Sort by date and drop NA values.""" 38 | # sort by date 39 | df_clean = df.sort_values(by='Date').reset_index(drop=True) 40 | # drop NaN 41 | df_clean = df_clean.dropna() 42 | 43 | return df_clean 44 | 45 | 46 | def create_features( 47 | df 48 | ): 49 | """Creates new features.""" 50 | 51 | # add date-derived features 52 | df['Day_Of_Week'] = pd.DatetimeIndex(df['Date']).dayofweek 53 | df['Month_Of_Year'] = pd.DatetimeIndex(df['Date']).month 54 | df['Quarter_Of_Year'] = pd.DatetimeIndex(df['Date']).quarter 55 | 56 | # add intraday gaps 57 | df['High_Low_Pct'] = (df.High - df.Low) / df.Low # percentage intraday change 58 | df['Open_Close_Pct'] = (df.Open.shift(-1) - df.Close) / df.Close # percentage change using next day open 59 | 60 | # drop rows with missing values 61 | df = df.dropna() 62 | 63 | return df 64 | 65 | 66 | def split_data( 67 | df, 68 | train_frac 69 | ): 70 | train_size = int(len(df) * train_frac) 71 | train_df, test_df = df[:train_size], df[train_size:] 72 | 73 | return train_df, test_df, train_size 74 | 75 | 76 | def rescale_data( 77 | df 78 | ): 79 | """Rescale all features using MinMaxScaler() to same scale, between 0 and 1.""" 80 | 81 | scaler = MinMaxScaler() 82 | scaler = scaler.fit(df) 83 | 84 | df_scaled = pd.DataFrame( 85 | scaler.transform(df), 86 | index=df.index, 87 | columns=df.columns) 88 | 89 | # save trained data scaler 90 | joblib.dump(scaler, Path(model_dir, 'scaler.gz')) 91 | 92 | return df_scaled 93 | 94 | 95 | def prep_data( 96 | df, 97 | train_frac, 98 | plot_df=False 99 | ): 100 | print("Starting with data preparation...") 101 | df_clean = clean_data(df) 102 | df_clean = create_features(df_clean) 103 | 104 | # split into train/test datasets 105 | train_df, test_df, train_size = split_data(df_clean, train_frac) 106 | 107 | # subset data 108 | train_df = train_df[['Close', 'Volume', 'High_Low_Pct', 'Open_Close_Pct', 109 | 'Day_Of_Week', 'Month_Of_Year', 'Quarter_Of_Year']] 110 | test_df = test_df[['Close', 'Volume', 'High_Low_Pct', 'Open_Close_Pct', 111 | 'Day_Of_Week', 'Month_Of_Year', 'Quarter_Of_Year']] 112 | 113 | if plot_df: 114 | save_data(train_df, 'plot_df.csv') 115 | 116 | # rescale data 117 | train_df = rescale_data(train_df) 118 | 119 | scaler = joblib.load(Path(model_dir, 'scaler.gz')) 120 | test_df = pd.DataFrame( 121 | scaler.transform(test_df), 122 | index=test_df.index, 123 | columns=test_df.columns) 124 | 125 | # save data 126 | save_data(train_df, 'train.csv') 127 | save_data(test_df, 'test.csv') 128 | print("Completed.") 129 | 130 | return train_df, test_df 131 | 132 | 133 | if __name__ == "__main__": 134 | parser = argparse.ArgumentParser() 135 | parser.add_argument("--file-name", type=str, default=params['file_name']) 136 | parser.add_argument("--train-frac", type=float, default=params['train_frac']) 137 | args = parser.parse_args() 138 | 139 | df = load_data(args.file_name) 140 | prep_data(df, args.train_frac) 141 | -------------------------------------------------------------------------------- /scripts/train.py: -------------------------------------------------------------------------------- 1 | """ Module for model training. """ 2 | 3 | 4 | import yaml 5 | import argparse 6 | import numpy as np 7 | import pandas as pd 8 | from pathlib import Path 9 | import torch 10 | import torch.nn as nn 11 | from torch.utils.data import Dataset, DataLoader 12 | import preprocess 13 | 14 | 15 | with open("../model/params.yaml", "r") as params_file: 16 | params = yaml.safe_load(params_file) 17 | 18 | model_dir = params['model_dir'] 19 | 20 | 21 | class TimeSeriesDataset(Dataset): 22 | def __init__(self, X, y, seq_len=1): 23 | self.X = X 24 | self.y = y 25 | self.seq_len = seq_len 26 | 27 | def __len__(self): 28 | return self.X.__len__() - self.seq_len 29 | 30 | def __getitem__(self, index): 31 | return self.X[index:index+self.seq_len], self.y[index+self.seq_len] 32 | 33 | 34 | class TSModel(nn.Module): 35 | def __init__(self, n_features, n_hidden=64, n_layers=2): 36 | super(TSModel, self).__init__() 37 | 38 | self.n_hidden = n_hidden 39 | self.lstm = nn.LSTM( 40 | input_size=n_features, 41 | hidden_size=n_hidden, 42 | batch_first=True, 43 | num_layers=n_layers, 44 | dropout=0.5 45 | ) 46 | self.linear = nn.Linear(n_hidden, 1) 47 | 48 | def forward(self, x): 49 | _, (hidden, _) = self.lstm(x) 50 | lstm_out = hidden[-1] # output last hidden state output 51 | y_pred = self.linear(lstm_out) 52 | 53 | return y_pred 54 | 55 | 56 | def train_model( 57 | train_df, 58 | test_df, 59 | label_name, 60 | sequence_length, 61 | batch_size, 62 | n_epochs, 63 | n_epochs_stop 64 | ): 65 | """Train LSTM model.""" 66 | print("Starting with model training...") 67 | 68 | # create dataloaders 69 | train_dataset = TimeSeriesDataset(np.array(train_df), np.array(train_df[label_name]), seq_len=sequence_length) 70 | train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=False) 71 | 72 | test_dataset = TimeSeriesDataset(np.array(test_df), np.array(test_df[label_name]), seq_len=sequence_length) 73 | test_loader = DataLoader(test_dataset, batch_size=100, shuffle=False) 74 | 75 | # set up training 76 | n_features = train_df.shape[1] 77 | model = TSModel(n_features) 78 | criterion = torch.nn.MSELoss() # L1Loss() 79 | optimizer = torch.optim.Adam(model.parameters(), lr=0.001) 80 | 81 | train_hist = [] 82 | test_hist = [] 83 | 84 | # start training 85 | best_loss = np.inf 86 | epochs_no_improve = 0 87 | for epoch in range(1, n_epochs+1): 88 | running_loss = 0 89 | model.train() 90 | 91 | for batch_idx, (data, target) in enumerate(train_loader, 1): 92 | # zero the parameter gradients 93 | optimizer.zero_grad() 94 | 95 | # forward + backward + optimize 96 | data = torch.Tensor(np.array(data)) 97 | output = model(data) 98 | loss = criterion(output.flatten(), target.type_as(output)) 99 | # if type(criterion) == torch.nn.modules.loss.MSELoss: 100 | # loss = torch.sqrt(loss) # RMSE 101 | loss.backward() 102 | optimizer.step() 103 | 104 | running_loss += loss.item() 105 | running_loss /= len(train_loader) 106 | train_hist.append(running_loss) 107 | 108 | # test loss 109 | model.eval() 110 | test_loss = 0 111 | with torch.no_grad(): 112 | for data, target in test_loader: 113 | data = torch.Tensor(np.array(data)) 114 | output = model(data) 115 | loss = criterion(output.flatten(), target.type_as(output)) 116 | test_loss += loss.item() 117 | test_loss /= len(test_loader) 118 | test_hist.append(test_loss) 119 | 120 | # early stopping 121 | if test_loss < best_loss: 122 | best_loss = test_loss 123 | torch.save(model.state_dict(), Path(model_dir, 'model.pt')) 124 | epochs_no_improve = 0 125 | else: 126 | epochs_no_improve += 1 127 | if epochs_no_improve == n_epochs_stop: 128 | print("Early stopping.") 129 | break 130 | 131 | print(f'Epoch {epoch} train loss: {round(running_loss,4)} test loss: {round(test_loss,4)}') 132 | 133 | hist = pd.DataFrame() 134 | hist['training_loss'] = train_hist 135 | hist['test_loss'] = test_hist 136 | 137 | print("Completed.") 138 | 139 | return hist 140 | 141 | 142 | if __name__ == "__main__": 143 | parser = argparse.ArgumentParser() 144 | parser.add_argument("--sequence-length", type=int, default=params['sequence_length']) 145 | parser.add_argument("--batch-size", type=int, default=params['batch_size']) 146 | parser.add_argument("--n-epochs", type=int, default=params['n_epochs']) 147 | parser.add_argument("--n-epochs-stop", type=int, default=params['n_epochs_stop']) 148 | args = parser.parse_args() 149 | 150 | train_df = preprocess.load_data('train.csv') 151 | test_df = preprocess.load_data('test.csv') 152 | label_name = params['label_name'] 153 | 154 | train_model( 155 | train_df, 156 | test_df, 157 | label_name, 158 | args.sequence_length, 159 | args.batch_size, 160 | args.n_epochs, 161 | args.n_epochs_stop 162 | ) 163 | --------------------------------------------------------------------------------