forked from passalis/dain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_utils.py
206 lines (152 loc) · 7.27 KB
/
train_utils.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
import numpy as np
import torch
from torch.autograd import Variable
from tqdm import tqdm
import torch.optim as optim
from lob_loader import get_wf_lob_loaders
from torch.nn import CrossEntropyLoss
from sklearn.metrics import precision_recall_fscore_support, cohen_kappa_score
def lob_epoch_trainer(model, loader, lr=0.0001, optimizer=optim.RMSprop):
model.train()
model_optimizer = optimizer([
{'params': model.base.parameters()},
{'params': model.dean.mean_layer.parameters(), 'lr': lr * model.dean.mean_lr},
{'params': model.dean.scaling_layer.parameters(), 'lr': lr * model.dean.scale_lr},
{'params': model.dean.gating_layer.parameters(), 'lr': lr * model.dean.gate_lr},
], lr=lr)
criterion = CrossEntropyLoss()
train_loss, counter = 0, 0
for (inputs, targets) in loader:
model_optimizer.zero_grad()
inputs, targets = Variable(inputs.cuda()), Variable(targets.cuda())
targets = torch.squeeze(targets)
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
model_optimizer.step()
train_loss += loss.item()
counter += inputs.size(0)
loss = (loss / counter).cpu().data.numpy()
return loss
def lob_epoch_trainer_mps(model, loader, lr=0.0001, optimizer=optim.RMSprop):
model.train()
model_optimizer = optimizer([
{'params': model.base.parameters()},
{'params': model.dean.mean_layer.parameters(), 'lr': lr * model.dean.mean_lr},
{'params': model.dean.scaling_layer.parameters(), 'lr': lr * model.dean.scale_lr},
{'params': model.dean.gating_layer.parameters(), 'lr': lr * model.dean.gate_lr},
], lr=lr)
criterion = CrossEntropyLoss()
train_loss, counter = 0, 0
# 'mps' device 설정 (Metal Performance Shaders)
device = torch.device('mps') if torch.backends.mps.is_available() else torch.device('cpu')
print('On device: ', device)
model.to(device)
for (inputs, targets) in loader:
model_optimizer.zero_grad()
# 데이터를 'mps' 또는 'cpu'로 이동
inputs, targets = inputs.to(device), targets.to(device)
targets = torch.squeeze(targets)
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
model_optimizer.step()
train_loss += loss.item()
counter += inputs.size(0)
loss = (train_loss / counter)
return loss
def lob_evaluator(model, loader):
model.eval()
true_labels = []
predicted_labels = []
for (inputs, targets) in tqdm(loader):
inputs, targets = inputs.cuda(), targets.cuda()
inputs, targets = Variable(inputs, volatile=True), Variable(targets)
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
predicted_labels.append(predicted.cpu().numpy())
true_labels.append(targets.cpu().data.numpy())
true_labels = np.squeeze(np.concatenate(true_labels))
predicted_labels = np.squeeze(np.concatenate(predicted_labels))
precision, recall, f1, _ = precision_recall_fscore_support(true_labels, predicted_labels, average=None)
precision_avg, recall_avg, f1_avg, _ = precision_recall_fscore_support(true_labels, predicted_labels,
average='macro')
kappa = cohen_kappa_score(true_labels, predicted_labels)
metrics = {}
metrics['accuracy'] = np.sum(true_labels == predicted_labels) / len(true_labels)
metrics['precision'], metrics['recall'], metrics['f1'] = precision, recall, f1
metrics['precision_avg'], metrics['recall_avg'], metrics['f1_avg'] = precision_avg, recall_avg, f1_avg
metrics['kappa'] = kappa
return metrics
def lob_evaluator_mps(model, loader):
model.eval()
true_labels = []
predicted_labels = []
# 'mps' device 설정 (Metal Performance Shaders)
device = torch.device('mps') if torch.backends.mps.is_available() else torch.device('cpu')
model.to(device)
for (inputs, targets) in tqdm(loader):
inputs, targets = inputs.to(device), targets.to(device)
with torch.no_grad(): # 'volatile' 대체
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
predicted_labels.append(predicted.cpu().numpy())
true_labels.append(targets.cpu().numpy())
true_labels = np.squeeze(np.concatenate(true_labels))
predicted_labels = np.squeeze(np.concatenate(predicted_labels))
precision, recall, f1, _ = precision_recall_fscore_support(true_labels, predicted_labels, average=None)
precision_avg, recall_avg, f1_avg, _ = precision_recall_fscore_support(true_labels, predicted_labels,
average='macro')
kappa = cohen_kappa_score(true_labels, predicted_labels)
metrics = {}
metrics['accuracy'] = np.sum(true_labels == predicted_labels) / len(true_labels)
metrics['precision'], metrics['recall'], metrics['f1'] = precision, recall, f1
metrics['precision_avg'], metrics['recall_avg'], metrics['f1_avg'] = precision_avg, recall_avg, f1_avg
metrics['kappa'] = kappa
return metrics
def train_evaluate_anchored(model, epoch_trainer=lob_epoch_trainer_mps, evaluator=lob_evaluator_mps,
horizon=0, window=5, batch_size=128, train_epochs=20, verbose=True,
use_resampling=True, learning_rate=0.0001, splits=[6, 7, 8], normalization='std'):
"""
Trains and evaluates a model for using an anchored walk-forward setup
:param model: model to train
:param epoch_trainer: function to use for training the model (please refer to lob.model_utils.epoch_trainer() )
:param evaluator: function to use for evaluating the model (please refer to lob.model_utils.epoch_trainer() )
:param horizon: the prediction horizon for the evaluation (0, 5 or 10)
:param window: the window to use
:param batch_size: batch size to be used
:param train_epochs: number of epochs for training the model
:param verbose:
:return:
"""
results = []
for i in splits:
print("Evaluating for split: ", i)
train_loader, test_loader = get_wf_lob_loaders(window=window, horizon=horizon, split=i, batch_size=batch_size,
class_resample=use_resampling, normalization=normalization)
current_model = model()
# current_model.cuda()
# current_model
for epoch in range(train_epochs):
loss = epoch_trainer(model=current_model, loader=train_loader, lr=learning_rate)
if verbose:
print("Epoch ", epoch, "loss: ", loss)
test_results = evaluator(current_model, test_loader)
print(test_results)
results.append(test_results)
return results
def get_average_metrics(results):
precision, recall, f1 = [], [], []
kappa = []
acc = []
for x in results:
acc.append(x['accuracy'])
precision.append(x['precision_avg'])
recall.append(x['recall_avg'])
f1.append(x['f1_avg'])
kappa.append(x['kappa'])
print("Precision = ", np.mean(precision))
print("Recall = ", np.mean(recall))
print("F1 = ", np.mean(f1))
print("Cohen = ", np.mean(kappa))
return acc, precision, recall, f1, kappa