-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathbase.py
238 lines (183 loc) · 6.76 KB
/
base.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
import numpy as np
from numpy.random import shuffle
from collections import defaultdict
from skge.param import Parameter, AdaGrad
import timeit
import pickle
_cutoff = 30
_DEF_NBATCHES = 100
_DEF_POST_EPOCH = []
_DEF_LEARNING_RATE = 0.1
_DEF_SAMPLE_FUN = None
_DEF_MAX_EPOCHS = 1000
_DEF_MARGIN = 1.0
class Config(object):
def __init__(self, model, trainer):
self.model = model
self.trainer = trainer
def __getstate__(self):
return {
'model': self.model,
'trainer': self.trainer
}
class Model(object):
"""
Base class for all Knowledge Graph models
Implements basic setup routines for parameters and serialization methods
Subclasses need to implement:
- scores(self, ss, ps, os)
- _gradients(self, xys) for StochasticTrainer
- _pairwise_gradients(self, pxs, nxs) for PairwiseStochasticTrainer
"""
def __init__(self, *args, **kwargs):
#super(Model, self).__init__(*args, **)
self.params = {}
self.hyperparams = {}
self.add_hyperparam('init', kwargs.pop('init', 'nunif'))
def add_param(self, param_id, shape, post=None, value=None):
if value is None:
value = Parameter(shape, self.init, name=param_id, post=post)
setattr(self, param_id, value)
self.params[param_id] = value
def add_hyperparam(self, param_id, value):
setattr(self, param_id, value)
self.hyperparams[param_id] = value
def __getstate__(self):
return {
'hyperparams': self.hyperparams,
'params': self.params
}
def __setstate__(self, st):
self.params = {}
self.hyperparams = {}
for pid, p in st['params'].items():
self.add_param(pid, None, None, value=p)
for pid, p in st['hyperparams'].items():
self.add_hyperparam(pid, p)
def save(self, fname, protocol=pickle.HIGHEST_PROTOCOL):
with open(fname, 'wb') as fout:
pickle.dump(self, fout, protocol=protocol)
@staticmethod
def load(fname):
with open(fname, 'rb') as fin:
mdl = pickle.load(fin)
return mdl
class StochasticTrainer(object):
"""
Stochastic gradient descent trainer with scalar loss function.
Models need to implement
_gradients(self, xys)
to be trained with this class.
"""
def __init__(self, *args, **kwargs):
self.model = args[0]
self.hyperparams = {}
self.add_hyperparam('max_epochs', kwargs.pop('max_epochs', _DEF_MAX_EPOCHS))
self.add_hyperparam('nbatches', kwargs.pop('nbatches', _DEF_NBATCHES))
self.add_hyperparam('learning_rate', kwargs.pop('learning_rate', _DEF_LEARNING_RATE))
self.post_epoch = kwargs.pop('post_epoch', _DEF_POST_EPOCH)
self.samplef = kwargs.pop('samplef', _DEF_SAMPLE_FUN)
pu = kwargs.pop('param_update', AdaGrad)
self._updaters = {
key: pu(param, self.learning_rate)
for key, param in self.model.params.items()
}
def __getstate__(self):
return self.hyperparams
def __setstate__(self, st):
for pid, p in st['hyperparams']:
self.add_hyperparam(pid, p)
def add_hyperparam(self, param_id, value):
setattr(self, param_id, value)
self.hyperparams[param_id] = value
def fit(self, xs, ys):
self._optim(list(zip(xs, ys)))
def _pre_epoch(self):
self.loss = 0
def _optim(self, xys):
idx = np.arange(len(xys))
self.batch_size = np.ceil(len(xys) / self.nbatches)
batch_idx = np.arange(self.batch_size, len(xys), self.batch_size)
for self.epoch in range(1, self.max_epochs + 1):
# shuffle training examples
self._pre_epoch()
shuffle(idx)
# store epoch for callback
self.epoch_start = timeit.default_timer()
# process mini-batches
for batch in np.split(idx, batch_idx):
# select indices for current batch
bxys = [xys[z] for z in batch]
self._process_batch(bxys)
# check callback function, if false return
for f in self.post_epoch:
if not f(self):
break
def _process_batch(self, xys):
# if enabled, sample additional examples
if self.samplef is not None:
xys += self.samplef(xys)
if hasattr(self.model, '_prepare_batch_step'):
self.model._prepare_batch_step(xys)
# take step for batch
grads = self.model._gradients(xys)
self.loss += self.model.loss
self._batch_step(grads)
def _batch_step(self, grads):
for paramID in self._updaters.keys():
self._updaters[paramID](*grads[paramID])
class PairwiseStochasticTrainer(StochasticTrainer):
"""
Stochastic gradient descent trainer with pairwise ranking loss functions.
Models need to implement
_pairwise_gradients(self, pxs, nxs)
to be trained with this class.
"""
def __init__(self, *args, **kwargs):
super(PairwiseStochasticTrainer, self).__init__(*args, **kwargs)
self.model.add_hyperparam('margin', kwargs.pop('margin', _DEF_MARGIN))
def fit(self, xs, ys):
if self.samplef is None:
pidx = np.where(np.array(ys) == 1)[0]
nidx = np.where(np.array(ys) != 1)[0]
pxs = [xs[i] for i in pidx]
self.nxs = [xs[i] for i in nidx]
self.pxs = int(len(self.nxs) / len(pxs)) * pxs
xys = list(range(min(len(pxs), len(self.nxs))))
self._optim(xys)
else:
self._optim(list(zip(xs, ys)))
def _pre_epoch(self):
self.nviolations = 0
if self.samplef is None:
shuffle(self.pxs)
shuffle(self.nxs)
def _process_batch(self, xys):
pxs = []
nxs = []
for xy in xys:
if self.samplef is not None:
for nx in self.samplef([xy]):
pxs.append(xy)
nxs.append(nx)
else:
pxs.append((self.pxs[xy], 1))
nxs.append((self.nxs[xy], 1))
# take step for batch
if hasattr(self.model, '_prepare_batch_step'):
self.model._prepare_batch_step(pxs, nxs)
grads = self.model._pairwise_gradients(pxs, nxs)
# update if examples violate margin
if grads is not None:
self.nviolations += self.model.nviolations
self._batch_step(grads)
def sigmoid(fs):
# compute elementwise gradient for sigmoid
for i in range(len(fs)):
if fs[i] > _cutoff:
fs[i] = 1.0
elif fs[i] < -_cutoff:
fs[i] = 0.0
else:
fs[i] = 1.0 / (1 + np.exp(-fs[i]))
return fs[:, np.newaxis]