-
Notifications
You must be signed in to change notification settings - Fork 0
/
transformer_multi_step.py
337 lines (266 loc) · 12.4 KB
/
transformer_multi_step.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
from datetime import date
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import time
import math
from matplotlib import pyplot
from sklearn.preprocessing import MinMaxScaler
from base_config import config
from sklearn.metrics import mean_squared_error, mean_absolute_percentage_error, mean_absolute_error
from utils import print_metrics
transformer_config = config['methods_hyper_config']['transformer']
torch.manual_seed(0)
np.random.seed(0)
# This concept is also called teacher forceing.
# The flag decides if the loss will be calculted over all
# or just the predicted values.
calculate_loss_over_all_values = transformer_config['calculate_loss_over_all_values']
# S is the source sequence length
# T is the target sequence length
# N is the batch size
# E is the feature number
#src = torch.rand((10, 32, 512)) # (S,N,E)
#tgt = torch.rand((20, 32, 512)) # (T,N,E)
#out = transformer_model(src, tgt)
#
#print(out)
input_window = transformer_config['input_window']
output_window = transformer_config['output_window']
lr_definition = transformer_config['lr']
number_of_epochs = transformer_config['num_epochs']
batch_size = transformer_config['batch_size'] # batch size
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
scaler = MinMaxScaler(feature_range=(-1, 1))
criterion = nn.MSELoss()
lr = lr_definition
#optimizer = torch.optim.SGD(model.parameters(), lr=lr)
best_val_loss = float("inf")
epochs = number_of_epochs # The number of epochs
best_model = None
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super(PositionalEncoding, self).__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
#pe.requires_grad = False
self.register_buffer('pe', pe)
def forward(self, x):
return x + self.pe[:x.size(0), :]
class TransAm(nn.Module):
def __init__(self,feature_size=transformer_config['hidden_dim'], num_layers=transformer_config['num_layers'], dropout=transformer_config['dropout']):
super(TransAm, self).__init__()
self.model_type = 'Transformer'
self.src_mask = None
self.pos_encoder = PositionalEncoding(feature_size)
self.encoder_layer = nn.TransformerEncoderLayer(d_model=feature_size, nhead=transformer_config['nhead'], dropout=dropout)
self.transformer_encoder = nn.TransformerEncoder(self.encoder_layer, num_layers=num_layers)
self.decoder = nn.Linear(feature_size,1)
self.init_weights()
def init_weights(self):
initrange = 0.1
self.decoder.bias.data.zero_()
self.decoder.weight.data.uniform_(-initrange, initrange)
def forward(self,src):
if self.src_mask is None or self.src_mask.size(0) != len(src):
device = src.device
mask = self._generate_square_subsequent_mask(len(src)).to(device)
self.src_mask = mask
src = self.pos_encoder(src)
output = self.transformer_encoder(src,self.src_mask)#, self.src_mask)
output = self.decoder(output)
return output
def _generate_square_subsequent_mask(self, sz):
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
return mask
model = TransAm().to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.98)
# if window is 100 and prediction step is 1
# in -> [0..99]
# target -> [1..100]
def create_inout_sequences(input_data, tw):
inout_seq = []
L = len(input_data)
for i in range(L-tw):
train_seq = np.append(input_data[i:i+tw][:-output_window] , output_window * [0])
train_label = input_data[i:i+tw]
#train_label = input_data[i+output_window:i+tw+output_window]
inout_seq.append((train_seq ,train_label))
return torch.FloatTensor(inout_seq)
def prepare_data(series_train, series_test):
price_train = scaler.fit_transform(
series_train['open'].to_numpy().reshape(-1, 1)
).reshape(-1)
price_test = scaler.fit_transform(
series_test['open'].to_numpy().reshape(-1, 1)
).reshape(-1)
# amplitude = scaler.fit_transform(amplitude.reshape(-1, 1)).reshape(-1)
# convert our train data into a pytorch train tensor
#train_tensor = torch.FloatTensor(train_data).view(-1)
# todo: add comment..
train_sequence = create_inout_sequences(price_train,input_window)
train_sequence = train_sequence[:-output_window] #todo: fix hack?
#test_data = torch.FloatTensor(test_data).view(-1)
test_data = create_inout_sequences(price_test,input_window)
test_data = test_data[:-output_window] #todo: fix hack?
return train_sequence.to(device),test_data.to(device)
def get_batch(source, i,batch_size):
seq_len = min(batch_size, len(source) - 1 - i)
data = source[i:i+seq_len]
input = torch.stack(torch.stack([item[0] for item in data]).chunk(input_window,1)) # 1 is feature size
target = torch.stack(torch.stack([item[1] for item in data]).chunk(input_window,1))
return input, target
def train(train_data, epoch):
model.train() # Turn on the train mode
total_loss = 0.
start_time = time.time()
for batch, i in enumerate(range(0, len(train_data) - 1, batch_size)):
data, targets = get_batch(train_data, i,batch_size)
optimizer.zero_grad()
output = model(data)
if calculate_loss_over_all_values:
loss = criterion(output, targets)
else:
loss = criterion(output[-output_window:], targets[-output_window:])
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
optimizer.step()
total_loss += loss.item()
log_interval = int(len(train_data) / batch_size / 5)
if batch % log_interval == 0 and batch > 0:
cur_loss = total_loss / log_interval
elapsed = time.time() - start_time
print('| epoch {:3d} | {:5d}/{:5d} batches | '
'lr {:02.6f} | {:5.2f} ms | '
'loss {:5.5f} | ppl {:8.2f}'.format(
epoch, batch, len(train_data) // batch_size, scheduler.get_lr()[0],
elapsed * 1000 / log_interval,
cur_loss, math.exp(cur_loss)))
total_loss = 0
start_time = time.time()
def plot_and_loss(eval_model, data_source, epoch, series):
eval_model.eval()
total_loss = 0.
test_result = torch.Tensor(0)
truth = torch.Tensor(0)
# print('date source', data_source)
with torch.no_grad():
for i in range(0, len(data_source) - 1):
data, target = get_batch(data_source, i,1)
# look like the model returns static values for the output window
output = eval_model(data)
if calculate_loss_over_all_values:
total_loss += criterion(output, target).item()
else:
total_loss += criterion(output[-output_window:], target[-output_window:]).item()
test_result = torch.cat((test_result, output[-1].view(-1).cpu()), 0) #todo: check this. -> looks good to me
truth = torch.cat((truth, target[-1].view(-1).cpu()), 0)
#test_result = test_result.cpu().numpy()
print('train', series['series_train'])
print('test', series['series_test'])
# train_dates = dates['train_dates']
# test_dates = dates['test_dates'][:145]
truth_result = scaler.inverse_transform(truth[:len(test_result)].numpy().reshape(1, -1)).reshape(-1)
test_result = scaler.inverse_transform(test_result.numpy().reshape(1, -1)).reshape(-1)
dates_train = series['series_train'].iloc[::5, :]
print('dates', dates_train.shape)
print('train dates', series['series_train'].shape)
print('test dates', series['series_test'].shape)
print('test results', test_result.shape)
print('truth results', truth_result.shape)
pyplot.plot(test_result, color="red")
pyplot.plot(truth_result, color="blue")
# pyplot.plot(test_result-truth,color="green")
# pyplot.grid(True, which='both')
pyplot.axhline(y=0, color='k')
pyplot.show()
# pyplot.savefig('graphs/transformer/transformer-multi-epoch%d.png'%epoch)
pyplot.close()
return total_loss / i
def mean_absolute_percentage_error_custom(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
def predict_future(eval_model, data_source, original_series, epoch):
eval_model.eval()
total_loss = 0.
test_result = torch.Tensor(0)
truth = torch.Tensor(0)
test_series = original_series['series_test']
steps = test_series.shape[0] - input_window
# _, full_data = get_batch(data_source, 0, 1)
_ , data = get_batch(data_source, 0,1)
with torch.no_grad():
for i in range(0, steps,1):
input = torch.clone(data[-input_window:])
input[-output_window:] = 0
output = eval_model(data[-input_window:])
data = torch.cat((data, output[-1:]))
data = data.cpu().view(-1)
data_plot = scaler.inverse_transform(data.numpy().reshape(1, -1)).reshape(-1)
# full_data = full_data.cpu().view
# full_data = scaler.inverse_transform(full_data.numpy().reshape(1, -1)).reshape(-1)
original_values = test_series['open'].to_numpy()
print_metrics(original_values, data_plot)
print('Steps: ', steps)
print('Epoch: ', epoch)
# if epoch > transformer_config['number_of_epochs'] * 0.7:
pyplot.plot(data_plot,color="red")
pyplot.plot(test_series['open'], color="blue")
# pyplot.grid(True, which='both')
pyplot.legend(['Predikce ceny', 'Realná cena'])
# pyplot.axhline(y=0, color='k')
pyplot.xlabel('Predikce vs realná data na části testovacího souboru')
pyplot.ylabel(f"{config['ticker']} cena akcie")
# pyplot.show()
pyplot.savefig(f"graphs/transformer/transformer_predicted_{config['ticker']}_{str(steps)}_{str(epoch)}.png")
pyplot.close()
def evaluate(eval_model, data_source):
eval_model.eval() # Turn on the evaluation mode
total_loss = 0.
eval_batch_size = transformer_config['eval_batch_size']
with torch.no_grad():
for i in range(0, len(data_source) - 1, eval_batch_size):
data, targets = get_batch(data_source, i,eval_batch_size)
output = eval_model(data)
if calculate_loss_over_all_values:
total_loss += len(data[0])* criterion(output, targets).cpu().item()
else:
total_loss += len(data[0])* criterion(output[-output_window:], targets[-output_window:]).cpu().item()
return total_loss / len(data_source)
def predict_with_transformer_multi(series_train, series_test):
train_data, val_data = prepare_data(series_train, series_test)
print('train_data: ', train_data)
print('series_test: ', series_test)
for epoch in range(1, epochs + 1):
epoch_start_time = time.time()
train(train_data, epoch)
if(epoch % 10 is 0):
# val_loss = plot_and_loss(model, val_data, epoch, {
# "series_train": series_train,
# "series_test": series_test
# })
predict_future(model, val_data, {
"series_train": series_train,
"series_test": series_test
}, epoch)
else:
val_loss = evaluate(model, val_data)
print('-' * 89)
print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.5f} | valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),val_loss, math.exp(val_loss)))
print('-' * 89)
# if val_loss < best_val_loss:
# best_val_loss = val_loss
# best_model = model
scheduler.step()
#src = torch.rand(input_window, batch_size, 1) # (source sequence length,batch size,feature number)
#out = model(src)
#
#print(out)
#print(out.shape)