learnedbf 0.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
learnedbf/__init__.py ADDED
@@ -0,0 +1,1724 @@
1
+ import abc
2
+ import gc
3
+ import logging
4
+ import math
5
+ import numpy as np
6
+
7
+ from sklearn.base import BaseEstimator, ClassifierMixin
8
+ from sklearn.metrics import auc, precision_recall_curve, make_scorer, confusion_matrix
9
+ from sklearn.model_selection import StratifiedKFold, GridSearchCV, \
10
+ train_test_split
11
+ from sklearn.utils.validation import NotFittedError, check_X_y, check_array, \
12
+ check_is_fitted
13
+ from sklearn.neural_network import MLPClassifier
14
+ from sklearn.tree import DecisionTreeClassifier
15
+
16
+ from learnedbf.BF import BloomFilter, ClassicalBloomFilter, VarhashBloomFilter, ClassicalBloomFilterImpl
17
+ from learnedbf.classifiers import ScoredDecisionTreeClassifier
18
+
19
+ # TODO: check the behavior when using non-integer keys
20
+ # TODO: check what happens with the `classes_` attribute of classifiers
21
+ # not based on trees
22
+
23
+ __version__ = '0.6'
24
+
25
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
26
+
27
+ def auprc(y, y_hat):
28
+ precision, recall, thresholds = precision_recall_curve(y, y_hat)
29
+ return auc(recall, precision)
30
+
31
+ def auprc_score(cls, X, y):
32
+ scorer = make_scorer(auprc)
33
+ return scorer(cls, X, y)
34
+
35
+
36
+ def threshold_evaluate(epsilon, key_predictions, nonkey_predictions):
37
+ epsilon_tau = nonkey_predictions.sum() / len(nonkey_predictions)
38
+ if epsilon_tau >= epsilon:
39
+ # epsilon_tau >= epsilon, constraint not met
40
+ # return None, to get aware the caller that the
41
+ # current candidate threshold should not be considered
42
+ return None
43
+
44
+ epsilon_b = (epsilon - epsilon_tau) / (1 - epsilon_tau)
45
+
46
+ # compute m_b (backup filter bitmap size)
47
+ num_fn = (~key_predictions).sum()
48
+ m_b = -num_fn * np.log(epsilon_b) / np.log(2)**2
49
+ return epsilon_tau, epsilon_b, m_b
50
+
51
+ def check_y(y):
52
+ """ Check if the input array has valid labels for binary classification.
53
+ Valid combinations are (False, True), (0, 1), (-1, 1)
54
+ """
55
+ if y.dtype.type == np.bool_: return y
56
+
57
+ if np.all(np.isin(y, [-1, 1])) or np.all(np.isin(y, [0, 1])):
58
+ print("Warning: all the values of y are cast to bool")
59
+ return y == 1
60
+
61
+ raise ValueError("Possible values for y are (0, 1), (-1, 1) or \
62
+ (False, True)")
63
+
64
+
65
+ class LBF(BaseEstimator, BloomFilter, ClassifierMixin):
66
+ """Implementation of the Learned Bloom Filter"""
67
+
68
+ # MASTER TODO: Each classifier class should
69
+ # 1. output predictions in terms of True/False (MA VERO???)
70
+ # 2. implement a get_size method returning the size in bits of the model
71
+ # 3. implement a predict_score method returning the score of the
72
+ # classifier, intended as how confident the classifier is in saying that
73
+ # an element is a key.
74
+
75
+ def __init__(self,
76
+ n=None,
77
+ epsilon=None,
78
+ m=None,
79
+ classifier=ScoredDecisionTreeClassifier(),
80
+ hyperparameters={},
81
+ num_candidate_thresholds=10,
82
+ threshold_test_size=0.7,
83
+ model_selection_method=StratifiedKFold(n_splits=5,
84
+ shuffle=True),
85
+ scoring=auprc_score,
86
+ threshold_evaluate=threshold_evaluate,
87
+ threshold=None,
88
+ classical_BF_class=ClassicalBloomFilterImpl,
89
+ backup_filter_size=None,
90
+ random_state=4678913,
91
+ verbose=False):
92
+ """Create an instance of :class:`LBF`.
93
+
94
+ :param n: number of keys, defaults to None.
95
+ :type n: `int`
96
+ :param epsilon: expected false positive rate, defaults to None.
97
+ :type epsilon: `float`
98
+ :param m: dimension in bit of the bitmap, defaults to None.
99
+ :type m: `int`
100
+ :param classifier: classifier to be trained, defaults to
101
+ :class:`DecisionTreeClassifier`.
102
+ :type classifier: :class:`sklearn.BaseEstimator`
103
+ :param hyperparameters: grid of values for hyperparameters to be
104
+ considered during classifier training, defaults to {}.
105
+ :type hyperparameters: `dict`
106
+ :param num_candidate_thresholds: number of candidate thresholds to be
107
+ considered for mapping classifier scores onto predictions,
108
+ defaults to 10.
109
+ :type num_candidate_thresholds: `int`
110
+ :param threshold_test_size: relative validation set size used to set
111
+ the best classifier threshold, defaults to 0.7.
112
+ :param model_selection_method: strategy to be used for
113
+ discovering the best hyperparameter values for the learnt
114
+ classifier, defaults to
115
+ `StratifiedKFold(n_splits=5, shuffle=True)`.
116
+ :type model_selection_method:
117
+ :class:`sklearn.model_selection.BaseShuffleSplit` or
118
+ :class:`sklearn.model_selection.BaseCrossValidator`
119
+ :param scoring: method to be used for scoring learnt
120
+ classifiers, defaults to `auprc`.
121
+ :type scoring: `str` or function
122
+ :param threshold_evaluate: function to be used to optimize the
123
+ classifier threshold choice (NOTE: at the current implementation
124
+ stage there are no alternatives w.r.t. minimizing the size of the
125
+ backup filter).
126
+ :type threshold_evaluate: function
127
+ :param threshold: the threshold of the bloom filter, defaults to `None`.
128
+ :type threshold: `float`
129
+ :param classical_BF_class: class of the backup filter, defaults
130
+ to :class:`ClassicalBloomFilterImpl`.
131
+ :param backup_filter_size: the size of the backup filter, defaults to `None`.
132
+ :type backup_filter_size: `int`
133
+ :param random_state: random seed value, defaults to `None`,
134
+ meaning the current seed value should be kept.
135
+ :type random_state: `int` or `None`
136
+ :param verbose: flag triggering verbose logging, defaults to
137
+ `False`.
138
+ :type verbose: `bool`
139
+ """
140
+
141
+ self.n = n
142
+ self.epsilon = epsilon
143
+ self.m = m
144
+ self.classifier = classifier
145
+ self.hyperparameters = hyperparameters
146
+ self.num_candidate_thresholds = num_candidate_thresholds
147
+ self.threshold_test_size = threshold_test_size
148
+ self.model_selection_method = model_selection_method
149
+ self.scoring = scoring
150
+ self.threshold_evaluate = threshold_evaluate
151
+ self.threshold = threshold
152
+ self.classical_BF_class = classical_BF_class
153
+ self.backup_filter_size = backup_filter_size
154
+ self.random_state = random_state
155
+ self.verbose = verbose
156
+
157
+ def __repr__(self):
158
+ args = []
159
+ if self.epsilon != None:
160
+ args.append(f'epsilon={self.epsilon}')
161
+ if self.classifier.__repr__() != 'ScoredDecisionTreeClassifier()':
162
+ args.append(f'classifier={self.classifier}')
163
+ if self.hyperparameters != {}:
164
+ args.append(f'hyperparameters={self.hyperparameters}')
165
+ if self.threshold != None:
166
+ args.append(f'threshold={self.threshold}')
167
+ if (self.model_selection_method.__class__ != StratifiedKFold or
168
+ self.model_selection_method.n_splits != 5 or
169
+ self.model_selection_method.shuffle != True):
170
+ args.append(f'model_selection_method={self.model_selection_method}')
171
+ if callable(self.scoring):
172
+ if self.scoring.__name__ != 'auprc_score':
173
+ args.append(f'scoring={self.scoring.__name__}')
174
+ else:
175
+ score_name = args.append(f'scoring="{self.scoring}"')
176
+ if self.random_state != 4678913:
177
+ args.append(f'random_state={self.random_state}')
178
+ if self.verbose != False:
179
+ args.append(f'verbose={self.verbose}')
180
+
181
+ args = ', '.join(args)
182
+ return f'LBF({args})'
183
+
184
+ def fit(self, X, y):
185
+ """Fits the Learned Bloom Filter, training its classifier,
186
+ setting the score threshold and building the backup filter.
187
+
188
+ :param X: examples to be used for fitting the classifier.
189
+ :type X: array of numerical arrays
190
+ :param y: labels of the examples.
191
+ :type y: array of `bool`
192
+ :return: the fit Bloom Filter instance.
193
+ :rtype: :class:`LBF`
194
+ :raises: `ValueError` if X is empty, or if no threshold value is
195
+ compliant with the false positive rate requirements.
196
+
197
+ NOTE: If the classifier variable instance has been specified as an
198
+ already trained classifier, `X` and `y` are considered as the dataset
199
+ to be used to build the LBF, that is, setting the threshold for the
200
+ in output of the classifier, and evaluating the overall empirical FPR.
201
+ In this case, `X` and `y` are assumed to contain values not used in
202
+ order to infer the classifier, in order to ensure a fair estimate of
203
+ FPR. Otherwise, `X` and `y` are meant to be the examples to be used to
204
+ train the classifier, and subsequently set the threshold and evaluate
205
+ the empirical FPR.
206
+ """
207
+
208
+ if self.m is None and self.epsilon is None:
209
+ raise ValueError("At least one parameter \
210
+ between mand epsilon must be specified.")
211
+
212
+ if len(X) == 0:
213
+ raise ValueError('Empty set of keys')
214
+
215
+ X, y = check_X_y(X, y)
216
+
217
+ y = check_y(y)
218
+
219
+ if self.random_state is not None:
220
+ self.model_selection_method.random_state = self.random_state
221
+
222
+ X_pos = X[y]
223
+
224
+ self.n = len(X_pos)
225
+
226
+ y_pos = y[y]
227
+
228
+ try:
229
+ check_is_fitted(self.classifier)
230
+ # a trained classifier was passed to the constructor
231
+ X_neg_threshold_test = X[~y]
232
+ except NotFittedError:
233
+ # the classifier has to be trained
234
+ X_neg = X[~y]
235
+
236
+ X_neg_trainval, X_neg_threshold_test = \
237
+ train_test_split(X_neg,
238
+ test_size=self.threshold_test_size,
239
+ random_state=self.random_state)
240
+ del X_neg
241
+ gc.collect()
242
+ y_neg_trainval = [False] * len(X_neg_trainval)
243
+ X_trainval = np.vstack([X_pos, X_neg_trainval])
244
+ del X_neg_trainval
245
+ gc.collect()
246
+
247
+ y_trainval = np.hstack([y_pos, y_neg_trainval])
248
+ del y_neg_trainval
249
+ gc.collect()
250
+
251
+ model = GridSearchCV(estimator=self.classifier,
252
+ param_grid=self.hyperparameters,
253
+ cv=self.model_selection_method,
254
+ scoring=self.scoring,
255
+ refit=True,
256
+ n_jobs=-1)
257
+ model.fit(X_trainval, y_trainval)
258
+ del X_trainval, y_trainval
259
+ gc.collect()
260
+ self.classifier = model.best_estimator_
261
+
262
+ backup_filter_fpr = None
263
+ if self.threshold is None:
264
+ key_scores = self.classifier.predict_score(X_pos)
265
+ del X_pos
266
+ gc.collect()
267
+ nonkey_scores = self.classifier.predict_score(X_neg_threshold_test)
268
+ del X_neg_threshold_test
269
+ gc.collect()
270
+
271
+ scores = np.hstack([key_scores, nonkey_scores])
272
+
273
+ # unique_scores = np.unique(scores)
274
+ # n_unique = len(unique_scores)
275
+ # if n_unique <= self.num_candidate_thresholds:
276
+ # self.num_candidate_thresholds = n_unique - 1
277
+ # candidate_threshold = np.sort(unique_scores)[:-1]
278
+ # else:
279
+ # candidate_threshold = \
280
+ # np.quantile(scores,
281
+ # np.linspace(0,
282
+ # 1 - 1 / len(scores),
283
+ # self.num_candidate_thresholds))
284
+ candidate_threshold = \
285
+ np.quantile(scores,
286
+ np.linspace(0,
287
+ 1 - 1 / len(scores),
288
+ self.num_candidate_thresholds))
289
+
290
+ self.backup_filter_size = np.inf
291
+ self.threshold = None
292
+
293
+ if self.m is not None:
294
+ epsilon = 1
295
+ self.backup_filter_size = self.m
296
+ for t in candidate_threshold:
297
+ key_predictions = (key_scores > t)
298
+ nonkey_predictions = (nonkey_scores > t)
299
+
300
+ num_fn = (~key_predictions).sum()
301
+ Fp = nonkey_predictions.sum() / len(nonkey_predictions)
302
+
303
+ if num_fn == 0:
304
+ #no FN so epsilon_lbf = epsilon_tau
305
+ epsilon_lbf = Fp
306
+ e_b=1
307
+
308
+ else:
309
+ e_b = np.exp(-np.log(2)**2 * self.m / num_fn)
310
+ if self.verbose:
311
+ print(f"e_b = {e_b}")
312
+ epsilon_lbf = Fp + (1-Fp) * e_b
313
+
314
+
315
+ if self.verbose:
316
+ print(f"t = {t}")
317
+ print(f"Fp = {Fp}")
318
+ print(f"nFn = {num_fn}")
319
+ print(f"bf epsilon={e_b}")
320
+ print(f"lbf epsilon={epsilon_lbf}")
321
+
322
+ if epsilon_lbf < epsilon:
323
+ backup_filter_fpr = e_b
324
+ epsilon = epsilon_lbf
325
+ if self.verbose:
326
+ print("NEW OPTIMAL VALUE FOUND")
327
+
328
+ self.threshold = t
329
+
330
+ if self.verbose:
331
+ print("=============")
332
+
333
+ if self.epsilon is not None and epsilon > self.epsilon:
334
+ raise ValueError("No threshold value is feasible.")
335
+ self.epsilon = epsilon
336
+
337
+ elif self.epsilon is not None:
338
+ #caso ottimizzo m
339
+ for t in candidate_threshold:
340
+ key_predictions = (key_scores > t)
341
+ nonkey_predictions = (nonkey_scores > t)
342
+
343
+ nonkey_predictions_temp = (nonkey_scores >= t)
344
+ epsilon_tau = nonkey_predictions_temp.sum() / len(nonkey_predictions_temp)
345
+
346
+ result = threshold_evaluate(self.epsilon,
347
+ key_predictions,
348
+ nonkey_predictions)
349
+ if result is None:
350
+ # epsilon_tau >= epsilon, constraint not met
351
+ # don't consider this value of t
352
+ continue
353
+
354
+ e_t, e_b, m_b = result
355
+
356
+ if m_b == 0 and e_t <= self.epsilon:
357
+ self.threshold = t
358
+ self.backup_filter_ = None
359
+ break
360
+
361
+
362
+ if m_b < self.backup_filter_size:
363
+ self.threshold = t
364
+ self.backup_filter_size = m_b
365
+ backup_filter_fpr = e_b
366
+
367
+
368
+ if self.threshold is None:
369
+ raise ValueError('No threshold value is feasible.')
370
+ else:
371
+ if self.backup_filter_size is None:
372
+ raise ValueError('threshold set in LBF'
373
+ ' without setting the backup filter size')
374
+
375
+ all_keys = X[y]
376
+ key_scores = self.classifier.predict_score(all_keys)
377
+ key_predictions = (key_scores > self.threshold)
378
+
379
+ fn_mask = ~key_predictions
380
+ num_fn = fn_mask.sum()
381
+
382
+ if num_fn > 0:
383
+ #if the number of fn is very small the estimated backup_filter_fpr
384
+ #results equal to zero and the Bloom filter raises an exception
385
+ if backup_filter_fpr == 0.0:
386
+ backup_filter_fpr = None
387
+
388
+ self.backup_filter_ = \
389
+ ClassicalBloomFilter(filter_class=self.classical_BF_class,
390
+ n=num_fn,
391
+ epsilon=backup_filter_fpr,
392
+ m=self.backup_filter_size)
393
+
394
+ self.backup_filter_.fit(all_keys[fn_mask])
395
+ else:
396
+ self.backup_filter_ = None
397
+
398
+ # TODO: is it necessary to save X and y? probably not, check this.
399
+ # self.X_ = X
400
+ # self.y_ = y
401
+
402
+ self.is_fitted_ = True
403
+ self.n_features_in_ = X.shape[1]
404
+
405
+ return self
406
+
407
+ def predict(self, X):
408
+ """Computes predictions for a set of queries, each to be checked
409
+ for inclusion in the Learned Bloom Filter.
410
+
411
+ :param X: elements to classify.
412
+ :type X: array of numerical arrays
413
+ :return: prediction for each value in 'X'.
414
+ :rtype: array of `bool`
415
+ :raises: NotFittedError if the classifier is not fitted.
416
+
417
+ NOTE: the implementation assumes that the classifier which is
418
+ used (either pre-trained or trained in fit) refers to 1 as the
419
+ label of keys in the Bloom filter
420
+ """
421
+ # TODO test that the assumption above is met for all classifiers
422
+ # that have been tested.
423
+ # TODO: rework after new classifier classes have been introduced
424
+
425
+ check_is_fitted(self, 'is_fitted_')
426
+ X = check_array(X)
427
+
428
+ scores = self.classifier.predict_score(X)
429
+
430
+ predictions = scores > self.threshold
431
+ if self.backup_filter_ is not None and not predictions.all():
432
+ predictions[~predictions] = (self.backup_filter_
433
+ .predict(X[~predictions]))
434
+ return predictions
435
+
436
+ def get_size(self):
437
+ """Return the Learned Bloom Filter size.
438
+
439
+ :return: size of the Learned Bloom Filter (in bits), detailed
440
+ w.r.t. the size of the classifier and of the backup filter.
441
+ :rtype: `dict`
442
+
443
+ NOTE: the implementation assumes that the classifier object used to
444
+ build the Learned Bloom Filter has a get_size method, returning the
445
+ size of the classifier, measured in bits.
446
+ """
447
+
448
+ # TODO subclass all classes of the considered classifiers in order to
449
+ # add the get_size method, also providing a flag in the constructor,
450
+ # allowing either to compute the theoretical size or the size actually
451
+ # occupied by the model (i.e., via json.dumps or sys.getsizeof).
452
+
453
+ check_is_fitted(self, 'is_fitted_')
454
+
455
+ # TODO: implement the computation of classifier size
456
+ backup_filter_size = self.backup_filter_.get_size() \
457
+ if self.backup_filter_ is not None else 0
458
+ return {'backup_filter': backup_filter_size,
459
+ 'classifier': self.classifier.get_size()}
460
+
461
+ class SLBF(BaseEstimator, BloomFilter, ClassifierMixin):
462
+ """Implementation of the Sandwiched Learned Bloom Filter"""
463
+
464
+ def __init__(self,
465
+ n=None,
466
+ epsilon=None,
467
+ m=None,
468
+ classifier=ScoredDecisionTreeClassifier(),
469
+ hyperparameters={},
470
+ num_candidate_thresholds=10,
471
+ threshold_test_size=0.7,
472
+ model_selection_method=StratifiedKFold(n_splits=5,
473
+ shuffle=True),
474
+ scoring=auprc_score,
475
+ threshold_evaluate=threshold_evaluate,
476
+ classical_BF_class=ClassicalBloomFilterImpl,
477
+ random_state=4678913,
478
+ verbose=False):
479
+ """Create an instance of :class:`SLBF`.
480
+
481
+ :param n: number of keys, defaults to None.
482
+ :type n: `int`
483
+ :param epsilon: expected false positive rate, defaults to None.
484
+ :type epsilon: `float`
485
+ :param m: dimension in bit of the bitmap, defaults to None.
486
+ :type m: `int`
487
+ :param classifier: classifier to be trained, defaults to
488
+ :class:`DecisionTreeClassifier`.
489
+ :type classifier: :class:`sklearn.BaseEstimator`
490
+ :param hyperparameters: grid of values for hyperparameters to be
491
+ considered during classifier training, defaults to {}.
492
+ :type hyperparameters: `dict`
493
+ :param num_candidate_thresholds: number of candidate thresholds to be
494
+ considered for mapping classifier scores onto p redictions,
495
+ defaults to 10.
496
+ :type num_candidate_thresholds: `int`
497
+ :param threshold_test_size: relative validation set size used to set
498
+ the best classifier threshold, defaults to 0.7.
499
+ :type test_size: `float`
500
+ :param model_selection_method: strategy to be used for
501
+ discovering the best hyperparameter values for the learnt
502
+ classifier, defaults to
503
+ `StratifiedKFold(n_splits=5, shuffle=True)`.
504
+ :type model_selection_method:
505
+ :class:`sklearn.model_selection.BaseShuffleSplit` or
506
+ :class:`sklearn.model_selection.BaseCrossValidator`
507
+ :param scoring: method to be used for scoring learnt
508
+ classifiers, defaults to `auprc`.
509
+ :type scoring: `str` or function
510
+ :param threshold_evaluate: function to be used to optimize the
511
+ classifier threshold choice (NOTE: at the current implementation
512
+ stage there are no alternatives w.r.t. minimizing the size of the
513
+ backup filter).
514
+ :type threshold_evaluate: function
515
+ :param classical_BF_class: class of the backup filter, defaults
516
+ to :class:`ClassicalBloomFilterImpl`.
517
+ :param random_state: random seed value, defaults to `None`,
518
+ meaning the current seed value should be kept.
519
+ :type random_state: `int` or `None`
520
+ :param verbose: flag triggering verbose logging, defaults to
521
+ `False`.
522
+ :type verbose: `bool`
523
+ """
524
+
525
+ self.n = n
526
+ self.epsilon = epsilon
527
+ self.m = m
528
+ self.classifier = classifier
529
+ self.hyperparameters = hyperparameters
530
+ self.num_candidate_thresholds = num_candidate_thresholds
531
+ self.threshold_test_size = threshold_test_size
532
+ self.model_selection_method = model_selection_method
533
+ self.scoring = scoring
534
+ self.threshold_evaluate = threshold_evaluate
535
+ self.classical_BF_class = classical_BF_class
536
+ self.random_state = random_state
537
+ self.verbose = verbose
538
+
539
+ def __repr__(self):
540
+ args = []
541
+ if self.epsilon != None:
542
+ args.append(f'epsilon={self.epsilon}')
543
+ if self.classifier.__repr__() != 'ScoredDecisionTreeClassifier()':
544
+ args.append(f'classifier={self.classifier}')
545
+ if self.hyperparameters != {}:
546
+ args.append(f'hyperparameters={self.hyperparameters}')
547
+ if (self.model_selection_method.__class__ != StratifiedKFold or
548
+ self.model_selection_method.n_splits != 5 or
549
+ self.model_selection_method.shuffle != True):
550
+ args.append(f'model_selection_method={self.model_selection_method}')
551
+ if callable(self.scoring):
552
+ if self.scoring.__name__ != 'auprc_score':
553
+ args.append(f'scoring={self.scoring.__name__}')
554
+ else:
555
+ score_name = args.append(f'scoring="{self.scoring}"')
556
+ if self.random_state != 4678913:
557
+ args.append(f'random_state={self.random_state}')
558
+ if self.verbose != False:
559
+ args.append(f'verbose={self.verbose}')
560
+
561
+ args = ', '.join(args)
562
+ return f'SLBF({args})'
563
+
564
+ def fit(self, X, y):
565
+ """Fits the Learned Bloom Filter, training its classifier,
566
+ setting the score threshold and building the backup filter.
567
+
568
+ :param X: examples to be used for fitting the classifier.
569
+ :type X: array of numerical arrays
570
+ :param y: labels of the examples.
571
+ :type y: array of `bool`
572
+ :return: the fit Bloom Filter instance.
573
+ :rtype: :class:`LBF`
574
+ :raises: `ValueError` if X is empty, or if no threshold value is
575
+ compliant with the false positive rate requirements.
576
+
577
+ NOTE: If the classifier variable instance has been specified as an
578
+ already trained classifier, `X` and `y` are considered as the dataset
579
+ to be used to build the LBF, that is, setting the threshold for the
580
+ in output of the classifier, and evaluating the overall empirical FPR.
581
+ In this case, `X` and `y` are assumed to contain values not used in
582
+ order to infer the classifier, in order to ensure a fair estimate of
583
+ FPR. Otherwise, `X` and `y` are meant to be the examples to be used to
584
+ train the classifier, and subsequently set the threshold and evaluate
585
+ the empirical FPR.
586
+ """
587
+
588
+ # TODO: check whether or not allowing a future release in which m
589
+ # is specified by the user, but in such case this code should be
590
+ # placed after the classifier has been provided / trained.
591
+ # if self.m is not None:
592
+ # raise NotImplementedError('LBF fixed size in constructor not yet'
593
+ # ' implemented.')
594
+
595
+ # self.n, self.epsilon, self.m = check_params_(self.n, self.epsilon,
596
+ # self.m)
597
+
598
+ if len(X) == 0:
599
+ raise ValueError('Empty set of keys')
600
+
601
+ if self.m is None and self.epsilon is None:
602
+ raise ValueError("At least one parameter \
603
+ between mand epsilon must be specified.")
604
+
605
+ X, y = check_X_y(X, y)
606
+
607
+ y = check_y(y)
608
+
609
+ if self.random_state is not None:
610
+ self.model_selection_method.random_state = self.random_state
611
+
612
+ X_pos = X[y]
613
+
614
+ self.n = len(X_pos)
615
+
616
+ y_pos = y[y]
617
+
618
+ try:
619
+ check_is_fitted(self.classifier)
620
+ # a trained classifier was passed to the constructor
621
+ X_neg_threshold_test = X[~y]
622
+ except NotFittedError:
623
+ # the classifier has to be trained
624
+ X_neg = X[~y]
625
+
626
+ X_neg_trainval, X_neg_threshold_test = \
627
+ train_test_split(X_neg,
628
+ test_size=self.threshold_test_size,
629
+ random_state=self.random_state)
630
+ del X_neg
631
+ gc.collect()
632
+ y_neg_trainval = [False] * len(X_neg_trainval)
633
+ X_trainval = np.vstack([X_pos, X_neg_trainval])
634
+ del X_neg_trainval
635
+ gc.collect()
636
+
637
+ y_trainval = np.hstack([y_pos, y_neg_trainval])
638
+ del y_neg_trainval
639
+ gc.collect()
640
+
641
+ model = GridSearchCV(estimator=self.classifier,
642
+ param_grid=self.hyperparameters,
643
+ cv=self.model_selection_method,
644
+ scoring=self.scoring,
645
+ refit=True,
646
+ n_jobs=-1)
647
+ model.fit(X_trainval, y_trainval)
648
+ del X_trainval, y_trainval
649
+ gc.collect()
650
+ self.classifier = model.best_estimator_
651
+
652
+ key_scores = self.classifier.predict_score(X_pos)
653
+ del X_pos
654
+ gc.collect()
655
+ nonkey_scores = self.classifier.predict_score(X_neg_threshold_test)
656
+ del X_neg_threshold_test
657
+ gc.collect()
658
+
659
+ scores = np.hstack([key_scores, nonkey_scores])
660
+ candidate_threshold = \
661
+ np.quantile(scores,
662
+ np.linspace(0,
663
+ 1 - 1 / len(scores),
664
+ self.num_candidate_thresholds,
665
+ endpoint=False))
666
+
667
+ initial_filter_size_opt = 0
668
+ backup_filter_size_opt = m_optimal = np.inf
669
+
670
+ # when optimizing the number of hash functions in a classical BF,
671
+ # the probability of a false positive is alpha raised to m/n,
672
+ # m is the size in bit of the bitmap and n is the number of keys.
673
+ alpha = 0.5 ** math.log(2)
674
+
675
+ # We prefer to stick to a notation analogous to that of formula
676
+ # (2) in Mitzenmacher, A Model for Learned Bloom Filters,
677
+ # and Optimizing by Sandwiching.
678
+ threshold = None
679
+
680
+ if self.m is not None:
681
+ #fixed bit array size: optimize epsilon
682
+
683
+ epsilon_lbf_optimal = 1
684
+ epsilon_optimal = 1
685
+
686
+ for t in candidate_threshold:
687
+ key_predictions = (key_scores > t)
688
+ n_Fn = (~key_predictions).sum()
689
+ Fn = (~key_predictions).sum() / len(key_predictions)
690
+ nonkey_predictions = (nonkey_scores > t)
691
+ Fp = nonkey_predictions.sum() / len(nonkey_predictions)
692
+
693
+ if Fp == 1 or Fn == 1:
694
+ continue
695
+
696
+ if Fp == 0:
697
+ #No need for initial filter, use only the lbf
698
+ backup_filter_size = self.m
699
+ initial_filter_size = 0
700
+
701
+ elif Fn == 0:
702
+ # No need for backup filter in LBF, but we need inital BF
703
+ initial_filter_size = self.m
704
+ backup_filter_size = 0
705
+
706
+ else:
707
+ #we need both initial and backup filter
708
+ b2 = Fn * math.log( \
709
+ Fp / ((1 - Fp) * (1/Fn - 1))) / math.log(alpha)
710
+
711
+ backup_filter_size = b2 * self.n
712
+ initial_filter_size = self.m - backup_filter_size
713
+
714
+ # The optimal backup filter size exceeds the given bitarray
715
+ # max size
716
+ if backup_filter_size > self.m:
717
+ backup_filter_size = self.m
718
+ initial_filter_size = 0
719
+
720
+ #estimate the slbf FPR
721
+ epsilon_initial_filter = alpha ** (initial_filter_size/self.n)
722
+ epsilon_b = 0
723
+ if n_Fn > 0:
724
+ epsilon_b = alpha ** (backup_filter_size / n_Fn)
725
+
726
+ epsilon_lbf = Fp + (1-Fp) * epsilon_b
727
+ epsilon_slbf = epsilon_initial_filter * (epsilon_lbf)
728
+
729
+
730
+ if self.verbose:
731
+ print(f'Fp = {Fp}')
732
+ print(f'Fn = {Fn}')
733
+ print(f't={t}')
734
+ print(f'b1_size={initial_filter_size}')
735
+ print(f'b2_size={backup_filter_size}')
736
+
737
+ if epsilon_slbf < epsilon_optimal:
738
+ if self.verbose:
739
+ print("NEW OPTIMAL VALUE FOUND")
740
+ epsilon_lbf_optimal = epsilon_lbf
741
+ epsilon_optimal = epsilon_lbf
742
+ optimal_b1 = initial_filter_size
743
+ optimal_b2 = backup_filter_size
744
+ threshold = t
745
+
746
+ if self.verbose:
747
+ print(f'=============================')
748
+
749
+ if self.epsilon and epsilon_optimal > self.epsilon:
750
+ raise ValueError("No threshold value is feasible.")
751
+ self.epsilon=epsilon_optimal
752
+ backup_filter_size = optimal_b2
753
+ initial_filter_size = optimal_b1
754
+ elif self.epsilon is not None:
755
+ # fixed epsilon: optimize bit array size
756
+ for t in candidate_threshold:
757
+ key_predictions = (key_scores > t)
758
+ Fn = (~key_predictions).sum() / len(key_predictions)
759
+ nonkey_predictions = (nonkey_scores > t)
760
+ Fp = nonkey_predictions.sum() / len(nonkey_predictions)
761
+
762
+ if Fp == 1 or Fn == 1:
763
+ continue
764
+
765
+ if Fp == 0:
766
+
767
+ if Fp > (1-Fn):
768
+ continue
769
+
770
+ # No need for initial filter, just build LBF with its own
771
+ # backup filter
772
+ initial_filter_size = 0
773
+
774
+ epsilon_b = (self.epsilon - Fp) / (1 - Fp)
775
+
776
+ backup_filter_size = -(Fn * self.n) * \
777
+ np.log(epsilon_b) / np.log(2)**2
778
+
779
+ epsilon_lbf = Fp + (1-Fp)*epsilon_b
780
+
781
+ elif Fn == 0:
782
+ backup_filter_size = 0
783
+ epsilon_lbf = Fp
784
+ # No need for backup filter in LBF, but we need inital BF
785
+ epsilon_initial_filter = self.epsilon/Fp
786
+ if epsilon_initial_filter > 1:
787
+ # Weird but possible case: the classifier alone has no
788
+ # false negatives and its false positive rate is better
789
+ # than the required rate for the SLBF.
790
+ initial_filter_size = 0
791
+ else:
792
+ initial_filter_size = -self.n * \
793
+ np.log(epsilon_initial_filter) / np.log(2)**2
794
+
795
+ else:
796
+ if Fp < self.epsilon * (1-Fn) or Fp > (1-Fn):
797
+ continue
798
+
799
+ b2 = Fn * math.log( \
800
+ Fp / ((1 - Fp) * (1/Fn - 1))) / math.log(alpha)
801
+ epsilon_lbf = Fp + (1-Fp)* alpha ** (b2/Fn)
802
+
803
+ b1 = math.log(self.epsilon / (epsilon_lbf)) \
804
+ / math.log(alpha)
805
+
806
+ initial_filter_size = b1 * self.n
807
+ backup_filter_size = b2 * self.n
808
+ m = initial_filter_size + backup_filter_size
809
+ if m < m_optimal:
810
+ m_optimal = m
811
+ backup_filter_size_opt = backup_filter_size
812
+ initial_filter_size_opt = initial_filter_size
813
+ epsilon_lbf_optimal = epsilon_lbf
814
+ threshold = t
815
+ if self.verbose:
816
+ print(f'Fp = {Fp}')
817
+ print(f'Fn = {Fn}')
818
+ print(f't={t}')
819
+ print(f'initial filter opt size={initial_filter_size_opt}')
820
+ print(f'backup filter opt size={backup_filter_size_opt}')
821
+ print(f'=============================')
822
+
823
+ if m_optimal == np.inf:
824
+ raise ValueError('No threshold value is feasible.')
825
+
826
+ backup_filter_size = backup_filter_size_opt
827
+ initial_filter_size = initial_filter_size_opt
828
+
829
+ all_keys = X[y]
830
+ if initial_filter_size > 0:
831
+ self.initial_filter_ = ClassicalBloomFilter(filter_class=self.classical_BF_class,
832
+ n=self.n,
833
+ m=initial_filter_size)
834
+ self.initial_filter_.fit(all_keys)
835
+ true_mask = self.initial_filter_.predict(X)
836
+ else:
837
+ self.initial_filter_ = None
838
+ true_mask = [True] * len(X)
839
+
840
+ # TODO in this implementation, the optimal threshold is computed
841
+ # anew, and this is pointless, as we already know that
842
+ # the optimal size of the Backup filter. We can pass to the
843
+ # constructor both epsilon and backup filter size and check in
844
+ # fit of LBF: if these are provided, skip threshold analysis.
845
+ self.lbf_ = LBF(epsilon=epsilon_lbf_optimal,
846
+ classifier=self.classifier,
847
+ threshold=threshold,
848
+ backup_filter_size=backup_filter_size)
849
+ self.lbf_.fit(X[true_mask], y[true_mask])
850
+
851
+ self.is_fitted_ = True
852
+ self.n_features_in_ = X.shape[1]
853
+
854
+ return self
855
+
856
+ def predict(self, X):
857
+ """Computes predictions for a set of queries, each to be checked
858
+ for inclusion in the Learned Bloom Filter.
859
+
860
+ :param X: elements to classify.
861
+ :type X: array of numerical arrays
862
+ :return: prediction for each value in 'X'.
863
+ :rtype: array of `bool`
864
+ :raises: NotFittedError if the classifier is not fitted.
865
+
866
+ NOTE: the implementation assumes that the classifier which is
867
+ used (either pre-trained or trained in fit) refers to 1 as the
868
+ label of keys in the Bloom filter
869
+ """
870
+ # TODO test that the assumption above is met for all classifiers
871
+ # that have been tested.
872
+ # TODO: rework after new classifier classes have been introduced
873
+
874
+ check_is_fitted(self, 'is_fitted_')
875
+ X = check_array(X)
876
+
877
+ if self.initial_filter_ is not None:
878
+ predictions = self.initial_filter_.predict(X)
879
+ else:
880
+ predictions = np.array([True] * len(X))
881
+
882
+ if len(X[predictions]) > 0:
883
+ predictions[predictions] = self.lbf_.predict(X[predictions])
884
+
885
+ return predictions
886
+
887
+ def get_size(self):
888
+ """Return the Learned Bloom Filter size.
889
+
890
+ :return: size of the Learned Bloom Filter (in bits), detailed
891
+ w.r.t. the size of the classifier and of the backup filter.
892
+ :rtype: `dict`
893
+
894
+ NOTE: the implementation assumes that the classifier object used to
895
+ build the Learned Bloom Filter has a get_size method, returning the
896
+ size of the classifier, measured in bits.
897
+ """
898
+
899
+ # TODO subclass all classes of the considered classifiers in order to
900
+ # add the get_size method, also providing a flag in the constructor,
901
+ # allowing either to compute the theoretical size or the size actually
902
+ # occupied by the model (i.e., via json.dumps or sys.getsizeof).
903
+
904
+ check_is_fitted(self, 'is_fitted_')
905
+
906
+ initial_filter_size = self.initial_filter_.get_size() \
907
+ if self.initial_filter_ is not None else 0
908
+ backup_filter_size = self.lbf_.backup_filter_.get_size() \
909
+ if self.lbf_.backup_filter_ is not None else 0
910
+ return {'backup_filter': backup_filter_size,
911
+ 'initial_filter': initial_filter_size,
912
+ 'classifier': self.lbf_.classifier.get_size()}
913
+
914
+ class AdaBF(BaseEstimator, BloomFilter, ClassifierMixin):
915
+ """Implementation of the Adaptive Learned Bloom Filter"""
916
+
917
+ def __init__(self,
918
+ n=None,
919
+ epsilon=None,
920
+ m=None,
921
+ classifier=ScoredDecisionTreeClassifier(),
922
+ hyperparameters={},
923
+ threshold_test_size=0.2,
924
+ model_selection_method=StratifiedKFold(n_splits=5,
925
+ shuffle=True),
926
+ scoring=auprc_score,
927
+ backup_filter_size=None,
928
+ random_state=4678913,
929
+ c_min = 1.6,
930
+ c_max = 2.5,
931
+ num_group_min = 8,
932
+ num_group_max = 12,
933
+ verbose=False):
934
+ """Create an instance of :class:`AdaBF`.
935
+
936
+ :param n: number of keys, defaults to None.
937
+ :type n: `int`
938
+ :param epsilon: expected false positive rate, defaults to None.
939
+ :type epsilon: `float`
940
+ :param m: dimension in bit of the bitmap, defaults to None.
941
+ :type m: `int`
942
+ :param classifier: classifier to be trained, defaults to
943
+ :class:`DecisionTreeClassifier`.
944
+ :type classifier: :class:`sklearn.BaseEstimator`
945
+ :param hyperparameters: grid of values for hyperparameters to be
946
+ considered during classifier training, defaults to {}.
947
+ :type hyperparameters: `dict`
948
+ :param num_candidate_thresholds: number of candidate thresholds to be
949
+ considered for mapping classifier scores onto p redictions,
950
+ defaults to 10.
951
+ :type num_candidate_thresholds: `int`
952
+ :param threshold_test_size: relative validation set size used to set
953
+ the best classifier threshold, defaults to 0.2.
954
+ :param model_selection_method: strategy to be used for
955
+ discovering the best hyperparameter values for the learnt
956
+ classifier, defaults to
957
+ `StratifiedKFold(n_splits=5, shuffle=True)`.
958
+ :type model_selection_method:
959
+ :class:`sklearn.model_selection.BaseShuffleSplit` or
960
+ :class:`sklearn.model_selection.BaseCrossValidator`
961
+ :param scoring: method to be used for scoring learnt
962
+ classifiers, defaults to `auprc`.
963
+ :type scoring: `str` or function
964
+ :param backup_filter_size: the size of the backup filter,
965
+ defaults to `None`.
966
+ :type backup_filter_size: `int`
967
+ :param random_state: random seed value, defaults to `None`,
968
+ meaning the current seed value should be kept.
969
+ :type random_state: `int` or `None`
970
+ :param c_min: min value for the c constant
971
+ `False`.
972
+ :type verbose: `int`
973
+ :param c_max: min value for the c constant
974
+ `False`.
975
+ :type verbose: `int`
976
+ :param num_group_min: min number of groups
977
+ `False`.
978
+ :type verbose: `int`
979
+ :param num_group_max: min number of groups
980
+ `False`.
981
+ :type verbose: `int`
982
+ :param verbose: flag triggering verbose logging, defaults to
983
+ `False`.
984
+ :type verbose: `bool`
985
+ """
986
+
987
+ self.n = n
988
+ self.epsilon = epsilon
989
+ self.m = m
990
+ self.classifier = classifier
991
+ self.hyperparameters = hyperparameters
992
+ self.threshold_test_size = threshold_test_size
993
+ self.model_selection_method = model_selection_method
994
+ self.scoring = scoring
995
+ self.threshold_evaluate = threshold_evaluate
996
+ self.backup_filter_size = backup_filter_size
997
+ self.random_state = random_state
998
+ self.c_min = c_min
999
+ self.c_max = c_max
1000
+ self.num_group_min = num_group_min
1001
+ self.num_group_max = num_group_max
1002
+ self.verbose = verbose
1003
+
1004
+ def __repr__(self):
1005
+ args = []
1006
+ if self.epsilon != None:
1007
+ args.append(f'epsilon={self.epsilon}')
1008
+ if self.classifier.__repr__() != 'ScoredDecisionTreeClassifier()':
1009
+ args.append(f'classifier={self.classifier}')
1010
+ if self.hyperparameters != {}:
1011
+ args.append(f'hyperparameters={self.hyperparameters}')
1012
+ if (self.model_selection_method.__class__ != StratifiedKFold or
1013
+ self.model_selection_method.n_splits != 5 or
1014
+ self.model_selection_method.shuffle != True):
1015
+ args.append(f'model_selection_method={self.model_selection_method}')
1016
+ if callable(self.scoring):
1017
+ if self.scoring.__name__ != 'auprc_score':
1018
+ args.append(f'scoring={self.scoring.__name__}')
1019
+ else:
1020
+ score_name = args.append(f'scoring="{self.scoring}"')
1021
+ if self.random_state != 4678913:
1022
+ args.append(f'random_state={self.random_state}')
1023
+ if self.c_min != 1.6:
1024
+ args.append(f'c_min={self.c_min}')
1025
+ if self.c_max != 2.5:
1026
+ args.append(f'c_max={self.c_max}')
1027
+ if self.num_group_min != 8:
1028
+ args.append(f'num_group_min={self.num_group_min}')
1029
+ if self.num_group_max != 12:
1030
+ args.append(f'num_group_max={self.num_group_max}')
1031
+ if self.verbose != False:
1032
+ args.append(f'verbose={self.verbose}')
1033
+
1034
+ args = ', '.join(args)
1035
+ return f'AdaBF({args})'
1036
+
1037
+ def fit(self, X, y):
1038
+ """Fits the Adaptive Learned Bloom Filter, training its classifier,
1039
+ setting the score thresholds and building the backup filter.
1040
+
1041
+ :param X: examples to be used for fitting the classifier.
1042
+ :type X: array of numerical arrays
1043
+ :param y: labels of the examples.
1044
+ :type y: array of `bool`
1045
+ :return: the fit Bloom Filter instance.
1046
+ :rtype: :class:`AdaBF`
1047
+ :raises: `ValueError` if X is empty, or if no threshold value is
1048
+ compliant with the false positive rate requirements.
1049
+
1050
+ NOTE: If the classifier variable instance has been specified as an
1051
+ already trained classifier, `X` and `y` are considered as the dataset
1052
+ to be used to build the LBF, that is, setting the threshold for the
1053
+ in output of the classifier, and evaluating the overall empirical FPR.
1054
+ In this case, `X` and `y` are assumed to contain values not used in
1055
+ order to infer the classifier, in order to ensure a fair estimate of
1056
+ FPR. Otherwise, `X` and `y` are meant to be the examples to be used to
1057
+ train the classifier, and subsequently set the threshold and evaluate
1058
+ the empirical FPR.
1059
+ """
1060
+
1061
+ if self.m is None:
1062
+ raise ValueError('The size of the bit array must be specified')
1063
+
1064
+ if len(X) == 0:
1065
+ raise ValueError('Empty set of keys')
1066
+
1067
+ X, y = check_X_y(X, y)
1068
+
1069
+ y = check_y(y)
1070
+
1071
+ if self.random_state is not None:
1072
+ self.model_selection_method.random_state = self.random_state
1073
+
1074
+ X_pos = X[y]
1075
+ self.n = len(X_pos)
1076
+
1077
+ y_pos = y[y]
1078
+
1079
+ try:
1080
+ check_is_fitted(self.classifier)
1081
+ # a trained classifier was passed to the constructor
1082
+ X_neg_threshold_test = X[~y]
1083
+ except NotFittedError:
1084
+ # the classifier has to be trained
1085
+ X_neg = X[~y]
1086
+
1087
+ X_neg_trainval, X_neg_threshold_test = \
1088
+ train_test_split(X_neg,
1089
+ test_size=self.threshold_test_size,
1090
+ random_state=self.random_state)
1091
+ del X_neg
1092
+ gc.collect()
1093
+ y_neg_trainval = [False] * len(X_neg_trainval)
1094
+ X_trainval = np.vstack([X_pos, X_neg_trainval])
1095
+ del X_neg_trainval
1096
+ gc.collect()
1097
+
1098
+ y_trainval = np.hstack([y_pos, y_neg_trainval])
1099
+ del y_neg_trainval
1100
+ gc.collect()
1101
+
1102
+ model = GridSearchCV(estimator=self.classifier,
1103
+ param_grid=self.hyperparameters,
1104
+ cv=self.model_selection_method,
1105
+ scoring=self.scoring,
1106
+ refit=True,
1107
+ n_jobs=-1)
1108
+ model.fit(X_trainval, y_trainval)
1109
+ del X_trainval, y_trainval
1110
+ gc.collect()
1111
+ self.classifier = model.best_estimator_
1112
+
1113
+ c_set = np.arange(self.c_min, self.c_max+10**(-6), 0.1)
1114
+
1115
+ X_neg = X[~y]
1116
+ positive_sample = X[y]
1117
+ negative_sample = X_neg
1118
+
1119
+ nonkey_scores = np.array(self.classifier.predict_score(negative_sample))
1120
+ key_scores = np.array(self.classifier.predict_score(positive_sample))
1121
+
1122
+ FP_opt = len(nonkey_scores)
1123
+
1124
+ k_min = 0
1125
+ for k_max in range(self.num_group_min, self.num_group_max+1):
1126
+ for c in c_set:
1127
+ tau = sum(c ** np.arange(0, k_max - k_min + 1, 1))
1128
+ n = positive_sample.shape[0]
1129
+ bloom_filter = VarhashBloomFilter(self.m, k_max)
1130
+ thresholds = np.zeros(k_max - k_min + 1)
1131
+ thresholds[-1] = 1.1
1132
+ num_negative = sum(nonkey_scores <= thresholds[-1])
1133
+ num_piece = int(num_negative / tau) + 1
1134
+ score = nonkey_scores[nonkey_scores < thresholds[-1]]
1135
+ score = np.sort(score)
1136
+ for k in range(k_min, k_max):
1137
+ i = k - k_min
1138
+ score_1 = score[score < thresholds[-(i + 1)]]
1139
+ if int(num_piece * c ** i) < len(score_1):
1140
+ thresholds[-(i + 2)] = score_1[-int(num_piece * c ** i)]
1141
+ query = positive_sample
1142
+ score = key_scores
1143
+
1144
+ my_count = 0
1145
+
1146
+ for score_s, item_s in zip(score, query):
1147
+ ix = min(np.where(score_s < thresholds)[0])
1148
+ k = k_max - ix
1149
+ if k > 0:
1150
+ my_count += 1
1151
+ bloom_filter.add(item_s, k)
1152
+
1153
+
1154
+ ML_positive = negative_sample[nonkey_scores >= thresholds[-2]]
1155
+ query_negative = negative_sample[nonkey_scores < thresholds[-2]]
1156
+ score_negative = nonkey_scores[nonkey_scores < thresholds[-2]]
1157
+
1158
+ test_result = np.zeros(len(query_negative))
1159
+ ss = 0
1160
+
1161
+ for score_s, item_s in zip(score_negative, query_negative):
1162
+ ix = min(np.where(score_s < thresholds)[0])
1163
+ k = k_max - ix
1164
+ test_result[ss] = bloom_filter.check(item_s, k)
1165
+ ss += 1
1166
+ FP_items = sum(test_result) + len(ML_positive)
1167
+ if self.verbose:
1168
+ print('False positive items: %d (%f), Number of groups: %d, c = %f' %(FP_items, FP_items / len(negative_sample), k_max, round(c, 2)))
1169
+
1170
+ if FP_opt > FP_items:
1171
+ FP_opt = FP_items
1172
+ self.backup_filter_ = bloom_filter
1173
+ self.thresholds_ = thresholds
1174
+ self.num_group_ = k_max
1175
+
1176
+ epsilon = FP_opt / len(negative_sample)
1177
+ if self.epsilon is not None and epsilon > self.epsilon:
1178
+ raise ValueError('No threshold value is feasible.')
1179
+
1180
+ self.is_fitted_ = True
1181
+ self.n_features_in_ = X.shape[1]
1182
+
1183
+ return self
1184
+
1185
+ def predict(self, X):
1186
+ """Computes predictions for a set of queries, each to be checked
1187
+ for inclusion in the Learned Bloom Filter.
1188
+
1189
+ :param X: elements to classify.
1190
+ :type X: array of numerical arrays
1191
+ :return: prediction for each value in 'X'.
1192
+ :rtype: array of `bool`
1193
+ :raises: NotFittedError if the classifier is not fitted.
1194
+
1195
+ NOTE: the implementation assumes that the classifier which is
1196
+ used (either pre-trained or trained in fit) refers to 1 as the
1197
+ label of keys in the Bloom filter
1198
+ """
1199
+ # TODO test that the assumption above is met for all classifiers
1200
+ # that have been tested.
1201
+ # TODO: rework after new classifier classes have been introduced
1202
+
1203
+ check_is_fitted(self, 'is_fitted_')
1204
+ X = check_array(X)
1205
+
1206
+ scores = np.array(self.classifier.predict_score(X))
1207
+
1208
+ predictions = scores > self.thresholds_[-2]
1209
+ negative_sample = X[scores <= self.thresholds_[-2]]
1210
+ negative_scores = scores[scores <= self.thresholds_[-2]]
1211
+
1212
+ ada_predictions = []
1213
+ for key, score in zip(negative_sample, negative_scores):
1214
+ ix = min(np.where(score < self.thresholds_)[0])
1215
+ # thres = thresholds[ix]
1216
+ k = self.num_group_ - ix
1217
+ ada_predictions.append(self.backup_filter_.check(key, k))
1218
+
1219
+ predictions[~predictions] = np.array(ada_predictions)
1220
+ return predictions
1221
+
1222
+ def get_size(self):
1223
+ """Return the Adaptive Learned Bloom Filter size.
1224
+
1225
+ :return: size of the Adaptive Learned Bloom Filter (in bits), detailed
1226
+ w.r.t. the size of the classifier and of the backup filter.
1227
+ :rtype: `dict`
1228
+
1229
+ NOTE: the implementation assumes that the classifier object used to
1230
+ build the Learned Bloom Filter has a get_size method, returning the
1231
+ size of the classifier, measured in bits.
1232
+ """
1233
+
1234
+ check_is_fitted(self, 'is_fitted_')
1235
+
1236
+ return {'backup_filter': self.m,
1237
+ 'classifier': self.classifier.get_size()}
1238
+
1239
+ class PLBF(BaseEstimator, BloomFilter, ClassifierMixin):
1240
+ """Implementation of the Partitioned Learned Bloom Filter"""
1241
+
1242
+ def __init__(self,
1243
+ n=None,
1244
+ epsilon=None,
1245
+ m=None,
1246
+ classifier=ScoredDecisionTreeClassifier(),
1247
+ hyperparameters={},
1248
+ threshold_test_size=0.2,
1249
+ model_selection_method=StratifiedKFold(n_splits=5,
1250
+ shuffle=True),
1251
+ scoring=auprc_score,
1252
+ classical_BF_class=ClassicalBloomFilterImpl,
1253
+ random_state=4678913,
1254
+ num_group_min = 4,
1255
+ num_group_max = 6,
1256
+ N=1000,
1257
+ verbose=False):
1258
+ """Create an instance of :class:`PLBF`.
1259
+
1260
+ :param n: number of keys, defaults to None.
1261
+ :type n: `int`
1262
+ :param epsilon: expected false positive rate, defaults to None.
1263
+ :type epsilon: `float`
1264
+ :param m: dimension in bit of the bitmap, defaults to None.
1265
+ :type m: `int`
1266
+ :param classifier: classifier to be trained, defaults to
1267
+ :class:`DecisionTreeClassifier`.
1268
+ :type classifier:
1269
+ :class:`sklearn.BaseEstimator`
1270
+ :param hyperparameters: grid of values for hyperparameters to be
1271
+ considered during classifier training, defaults to {}.
1272
+ :type hyperparameters: `dict`
1273
+ :param threshold_test_size: relative validation set size used to set
1274
+ the best classifier threshold, defaults to 0.7.
1275
+ :param model_selection_method: strategy to be used for
1276
+ discovering the best hyperparameter values for the learnt
1277
+ classifier, defaults to
1278
+ `StratifiedKFold(n_splits=5, shuffle=True)`.
1279
+ :type model_selection_method:
1280
+ :class:`sklearn.model_selection.BaseShuffleSplit` or
1281
+ :class:`sklearn.model_selection.BaseCrossValidator`
1282
+ :param scoring: method to be used for scoring learnt
1283
+ classifiers, defaults to `auprc`.
1284
+ :type scoring: `str` or function
1285
+ :param classical_BF_class: class of the backup filter, defaults
1286
+ to :class:`ClassicalBloomFilterImpl`.
1287
+ :param random_state: random seed value, defaults to `None`,
1288
+ meaning the current seed value should be kept.
1289
+ :type random_state: `int` or `None`
1290
+ :param num_group_min: min number of groups defaults to 4
1291
+ :type num_group_min: `int`
1292
+ :param num_group_max: max number of groups, defaults to 6
1293
+ :type num_group_max: `int`
1294
+ :param N: number of segments used to discretize the classifier
1295
+ score range, defaults to 1000
1296
+ :type N: `int`
1297
+ :param verbose: flag triggering verbose logging, defaults to `False`.
1298
+ :type verbose: `bool`
1299
+ """
1300
+
1301
+ self.n = n
1302
+ self.epsilon = epsilon
1303
+ self.m = m
1304
+ self.classifier = classifier
1305
+ self.hyperparameters = hyperparameters
1306
+ self.threshold_test_size = threshold_test_size
1307
+ self.model_selection_method = model_selection_method
1308
+ self.scoring = scoring
1309
+ self.threshold_evaluate = threshold_evaluate
1310
+ self.classical_BF_class = classical_BF_class
1311
+ self.random_state = random_state
1312
+ self.num_group_min = num_group_min
1313
+ self.num_group_max = num_group_max
1314
+ self.verbose = verbose
1315
+ self.optim_KL = None
1316
+ self.optim_partition = None
1317
+ self.N = N
1318
+
1319
+ def __repr__(self):
1320
+ args = []
1321
+ if self.epsilon != None:
1322
+ args.append(f'epsilon={self.epsilon}')
1323
+ if self.classifier.__repr__() != 'ScoredDecisionTreeClassifier()':
1324
+ args.append(f'classifier={self.classifier}')
1325
+ if self.hyperparameters != {}:
1326
+ args.append(f'hyperparameters={self.hyperparameters}')
1327
+ if (self.model_selection_method.__class__ != StratifiedKFold or
1328
+ self.model_selection_method.n_splits != 5 or
1329
+ self.model_selection_method.shuffle != True):
1330
+ args.append(f'model_selection_method={self.model_selection_method}')
1331
+ if callable(self.scoring):
1332
+ if self.scoring.__name__ != 'auprc_score':
1333
+ args.append(f'scoring={self.scoring.__name__}')
1334
+ else:
1335
+ score_name = args.append(f'scoring="{self.scoring}"')
1336
+ if self.random_state != 4678913:
1337
+ args.append(f'random_state={self.random_state}')
1338
+ if self.num_group_min != 4:
1339
+ args.append(f'num_group_min={self.num_group_min}')
1340
+ if self.num_group_max != 6:
1341
+ args.append(f'num_group_max={self.num_group_max}')
1342
+ if self.N != 1000:
1343
+ args.append(f'N={self.N}')
1344
+ if self.verbose != False:
1345
+ args.append(f'verbose={self.verbose}')
1346
+
1347
+ args = ', '.join(args)
1348
+ return f'PLBF({args})'
1349
+
1350
+ def fit(self, X, y):
1351
+ """Fits the Partitioned Bloom Filter, training its classifier,
1352
+ setting the score thresholds and building the backup filter.
1353
+
1354
+ :param X: examples to be used for fitting the classifier.
1355
+ :type X: array of numerical arrays
1356
+ :param y: labels of the examples.
1357
+ :type y: array of `bool`
1358
+ :return: the fit Bloom Filter instance.
1359
+ :rtype: :class:`AdaBF`
1360
+ :raises: `ValueError` if X is empty, or if no threshold value is
1361
+ compliant with the false positive rate requirements.
1362
+
1363
+ NOTE: If the classifier variable instance has been specified as an
1364
+ already trained classifier, `X` and `y` are considered as the dataset
1365
+ to be used to build the LBF, that is, setting the threshold for the
1366
+ in output of the classifier, and evaluating the overall empirical FPR.
1367
+ In this case, `X` and `y` are assumed to contain values not used in
1368
+ order to infer the classifier, in order to ensure a fair estimate of
1369
+ FPR. Otherwise, `X` and `y` are meant to be the examples to be used to
1370
+ train the classifier, and subsequently set the threshold and evaluate
1371
+ the empirical FPR.
1372
+ """
1373
+
1374
+ if len(X) == 0:
1375
+ raise ValueError('Empty set of keys')
1376
+
1377
+ if self.m is None and self.epsilon is None:
1378
+ raise ValueError("At least one parameter \
1379
+ between m and epsilon must be specified.")
1380
+
1381
+ X, y = check_X_y(X, y)
1382
+
1383
+ y = check_y(y)
1384
+
1385
+ if self.random_state is not None:
1386
+ self.model_selection_method.random_state = self.random_state
1387
+
1388
+ X_pos = X[y]
1389
+ self.n = len(X_pos)
1390
+
1391
+ y_pos = y[y]
1392
+
1393
+ try:
1394
+ check_is_fitted(self.classifier)
1395
+ X_neg_threshold_test = X[~y]
1396
+ except NotFittedError:
1397
+ X_neg = X[~y]
1398
+
1399
+ X_neg_trainval, X_neg_threshold_test = \
1400
+ train_test_split(X_neg,
1401
+ test_size=self.threshold_test_size,
1402
+ random_state=self.random_state)
1403
+ del X_neg
1404
+ gc.collect()
1405
+ y_neg_trainval = [False] * len(X_neg_trainval)
1406
+ X_trainval = np.vstack([X_pos, X_neg_trainval])
1407
+ del X_neg_trainval
1408
+ gc.collect()
1409
+
1410
+ y_trainval = np.hstack([y_pos, y_neg_trainval])
1411
+ del y_neg_trainval
1412
+ gc.collect()
1413
+
1414
+ model = GridSearchCV(estimator=self.classifier,
1415
+ param_grid=self.hyperparameters,
1416
+ cv=self.model_selection_method,
1417
+ scoring=self.scoring,
1418
+ refit=True,
1419
+ n_jobs=-1)
1420
+ model.fit(X_trainval, y_trainval)
1421
+ del X_trainval, y_trainval
1422
+ gc.collect()
1423
+ self.classifier = model.best_estimator_
1424
+
1425
+ X_neg = X[~y]
1426
+ X_pos = X[y]
1427
+
1428
+ nonkey_scores = np.array(self.classifier.predict_score(X_neg_threshold_test))
1429
+ key_scores = np.array(self.classifier.predict_score(X_pos))
1430
+ FP_opt = len(nonkey_scores)
1431
+
1432
+ interval = 1/self.N
1433
+ min_score = min(np.min(key_scores), np.min(nonkey_scores))
1434
+ max_score = min(np.max(key_scores), np.max(nonkey_scores))
1435
+
1436
+ score_partition = np.arange(min_score-10**(-10),max_score+10**(-10)+interval,interval)
1437
+
1438
+ h = [np.sum((score_low<=nonkey_scores) & (nonkey_scores<score_up)) for score_low, score_up in zip(score_partition[:-1], score_partition[1:])]
1439
+ h = np.array(h)
1440
+
1441
+ ## Merge the interval with less than 5 nonkey
1442
+ delete_ix = []
1443
+ for i in range(len(h)):
1444
+ if h[i] < 1:
1445
+ delete_ix += [i]
1446
+ score_partition = np.delete(score_partition, [i for i in delete_ix])
1447
+
1448
+ h = [np.sum((score_low<=nonkey_scores) & (nonkey_scores<score_up)) for score_low, score_up in zip(score_partition[:-1], score_partition[1:])]
1449
+ h = np.array(h)
1450
+ g = [np.sum((score_low<=key_scores) & (key_scores<score_up)) for score_low, score_up in zip(score_partition[:-1], score_partition[1:])]
1451
+ g = np.array(g)
1452
+
1453
+ delete_ix = []
1454
+ for i in range(len(g)):
1455
+ if g[i] < 1:
1456
+ delete_ix += [i]
1457
+ score_partition = np.delete(score_partition, [i for i in delete_ix])
1458
+
1459
+ ## Find the counts in each interval
1460
+ h = [np.sum((score_low<=nonkey_scores) & (nonkey_scores<score_up)) for score_low, score_up in zip(score_partition[:-1], score_partition[1:])]
1461
+ h = np.array(h) / sum(h)
1462
+ g = [np.sum((score_low<=key_scores) & (key_scores<score_up)) for score_low, score_up in zip(score_partition[:-1], score_partition[1:])]
1463
+ g = np.array(g) / sum(g)
1464
+
1465
+ n = len(score_partition)
1466
+ if self.optim_KL is None and self.optim_partition is None:
1467
+
1468
+ optim_KL = np.zeros((n, self.num_group_max))
1469
+ optim_partition = [[0]*self.num_group_max for _ in range(n)]
1470
+
1471
+ for i in range(n):
1472
+ optim_KL[i,0] = np.sum(g[:(i+1)]) * np.log2(sum(g[:(i+1)])/sum(h[:(i+1)]))
1473
+ optim_partition[i][0] = [i]
1474
+
1475
+ for j in range(1,self.num_group_max):
1476
+ for m in range(j,n):
1477
+ candidate_par = np.array([optim_KL[i][j-1]+np.sum(g[i:(m+1)])* \
1478
+ np.log2(np.sum(g[i:(m+1)])/np.sum(h[i:(m+1)])) for i in range(j-1,m)])
1479
+ optim_KL[m][j] = np.max(candidate_par)
1480
+ ix = np.where(candidate_par == np.max(candidate_par))[0][0] + (j-1)
1481
+ if j > 1:
1482
+ optim_partition[m][j] = optim_partition[ix][j-1] + [ix]
1483
+ else:
1484
+ optim_partition[m][j] = [ix]
1485
+
1486
+ self.optim_KL = optim_KL
1487
+ self.optim_partition = optim_partition
1488
+
1489
+ if self.m != None:
1490
+
1491
+ FP_opt = len(nonkey_scores)
1492
+
1493
+ for num_group in range(self.num_group_min, self.num_group_max+1):
1494
+ ### Determine the thresholds
1495
+ thresholds = np.zeros(num_group + 1)
1496
+ thresholds[0] = -0.00001
1497
+ thresholds[-1] = 1.00001
1498
+ inter_thresholds_ix = self.optim_partition[-1][num_group-1]
1499
+ inter_thresholds = score_partition[inter_thresholds_ix]
1500
+ thresholds[1:-1] = inter_thresholds
1501
+
1502
+
1503
+ ### Count the keys of each group
1504
+ count_nonkey = np.zeros(num_group)
1505
+ count_key = np.zeros(num_group)
1506
+
1507
+ query_group = []
1508
+ for j in range(num_group):
1509
+ count_nonkey[j] = sum((nonkey_scores >= thresholds[j]) & (nonkey_scores < thresholds[j + 1]))
1510
+ count_key[j] = sum((key_scores >= thresholds[j]) & (key_scores < thresholds[j + 1]))
1511
+
1512
+ query_group.append(X_pos[(key_scores >= thresholds[j]) & (key_scores < thresholds[j + 1])])
1513
+
1514
+
1515
+ R = np.zeros(num_group)
1516
+
1517
+ alpha = 0.5 ** np.log(2)
1518
+ c = self.m / self.n + (-self.optim_KL[-1][num_group-1] / np.log2(alpha))
1519
+
1520
+ for j in range(num_group):
1521
+ g_j = count_key[j] / self.n
1522
+ h_j = count_nonkey[j] / len(X_neg_threshold_test)
1523
+
1524
+ R_j = count_key[j] * (np.log2(g_j/h_j)/np.log(alpha) + c)
1525
+ R[j] = max(1, R_j)
1526
+
1527
+ #We need to fix the sizes to use all the available space
1528
+ pos_sizes_mask = R > 0
1529
+ used_bits = R[pos_sizes_mask].sum()
1530
+ relative_sizes = R[pos_sizes_mask] / used_bits
1531
+ extra_bits = self.m - used_bits
1532
+
1533
+ extra_sizes = relative_sizes * extra_bits
1534
+ R[pos_sizes_mask] += extra_sizes
1535
+
1536
+ for j in range(len(R)):
1537
+ R[j] = max(1, R[j])
1538
+
1539
+ backup_filters = []
1540
+ for j in range(num_group):
1541
+ if count_key[j]==0:
1542
+ backup_filters.append(None)
1543
+ else:
1544
+ backup_filters.append( \
1545
+ ClassicalBloomFilter(filter_class=self.classical_BF_class,
1546
+ n=count_key[j],
1547
+ m=R[j]))
1548
+ for item in query_group[j]:
1549
+ backup_filters[j].add(item)
1550
+
1551
+ FP_items = 0
1552
+ for score, item in zip(nonkey_scores, X_neg_threshold_test):
1553
+ ix = min(np.where(score < thresholds)[0]) - 1
1554
+ if backup_filters[ix] is not None:
1555
+ FP_items += int(backup_filters[ix].check(item))
1556
+
1557
+ FPR = FP_items/len(X_neg_threshold_test)
1558
+
1559
+ if FP_opt > FP_items:
1560
+ num_group_opt = num_group
1561
+ FP_opt = FP_items
1562
+ backup_filters_opt = backup_filters
1563
+ thresholds_opt = thresholds
1564
+ if self.verbose:
1565
+ print('False positive items: {}, FPR: {} Number of groups: {}'.format(FP_items, FPR, num_group))
1566
+ print("optimal thresholds: ", thresholds_opt)
1567
+
1568
+ elif self.epsilon != None:
1569
+
1570
+ m_optimal = np.inf
1571
+
1572
+ for num_group in range(self.num_group_min, self.num_group_max+1):
1573
+
1574
+ ### Determine the thresholds
1575
+ thresholds = np.zeros(num_group + 1)
1576
+ thresholds[0] = -0.00001
1577
+ thresholds[-1] = 1.00001
1578
+ inter_thresholds_ix = self.optim_partition[-1][num_group-1]
1579
+ inter_thresholds = score_partition[inter_thresholds_ix]
1580
+ thresholds[1:-1] = inter_thresholds
1581
+
1582
+
1583
+ ### Count the keys of each group
1584
+ count_nonkey = np.zeros(num_group)
1585
+ count_key = np.zeros(num_group)
1586
+
1587
+ query_group = []
1588
+ for j in range(num_group):
1589
+ count_nonkey[j] = sum((nonkey_scores >= thresholds[j]) & \
1590
+ (nonkey_scores < thresholds[j + 1]))
1591
+ count_key[j] = sum((key_scores >= thresholds[j]) & \
1592
+ (key_scores < thresholds[j + 1]))
1593
+ query_group.append(X_pos[(key_scores >= thresholds[j]) & \
1594
+ (key_scores < thresholds[j + 1])])
1595
+ g_sum = 0
1596
+ h_sum = 0
1597
+
1598
+ f = np.zeros(num_group)
1599
+
1600
+ for i in range(num_group):
1601
+ f[i] = self.epsilon * (count_key[i]/sum(count_key)) / \
1602
+ (count_nonkey[i]/sum(count_nonkey))
1603
+
1604
+ while sum(f > 1) > 0:
1605
+ for i in range(num_group):
1606
+ f[i] = min(1, f[i])
1607
+
1608
+ g_sum = 0
1609
+ h_sum = 0
1610
+
1611
+ for i in range(num_group):
1612
+ if f[i] == 1:
1613
+ g_sum += count_key[i] / np.sum(count_key)
1614
+ h_sum += count_nonkey[i] / np.sum(count_nonkey)
1615
+
1616
+ for i in range(num_group):
1617
+ if f[i] < 1:
1618
+
1619
+ g_i = count_key[i]/sum(count_key)
1620
+ h_i = count_nonkey[i]/sum(count_nonkey)
1621
+ f[i] = g_i*(self.epsilon-h_sum) / (h_i*(1-g_sum))
1622
+
1623
+ m = 0
1624
+ for i in range(num_group):
1625
+ if f[i] < 1:
1626
+ m += -count_key[i] * np.log(f[i]) / np.log(2)**2
1627
+ if m < m_optimal:
1628
+ m_optimal = m
1629
+ f_optimal = f
1630
+ num_group_opt = num_group
1631
+ thresholds_opt = thresholds
1632
+
1633
+
1634
+ count_nonkey = np.zeros(num_group_opt)
1635
+ count_key = np.zeros(num_group_opt)
1636
+ query_group = []
1637
+ for j in range(num_group_opt):
1638
+ count_nonkey[j] = sum((nonkey_scores >= thresholds[j]) & \
1639
+ (nonkey_scores < thresholds[j + 1]))
1640
+ count_key[j] = sum((key_scores >= thresholds[j]) & \
1641
+ (key_scores < thresholds[j + 1]))
1642
+ query_group.append(X_pos[(key_scores >= thresholds[j]) & \
1643
+ (key_scores < thresholds[j + 1])])
1644
+
1645
+ backup_filters_opt = []
1646
+ for i in range(num_group_opt):
1647
+ if f_optimal[i] < 1:
1648
+ bf = ClassicalBloomFilter(filter_class=self.classical_BF_class,
1649
+ n=count_key[i],
1650
+ epsilon=f[i])
1651
+ for key in query_group[i]:
1652
+ bf.add(key)
1653
+ backup_filters_opt.append(bf)
1654
+ else:
1655
+ backup_filters_opt.append(None)
1656
+
1657
+ self.num_groups = num_group_opt
1658
+ self.thresholds_ = thresholds_opt
1659
+ self.backup_filters_ = backup_filters_opt
1660
+ self.is_fitted_ = True
1661
+ self.n_features_in_ = X.shape[1]
1662
+
1663
+ return self
1664
+
1665
+ def predict(self, X):
1666
+ """Computes predictions for a set of queries, each to be checked
1667
+ for inclusion in the Learned Bloom Filter.
1668
+
1669
+ :param X: elements to classify.
1670
+ :type X: array of numerical arrays
1671
+ :return: prediction for each value in 'X'.
1672
+ :rtype: array of `bool`
1673
+ :raises: NotFittedError if the classifier is not fitted.
1674
+
1675
+ NOTE: the implementation assumes that the classifier which is
1676
+ used (either pre-trained or trained in fit) refers to 1 as the
1677
+ label of keys in the Bloom filter
1678
+ """
1679
+ # TODO test that the assumption above is met for all classifiers
1680
+ # that have been tested.
1681
+ # TODO: rework after new classifier classes have been introduced
1682
+
1683
+ check_is_fitted(self, 'is_fitted_')
1684
+ X = check_array(X)
1685
+
1686
+ scores = np.array(self.classifier.predict_score(X))
1687
+
1688
+ counts = [0] * self.num_groups
1689
+
1690
+ for j in range(self.num_groups):
1691
+ counts[j] = sum((scores >= self.thresholds_[j]) & (scores < self.thresholds_[j + 1]))
1692
+
1693
+ # predictions = scores > self.__thresholds[-1]
1694
+ # negative_sample = X[scores <= self.__thresholds[-1]]
1695
+ # negative_scores = scores[scores <= self.__thresholds[-1]]
1696
+
1697
+ predictions = []
1698
+ for score, item in zip(scores, X):
1699
+ ix = min(np.where(score < self.thresholds_)[0]) - 1
1700
+
1701
+ if self.backup_filters_[ix] is None:
1702
+ predictions.append(True)
1703
+ else:
1704
+ predictions.append(self.backup_filters_[ix].check(item))
1705
+
1706
+ return np.array(predictions)
1707
+
1708
+ def get_size(self):
1709
+ """Return the Partitioned Learned Bloom Filter size.
1710
+
1711
+ :return: size of the Partitioned Learned Bloom Filter (in bits), detailed
1712
+ w.r.t. the size of the classifier and of the backup filters.
1713
+ :rtype: `dict`
1714
+
1715
+ NOTE: the implementation assumes that the classifier object used to
1716
+ build the Learned Bloom Filter has a get_size method, returning the
1717
+ size of the classifier, measured in bits.
1718
+ """
1719
+
1720
+ check_is_fitted(self, 'is_fitted_')
1721
+
1722
+ return {'backup_filters': sum([bf.m for bf in self.backup_filters_ if bf is not None]),
1723
+ 'classifier': self.classifier.get_size()}
1724
+