-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdeep_model.py
165 lines (129 loc) · 4.19 KB
/
deep_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# Data wrangling
import pandas as pd
import numpy as np
# Deep learning:
from keras.models import Sequential
from keras.layers import LSTM, Dense
class DeepModelTS():
"""
A class to create a deep time series model
"""
def __init__(
self,
data: pd.DataFrame,
Y_var: str,
lag: int,
LSTM_layer_depth: int,
epochs=10,
batch_size=256,
train_test_split=0
):
self.data = data
self.Y_var = Y_var
self.lag = lag
self.LSTM_layer_depth = LSTM_layer_depth
self.batch_size = batch_size
self.epochs = epochs
self.train_test_split = train_test_split
@staticmethod
def create_X_Y(ts: list, lag: int) -> tuple:
"""
A method to create X and Y matrix from a time series list for the training of
deep learning models
"""
X, Y = [], []
if len(ts) - lag <= 0:
X.append(ts)
else:
for i in range(len(ts) - lag):
Y.append(ts[i + lag])
X.append(ts[i:(i + lag)])
X, Y = np.array(X), np.array(Y)
# Reshaping the X array to an LSTM input shape
X = np.reshape(X, (X.shape[0], X.shape[1], 1))
return X, Y
def create_data_for_NN(
self,
use_last_n=None
):
"""
A method to create data for the neural network model
"""
# Extracting the main variable we want to model/forecast
y = self.data[self.Y_var].tolist()
# Subseting the time series if needed
if use_last_n is not None:
y = y[-use_last_n:]
# The X matrix will hold the lags of Y
X, Y = self.create_X_Y(y, self.lag)
# Creating training and test sets
X_train = X
X_test = []
Y_train = Y
Y_test = []
if self.train_test_split > 0:
index = round(len(X) * self.train_test_split)
X_train = X[:(len(X) - index)]
X_test = X[-index:]
Y_train = Y[:(len(X) - index)]
Y_test = Y[-index:]
return X_train, X_test, Y_train, Y_test
def LSTModel(self):
"""
A method to fit the LSTM model
"""
# Getting the data
X_train, X_test, Y_train, Y_test = self.create_data_for_NN()
# Defining the model
model = Sequential()
model.add(LSTM(self.LSTM_layer_depth, activation='relu', input_shape=(self.lag, 1)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
# Defining the model parameter dict
keras_dict = {
'x': X_train,
'y': Y_train,
'batch_size': self.batch_size,
'epochs': self.epochs,
'shuffle': False
}
if self.train_test_split > 0:
keras_dict.update({
'validation_data': (X_test, Y_test)
})
# Fitting the model
model.fit(
**keras_dict
)
# Saving the model to the class
self.model = model
return model
def predict(self) -> list:
"""
A method to predict using the test data used in creating the class
"""
yhat = []
if(self.train_test_split > 0):
# Getting the last n time series
_, X_test, _, _ = self.create_data_for_NN()
# Making the prediction list
yhat = [y[0] for y in self.model.predict(X_test)]
return yhat
def predict_n_ahead(self, n_ahead: int):
"""
A method to predict n time steps ahead
"""
X, _, _, _ = self.create_data_for_NN(use_last_n=self.lag)
# Making the prediction list
yhat = []
for _ in range(n_ahead):
# Making the prediction
fc = self.model.predict(X)
yhat.append(fc)
# Creating a new input matrix for forecasting
X = np.append(X, fc)
# Ommiting the first variable
X = np.delete(X, 0)
# Reshaping for the next iteration
X = np.reshape(X, (1, len(X), 1))
return yhat