-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
190 lines (147 loc) · 5.68 KB
/
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import json
import numpy as np
import torch
import torch.optim
import joblib
import os
from sklearn import preprocessing
from sklearn.pipeline import Pipeline
from torch.utils.data import DataLoader
import net
from featurize import TreeFeaturizer
CUDA = torch.cuda.is_available()
def _nn_path(base):
return os.path.join(base, "nn_weights")
def _x_transform_path(base):
return os.path.join(base, "x_transform")
def _y_transform_path(base):
return os.path.join(base, "y_transform")
def _channels_path(base):
return os.path.join(base, "channels")
def _n_path(base):
return os.path.join(base, "n")
def _inv_log1p(x):
return np.exp(x) - 1
class BaoData:
def __init__(self, data):
assert data
self.__data = data
def __len__(self):
return len(self.__data)
def __getitem__(self, idx):
return (self.__data[idx]["tree"],
self.__data[idx]["target"])
def collate(x):
trees = []
targets = []
for tree, target in x:
trees.append(tree)
targets.append(target)
targets = torch.tensor(targets)
return trees, targets
class BaoRegression:
def __init__(self, verbose=False, have_cache_data=False):
self.__net = None
self.__verbose = verbose
log_transformer = preprocessing.FunctionTransformer(
np.log1p, _inv_log1p,
validate=True)
scale_transformer = preprocessing.MinMaxScaler()
self.__pipeline = Pipeline([("log", log_transformer),
("scale", scale_transformer)])
self.__tree_transform = TreeFeaturizer()
self.__have_cache_data = have_cache_data
self.__in_channels = None
self.__n = 0
def __log(self, *args):
if self.__verbose:
print(*args)
def num_items_trained_on(self):
return self.__n
def load(self, path):
with open(_n_path(path), "rb") as f:
self.__n = joblib.load(f)
with open(_channels_path(path), "rb") as f:
self.__in_channels = joblib.load(f)
self.__net = net.BaoNet(self.__in_channels)
self.__net.load_state_dict(torch.load(_nn_path(path)))
self.__net.eval()
with open(_y_transform_path(path), "rb") as f:
self.__pipeline = joblib.load(f)
with open(_x_transform_path(path), "rb") as f:
self.__tree_transform = joblib.load(f)
def save(self, path):
# try to create a directory here
os.makedirs(path, exist_ok=True)
torch.save(self.__net.state_dict(), _nn_path(path))
with open(_y_transform_path(path), "wb") as f:
joblib.dump(self.__pipeline, f)
with open(_x_transform_path(path), "wb") as f:
joblib.dump(self.__tree_transform, f)
with open(_channels_path(path), "wb") as f:
joblib.dump(self.__in_channels, f)
with open(_n_path(path), "wb") as f:
joblib.dump(self.__n, f)
def fit(self, X, y):
if isinstance(y, list):
y = np.array(y)
X = [json.loads(x) if isinstance(x, str) else x for x in X]
self.__n = len(X)
# transform the set of trees into feature vectors using a log
# (assuming the tail behavior exists, TODO investigate
# the quantile transformer from scikit)
y = self.__pipeline.fit_transform(y.reshape(-1, 1)).astype(np.float32)
self.__tree_transform.fit(X)
X = self.__tree_transform.transform(X)
pairs = list(zip(X, y))
dataset = DataLoader(pairs,
batch_size=16,
shuffle=True,
collate_fn=collate)
# determine the initial number of channels
for inp, _tar in dataset:
in_channels = inp[0][0].shape[0]
break
self.__log("Initial input channels:", in_channels)
# if self.__have_cache_data:
# assert in_channels == self.__tree_transform.num_operators() + 3
# else:
# assert in_channels == self.__tree_transform.num_operators() + 2
self.__net = net.BaoNet(in_channels)
self.__in_channels = in_channels
if CUDA:
self.__net = self.__net.cuda()
optimizer = torch.optim.Adam(self.__net.parameters())
loss_fn = torch.nn.MSELoss()
losses = []
for epoch in range(100):
loss_accum = 0
for x, y in dataset:
if CUDA:
y = y.cuda()
y_pred = self.__net(x)
loss = loss_fn(y_pred, y)
loss_accum += loss.item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_accum /= len(dataset)
losses.append(loss_accum)
if epoch % 15 == 0:
self.__log("Epoch", epoch, "training loss:", loss_accum)
# stopping condition
if len(losses) > 10 and losses[-1] < 0.1:
last_two = np.min(losses[-2:])
if last_two > losses[-10] or (losses[-10] - last_two < 0.0001):
self.__log("Stopped training from convergence condition at epoch", epoch)
break
else:
self.__log("Stopped training after max epochs")
def predict(self, X):
if not isinstance(X, list):
X = [X]
X = [json.loads(x) if isinstance(x, str) else x for x in X]
X = self.__tree_transform.transform(X)
self.__net.eval()
pred = self.__net(X).cpu().detach().numpy()
return self.__pipeline.inverse_transform(pred)