forked from anaderi/lhcb_trigger_ml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
losses.py
420 lines (344 loc) · 18.9 KB
/
losses.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
"""
Different loss functions for gradient boosting are defined here.
(They are available at `ugradientboosting`, but were moved to separate module to avoid mess)
"""
from __future__ import division, print_function, absolute_import
import numbers
import warnings
import numpy
import pandas
from scipy import sparse
from scipy.special import expit
from collections import defaultdict
from sklearn.utils.validation import check_random_state
from sklearn.base import BaseEstimator
from .commonutils import computeSignalKnnIndices, indices_of_values, check_sample_weight, check_uniform_label
from .metrics_utils import bin_to_group_indices, compute_group_weights, compute_bin_indices
__author__ = 'Alex Rogozhnikov'
def compute_positions(y_pred, sample_weight):
"""For each event computes it position among other events by prediction.
position = part of elements with lower predictions => position belongs to [0, 1]"""
order = numpy.argsort(y_pred)
ordered_weights = sample_weight[order]
ordered_weights /= float(numpy.sum(ordered_weights))
efficiencies = (numpy.cumsum(ordered_weights) - 0.5 * ordered_weights)
return efficiencies[numpy.argsort(order)]
class AbstractLossFunction(BaseEstimator):
def fit(self, X, y, sample_weight):
""" This method is optional, it is called before all the others."""
pass
def negative_gradient(self, y_pred):
"""The y_pred should contain all the events passed to `fit` method,
moreover, the order should be the same"""
raise NotImplementedError()
def __call__(self, y_pred):
"""The y_pred should contain all the events passed to `fit` method,
moreover, the order should be the same"""
raise NotImplementedError()
def update_tree(self, tree, X, y, y_pred, sample_weight, update_mask, residual):
"""This method may be not called at all, so it shouldn't
modify y_pred (unlike LossFunction from sklearn),
y_pred will be recomputed outside after updating the tree"""
# compute leaf for each sample in ``X``.
terminal_regions = tree.apply(X)
# mask all which are not in sample mask.
masked_terminal_regions = terminal_regions.copy()
masked_terminal_regions[~update_mask] = -1
for leaf, indices_in_leaf in indices_of_values(masked_terminal_regions):
if leaf == -1:
continue
tree.value[leaf, 0, 0] = self.update_tree_leaf(
leaf=leaf, indices_in_leaf=indices_in_leaf, X=X, y=y, y_pred=y_pred,
sample_weight=sample_weight, update_mask=update_mask, residual=residual)
def update_fast_tree(self, fast_tree, X, y, y_pred, sample_weight, update_mask, residual):
"""This method may be not called at all, so it shouldn't
modify y_pred (unlike LossFunction from sklearn),
y_pred will be recomputed outside after updating the tree"""
# compute leaf for each sample in ``X``.
terminal_regions, _ = fast_tree.apply(X)
# mask all which are not in sample mask.
terminal_regions[~update_mask] = -1
for leaf, indices_in_leaf in indices_of_values(terminal_regions):
if leaf == -1:
continue
new_value = self.update_tree_leaf(
leaf=leaf, indices_in_leaf=indices_in_leaf, X=X, y=y, y_pred=y_pred,
sample_weight=sample_weight, update_mask=update_mask, residual=residual)
assert len(fast_tree.nodes_data[leaf]) == 1
fast_tree.nodes_data[leaf] = (new_value, )
def update_tree_leaf(self, leaf, indices_in_leaf,
X, y, y_pred, sample_weight, update_mask, residual):
raise NotImplementedError('This method should be overriden')
class AdaLossFunction(AbstractLossFunction):
def __init__(self, regularization=1e-2):
self.regularization = regularization
def fit(self, X, y, sample_weight):
self.y = y
self.sample_weight = sample_weight
self.y_signed = 2 * y - 1
def __call__(self, y_pred):
return numpy.sum(self.sample_weight * numpy.exp(- self.y_signed * y_pred))
def negative_gradient(self, y_pred):
return self.y_signed * self.sample_weight * numpy.exp(- self.y_signed * y_pred)
def update_tree_leaf(self, leaf, indices_in_leaf, X, y, y_pred, sample_weight, update_mask, residual):
leaf_ans = y[indices_in_leaf]
leaf_exp = sample_weight[indices_in_leaf] * numpy.exp(
- self.y_signed[indices_in_leaf] * y_pred[indices_in_leaf])
w1 = numpy.sum(leaf_exp[leaf_ans == 1])
w2 = numpy.sum(leaf_exp[leaf_ans == 0])
# regularization
w_reg = (w1 + w2) * self.regularization
# minimization of w1 * e^(-x) + w2 * e^x
return 0.5 * numpy.log((w1 + w_reg) / (w2 + w_reg))
class BinomialDevianceLossFunction(AbstractLossFunction):
def fit(self, X, y, sample_weight):
self.y = y
self.sample_weight = sample_weight
self.y_signed = 2 * y - 1
def __call__(self, y_pred):
return numpy.sum(self.sample_weight * numpy.logaddexp(0, - self.y_signed * y_pred))
def negative_gradient(self, y_pred):
return self.y_signed * self.sample_weight * expit(- self.y_signed * y_pred)
def update_tree_leaf(self, leaf, indices_in_leaf, X, y, y_pred, sample_weight, update_mask, residual):
leaf_y = y[indices_in_leaf]
y_signed = 2 * leaf_y - 1
leaf_weights = sample_weight[indices_in_leaf]
residual_abs = expit(numpy.clip(-y_signed * y_pred[indices_in_leaf], -10, 10))
nominator = numpy.sum(y_signed * residual_abs * leaf_weights)
denominator = numpy.sum(residual_abs * (1 - residual_abs) * leaf_weights)
regularization = 1. * numpy.mean(leaf_weights)
return nominator / (denominator + regularization)
# region MatrixLossFunction
class AbstractMatrixLossFunction(AbstractLossFunction):
def __init__(self, uniform_variables):
"""KnnLossFunction is a base class to be inherited by other loss functions,
which choose the particular A matrix and w vector. The formula of loss is:
loss = \sum_i w_i * exp(- \sum_j a_ij y_j score_j)
"""
self.uniform_variables = uniform_variables
# real matrix and vector will be computed during fitting
self.A = None
self.A_t = None
self.w = None
def fit(self, X, y, sample_weight):
"""This method is used to compute A matrix and w based on train dataset"""
assert len(X) == len(y), "different size of arrays"
A, w = self.compute_parameters(X, y)
self.A = sparse.csr_matrix(A)
self.A_t = sparse.csr_matrix(self.A.transpose())
self.w = numpy.array(w)
assert A.shape[0] == len(w), "inconsistent sizes"
assert A.shape[1] == len(X), "wrong size of matrix"
self.y_signed = 2 * y - 1
return self
def __call__(self, y_pred):
"""Computing the loss itself"""
assert len(y_pred) == self.A.shape[1], "something is wrong with sizes"
exponents = numpy.exp(- self.A.dot(self.y_signed * y_pred))
return numpy.sum(self.w * exponents)
def negative_gradient(self, y_pred):
"""Computing negative gradient"""
assert len(y_pred) == self.A.shape[1], "something is wrong with sizes"
exponents = numpy.exp(- self.A.dot(self.y_signed * y_pred))
result = self.A_t.dot(self.w * exponents) * self.y_signed
return result
def compute_parameters(self, trainX, trainY):
"""This method should be overloaded in descendant, and should return A, w (matrix and vector)"""
raise NotImplementedError()
def update_tree(self, tree, X, y, y_pred, sample_weight, update_mask, residual):
self.update_exponents = self.w * numpy.exp(- self.A.dot(self.y_signed * y_pred))
AbstractLossFunction.update_tree(self, tree, X, y, y_pred, sample_weight, update_mask, residual)
def update_tree_leaf(self, leaf, indices_in_leaf, X, y, y_pred, sample_weight, update_mask, residual):
terminal_region = numpy.zeros(len(X), dtype=float)
terminal_region[indices_in_leaf] += 1
z = self.A.dot(terminal_region * self.y_signed)
# optimal value here by several steps?
alpha = numpy.sum(self.update_exponents * z) / (numpy.sum(self.update_exponents * z * z) + 1e-10)
return alpha
class SimpleKnnLossFunction(AbstractMatrixLossFunction):
def __init__(self, uniform_variables, knn=10, uniform_label=1, distinguish_classes=True, row_norm=1.):
"""A matrix is square, each row corresponds to a single event in train dataset, in each row we put ones
to the closest neighbours of that event if this event from class along which we want to have uniform prediction.
:param list[str] uniform_variables: the features, along which uniformity is desired
:param int knn: the number of nonzero elements in the row, corresponding to event in 'uniform class'
:param int|list[int] uniform_label: the label (labels) of 'uniform classes'
:param bool distinguish_classes: if True, 1's will be placed only for events of same class.
"""
self.knn = knn
self.distinguish_classes = distinguish_classes
self.row_norm = row_norm
self.uniform_label = check_uniform_label(uniform_label)
AbstractMatrixLossFunction.__init__(self, uniform_variables)
def compute_parameters(self, trainX, trainY):
sample_weight = numpy.ones(len(trainX))
A_parts = []
w_parts = []
for label in self.uniform_label:
label_mask = trainY == label
n_label = numpy.sum(label_mask)
if self.distinguish_classes:
mask = label_mask
else:
mask = numpy.ones(len(trainY), dtype=numpy.bool)
knn_indices = computeSignalKnnIndices(self.uniform_variables, trainX, mask, self.knn)
knn_indices = knn_indices[label_mask, :]
ind_ptr = numpy.arange(0, n_label * self.knn + 1, self.knn)
column_indices = knn_indices.flatten()
data = numpy.ones(n_label * self.knn, dtype=float) * self.row_norm / self.knn
A_part = sparse.csr_matrix((data, column_indices, ind_ptr), shape=[n_label, len(trainX)])
w_part = numpy.mean(numpy.take(sample_weight, knn_indices), axis=1)
assert A_part.shape[0] == len(w_part)
A_parts.append(A_part)
w_parts.append(w_part)
for label in set(trainY) - set(self.uniform_label):
label_mask = trainY == label
n_label = numpy.sum(label_mask)
ind_ptr = numpy.arange(0, n_label + 1)
column_indices = numpy.where(label_mask)[0].flatten()
data = numpy.ones(n_label, dtype=float) * self.row_norm
A_part = sparse.csr_matrix((data, column_indices, ind_ptr), shape=[n_label, len(trainX)])
w_part = sample_weight[label_mask]
A_parts.append(A_part)
w_parts.append(w_part)
A = sparse.vstack(A_parts, format='csr', dtype=float)
w = numpy.concatenate(w_parts)
assert A.shape == (len(trainX), len(trainX))
return A, w
# endregion
# region FlatnessLossFunction
def exp_margin(margin):
""" margin = - y_signed * y_pred """
return numpy.exp(numpy.clip(margin, -1e5, 2))
class AbstractFlatnessLossFunction(AbstractLossFunction):
def __init__(self, uniform_variables, uniform_label=1, power=2., ada_coefficient=1.,
allow_wrong_signs=True, use_median=False,
keep_debug_info=False):
"""
This loss function contains separately penalty for non-flatness and ada_coefficient.
The penalty for non-flatness is using bins.
:type uniform_variables: the vars, along which we want to obtain uniformity
:type n_bins: the number of bins along each axis
:type uniform_label: int | list(int), the labels for which we want to obtain uniformity
:type power: the loss contains the difference | F - F_bin |^p, where p is power
:type ada_coefficient: coefficient of ada_loss added to this one. The greater the coefficient,
the less we tend to uniformity.
:type allow_wrong_signs: defines whether gradient may different sign from the "sign of class"
(i.e. may have negative gradient on signal)
"""
self.uniform_variables = uniform_variables
if isinstance(uniform_label, numbers.Number):
self.uniform_label = numpy.array([uniform_label])
else:
self.uniform_label = numpy.array(uniform_label)
self.power = power
self.ada_coefficient = ada_coefficient
self.allow_wrong_signs = allow_wrong_signs
self.keep_debug_info = keep_debug_info
self.use_median = use_median
def fit(self, X, y, sample_weight=None):
sample_weight = check_sample_weight(y, sample_weight=sample_weight)
assert len(X) == len(y), 'lengths are different'
X = pandas.DataFrame(X)
self.group_indices = dict()
self.group_weights = dict()
occurences = numpy.zeros(len(X))
for label in self.uniform_label:
self.group_indices[label] = self.compute_groups_indices(X, y, label=label)
self.group_weights[label] = compute_group_weights(self.group_indices[label], sample_weight=sample_weight)
for group in self.group_indices[label]:
occurences[group] += 1
out_of_bins = (occurences == 0) & numpy.in1d(y, self.uniform_label)
if numpy.mean(out_of_bins) > 0.01:
warnings.warn("%i events out of all bins " % numpy.sum(out_of_bins), UserWarning)
self.y = y
self.y_signed = 2 * y - 1
self.sample_weight = numpy.copy(sample_weight)
self.divided_weight = sample_weight / numpy.maximum(occurences, 1)
if self.keep_debug_info:
self.debug_dict = defaultdict(list)
return self
def compute_groups_indices(self, X, y, label):
raise NotImplementedError()
def __call__(self, pred):
# TODO implement,
# the actual value does not play any role in boosting, but is interesting
return 0
def negative_gradient(self, y_pred):
y_pred = numpy.ravel(y_pred)
neg_gradient = numpy.zeros(len(self.y), dtype=numpy.float)
for label in self.uniform_label:
label_mask = self.y == label
global_positions = numpy.zeros(len(y_pred), dtype=float)
global_positions[label_mask] = \
compute_positions(y_pred[label_mask], sample_weight=self.sample_weight[label_mask])
for indices_in_bin in self.group_indices[label]:
local_pos = compute_positions(y_pred[indices_in_bin],
sample_weight=self.sample_weight[indices_in_bin])
global_pos = global_positions[indices_in_bin]
bin_gradient = self.power * numpy.sign(local_pos - global_pos) * \
numpy.abs(local_pos - global_pos) ** (self.power - 1)
neg_gradient[indices_in_bin] += bin_gradient
neg_gradient *= self.divided_weight
assert numpy.all(neg_gradient[~numpy.in1d(self.y, self.uniform_label)] == 0)
y_signed = self.y_signed
if self.keep_debug_info:
self.debug_dict['pred'].append(numpy.copy(y_pred))
self.debug_dict['fl_grad'].append(numpy.copy(neg_gradient))
self.debug_dict['ada_grad'].append(y_signed * self.sample_weight * exp_margin(-y_signed * y_pred))
# adding ada
neg_gradient += self.ada_coefficient * y_signed * self.sample_weight * exp_margin(-y_signed * y_pred)
if not self.allow_wrong_signs:
neg_gradient = y_signed * numpy.clip(y_signed * neg_gradient, 0, 1e5)
return neg_gradient
def update_tree_leaf(self, leaf, indices_in_leaf,
X, y, y_pred, sample_weight, update_mask, residual):
if self.use_median:
residual = residual[indices_in_leaf]
return numpy.median(residual)
else:
return numpy.clip(y_pred[indices_in_leaf[0]], -10, 10)
class BinFlatnessLossFunction(AbstractFlatnessLossFunction):
def __init__(self, uniform_variables, n_bins=10, uniform_label=1, power=2., ada_coefficient=1.,
allow_wrong_signs=True, use_median=False, keep_debug_info=False):
self.n_bins = n_bins
AbstractFlatnessLossFunction.__init__(self, uniform_variables,
uniform_label=uniform_label, power=power, ada_coefficient=ada_coefficient,
allow_wrong_signs=allow_wrong_signs, use_median=use_median,
keep_debug_info=keep_debug_info)
def compute_groups_indices(self, X, y, label):
"""Returns a list, each element is events' indices in some group."""
label_mask = y == label
extended_bin_limits = []
for var in self.uniform_variables:
f_min, f_max = numpy.min(X[var][label_mask]), numpy.max(X[var][label_mask])
extended_bin_limits.append(numpy.linspace(f_min, f_max, 2 * self.n_bins + 1))
groups_indices = list()
for shift in [0, 1]:
bin_limits = []
for axis_limits in extended_bin_limits:
bin_limits.append(axis_limits[1 + shift:-1:2])
bin_indices = compute_bin_indices(X.ix[:, self.uniform_variables].values, bin_limits=bin_limits)
groups_indices += list(bin_to_group_indices(bin_indices, mask=label_mask))
return groups_indices
class KnnFlatnessLossFunction(AbstractFlatnessLossFunction):
def __init__(self, uniform_variables, n_neighbours=100, uniform_label=1, power=2., ada_coefficient=1.,
max_groups_on_iteration=3000, allow_wrong_signs=True, use_median=False, keep_debug_info=False,
random_state=None):
self.n_neighbours = n_neighbours
self.max_group_on_iteration = max_groups_on_iteration
self.random_state = random_state
AbstractFlatnessLossFunction.__init__(self, uniform_variables,
uniform_label=uniform_label, power=power, ada_coefficient=ada_coefficient,
allow_wrong_signs=allow_wrong_signs, use_median=use_median,
keep_debug_info=keep_debug_info)
def compute_groups_indices(self, X, y, label):
mask = y == label
self.random_state = check_random_state(self.random_state)
knn_indices = computeSignalKnnIndices(self.uniform_variables, X, mask,
n_neighbors=self.n_neighbours)[mask, :]
if len(knn_indices) > self.max_group_on_iteration:
selected_group = self.random_state.choice(len(knn_indices), size=self.max_group_on_iteration)
return knn_indices[selected_group, :]
else:
return knn_indices
# endregion