Debian Codegraph @

apricot/optimizers.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # optimizers.py
2 # Author: Jacob Schreiber <[email protected]>
3
4 import os
5 import copy
6 import numpy
7 import scipy
8
9 from tqdm import tqdm
10
11 from .utils import PriorityQueue
12 from .utils import check_random_state
13 from .utils import _calculate_pairwise_distances
14
15 class BaseOptimizer(object):
16 """An approach for optimizing submodular functions.
17
18 This object contains a single method, `select`, that implements an
19 algorithm for optimizing submodular functions. This method will take in the
20 data set, the number of examples to select, and a stored reference to the
21 submodular function to be optimized, and yield a subset of examples. The
22 method operates on the gains provided in the `_calculate_gains` method from
23 the submodular function object and stores examples using the `_select_next`
24 method.
25
26 Parameters
27 ----------
28 function : base.BaseSelection
29 A submodular function that implements the `_calculate_gains` and
30 `_select_next` methods. This is the function that will be
31 optimized.
32
33 verbose : bool
34 Whether to display a progress bar during the optimization process.
35
36
37 Attributes
38 ----------
39 self.function : base.BaseSelection or None
40 A submodular function that implements the `_calculate_gains` and
41 `_select_next` methods. This is the function that will be
42 optimized. If None, will be set by the selector when passed in.
43
44 self.verbose : bool
45 Whether to display a progress bar during the optimization process.
46 """
47
48 def __init__(self, function=None, random_state=None, n_jobs=None,
49 verbose=False):
50 self.function = function
51 self.random_state = check_random_state(random_state)
52 self.n_jobs = n_jobs
53 self.verbose = verbose
54 self.gains_ = None
55
56 def select(self, X, k):
57 raise NotImplementedError
58
59
60 class NaiveGreedy(BaseOptimizer):
61 """The naive greedy algorithm for optimization.
62
63 The naive greedy algorithm is the simplest greedy approach for optimizing
64 submodular functions. The approach simply iterates through each example in
65 the ground set that has not already been selected and calculates the gain
66 in function value that would result from adding that example to the
67 selected set. This process is embarassingly parallel and so is extremely
68 amenable both to parallel processing and distributed computing. Further,
69 because it is conceptually simple, it is also simple to implement.
70
71 The naive greedy algorithm can be specified for any function by passing in
72 `optimizer='naive'` to the relevant selector object. Here is an example of
73 specifying the naive greedy algorithm for optimizing a feature-based function.
74
75 .. code::python
76
77 from apricot import FeatureBasedSelection
78
79 X = numpy.random.randint(10, size=(10000, 100))
80
81 selector = FeatureBasedSelection(100, 'sqrt', optimizer='naive')
82 selector.fit(X)
83
84 Parameters
85 ----------
86 self.function : base.BaseSelection
87 A submodular function that implements the `_calculate_gains` and
88 `_select_next` methods. This is the function that will be
89 optimized.
90
91 self.verbose : bool
92 Whether to display a progress bar during the optimization process.
93
94
95 Attributes
96 ----------
97 self.function : base.BaseSelection
98 A submodular function that implements the `_calculate_gains` and
99 `_select_next` methods. This is the function that will be
100 optimized.
101
102 self.verbose : bool
103 Whether to display a progress bar during the optimization process.
104
105 self.gains_ : numpy.ndarray or None
106 The gain that each example would give the last time that it was
107 evaluated.
108 """
109
110 def __init__(self, function=None, random_state=None, n_jobs=None,
111 verbose=False):
112 super(NaiveGreedy, self).__init__(function=function,
113 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
114
115 def select(self, X, k, sample_cost=None):
116 cost = 0.0
117 while cost < k:
118 gains = self.function._calculate_gains(X)
119
120 if sample_cost is None:
121 idx = numpy.argmax(gains)
122 best_idx = self.function.idxs[idx]
123 idx_cost = 1
124 else:
125 idxs = numpy.lexsort((numpy.arange(gains.shape[0]), -gains / sample_cost[self.function.idxs]))
126 for idx in idxs:
127 best_idx = self.function.idxs[idx]
128 idx_cost = sample_cost[best_idx]
129 if cost + idx_cost <= k:
130 break
131 else:
132 break
133
134 cost += idx_cost
135 gain = gains[idx]
136 self.function._select_next(X[best_idx], gain, best_idx)
137
138 if self.verbose == True:
139 self.function.pbar.update(round(idx_cost, 1))
140
141
142 class LazyGreedy(BaseOptimizer):
143 """The lazy/accelerated greedy algorithm for optimization.
144
145 The lazy (or accelerated) greedy algorithm is a fast alternate to the
146 naive greedy algorithm that results in the same items being selected.
147 This algorithm exploits the diminishing returns property of submodular
148 functions in order to avoid re-evaluating examples that are known to
149 provide little gain. If an example has a small gain relative to other
150 examples, it is unlikely to be the next selected example because that
151 gain can only go down as more items are selected. Thus, the example
152 should only be re-evaluated once the gains of other examples have gotten
153 smaller.
154
155 The key idea of the lazy greedy algorithm is to maintain a priority queue
156 where the examples are the elements in the queue and the priorities are
157 the gains the last time they were evaluated. The algorithm has two steps.
158 The first step is to calculate the gain that each example would have if
159 selected first (the modular upper bound) and populate the priority queue
160 using these values. The second step is to recalculate the gain of the
161 first example in the priority queue and then add the example back into
162 the queue. If the example remains at the front of the queue it is selected
163 because no other example could have a larger gain once re-evaluated (due
164 to the diminishing returns property).
165
166 While the worst case time complexity of this algorithm is the same as the
167 naive greedy algorithm, in practice it can be orders of magnitude faster.
168 Empirically, it appears to accelerate graph-based functions much more
169 than it does feature-based ones. Functions also seem to be more
170 accelerated the more curved they are.
171
172 .. code::python
173
174 from apricot import FeatureBasedSelection
175
176 X = numpy.random.randint(10, size=(10000, 100))
177
178 selector = FeatureBasedSelection(100, 'sqrt', optimizer='lazy')
179 selector.fit(X)
180
181 Parameters
182 ----------
183 self.function : base.BaseSelection
184 A submodular function that implements the `_calculate_gains` and
185 `_select_next` methods. This is the function that will be
186 optimized.
187
188 self.verbose : bool
189 Whether to display a progress bar during the optimization process.
190
191
192 Attributes
193 ----------
194 self.function : base.BaseSelection
195 A submodular function that implements the `_calculate_gains` and
196 `_select_next` methods. This is the function that will be
197 optimized.
198
199 self.verbose : bool
200 Whether to display a progress bar during the optimization process.
201
202 self.pq : utils.PriorityQueue
203 The priority queue used to order examples for evaluation.
204
205 self.gains_ : numpy.ndarray or None
206 The gain that each example would give the last time that it was
207 evaluated.
208 """
209
210 def __init__(self, function=None, random_state=None, n_jobs=None,
211 verbose=False):
212 super(LazyGreedy, self).__init__(function=function,
213 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
214
215 def select(self, X, k, sample_cost=None):
216 cost = 0.0
217 if sample_cost is None:
218 sample_cost = numpy.ones(X.shape[0], dtype='float64')
219
220 gains = self.function._calculate_gains(X) / sample_cost[self.function.idxs]
221 self.pq = PriorityQueue(self.function.idxs, -gains)
222
223 while cost < k:
224 best_gain = float("-inf")
225 best_idx = None
226
227 while True:
228 if len(self.pq.pq) == 0:
229 return
230
231 prev_gain, idx = self.pq.pop()
232 #prev_gain, idx = self.pq.peek()
233 prev_gain = -prev_gain
234
235 if cost + sample_cost[idx] > k:
236 continue
237
238 if best_idx == idx:
239 break
240
241 idxs = numpy.array([idx])
242 gain = self.function._calculate_gains(X, idxs)[0] / sample_cost[idx]
243
244 #self.pq.swap(idx, -gain)
245 self.pq.add(idx, -gain)
246
247 if gain > best_gain:
248 best_gain = gain
249 best_idx = idx
250 elif gain == best_gain and best_gain == 0.0:
251 best_gain = gain
252 best_idx = idx
253 break
254
255 cost += sample_cost[best_idx]
256 best_gain *= sample_cost[best_idx]
257 self.function._select_next(X[best_idx], best_gain, best_idx)
258
259 if self.verbose == True:
260 self.function.pbar.update(1)
261
262 class ApproximateLazyGreedy(BaseOptimizer):
263 """The approximate lazy/accelerated greedy algorithm for optimization.
264
265 The approximate lazy greedy algorithm is a simple extension of the lazy
266 greedy algorithm that, rather than requiring that an element remains at
267 the top of the priority queue after being re-evaluated, only requires
268 that the gain is within a certain user-defined percentage of the best
269 gain to be selected. The key point in this approach is that finding the
270 very best element while maintaining the priority queue may be expensive,
271 but finding elements that are good enough is simple. While the best
272 percentage to use is data set specific, even values near 1 can lead to
273 large savings in computation.
274
275 .. code::python
276
277 from apricot import FeatureBasedSelection
278
279 X = numpy.random.randint(10, size=(10000, 100))
280
281 selector = FeatureBasedSelection(100, 'sqrt', optimizer='approximate-lazy')
282 selector.fit(X)
283
284 Parameters
285 ----------
286 self.function : base.BaseSelection
287 A submodular function that implements the `_calculate_gains` and
288 `_select_next` methods. This is the function that will be
289 optimized.
290
291 self.verbose : bool
292 Whether to display a progress bar during the optimization process.
293
294
295 Attributes
296 ----------
297 self.function : base.BaseSelection
298 A submodular function that implements the `_calculate_gains` and
299 `_select_next` methods. This is the function that will be
300 optimized.
301
302 self.verbose : bool
303 Whether to display a progress bar during the optimization process.
304
305 self.pq : utils.PriorityQueue
306 The priority queue used to order examples for evaluation.
307
308 self.gains_ : numpy.ndarray or None
309 The gain that each example would give the last time that it was
310 evaluated.
311 """
312
313 def __init__(self, function=None, beta=0.9, random_state=None,
314 n_jobs=None, verbose=False):
315 self.beta = beta
316 super(ApproximateLazyGreedy, self).__init__(function=function,
317 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
318
319 def select(self, X, k, sample_cost=None):
320 cost = 0.0
321 if sample_cost is None:
322 sample_cost = numpy.ones(X.shape[0], dtype='float64')
323
324 gains = self.function._calculate_gains(X) / sample_cost[self.function.idxs]
325 self.pq = PriorityQueue(self.function.idxs, -gains)
326
327 while cost < k:
328 while True:
329 if len(self.pq.pq) == 0:
330 return
331
332 prev_gain, idx = self.pq.pop()
333 prev_gain = -prev_gain
334
335 if cost + sample_cost[idx] > k:
336 continue
337
338 idxs = numpy.array([idx])
339 gain = self.function._calculate_gains(X, idxs)[0] / sample_cost[idx]
340
341 if gain >= self.beta * prev_gain:
342 best_gain = gain
343 best_idx = idx
344 break
345 else:
346 self.pq.add(idx, -gain)
347
348
349 cost += sample_cost[best_idx]
350 best_gain *= sample_cost[best_idx]
351 self.function._select_next(X[best_idx], best_gain, best_idx)
352
353 if self.verbose == True:
354 self.function.pbar.update(1)
355
356
357 class TwoStageGreedy(BaseOptimizer):
358 """An approach that switches between two optimizers midway through.
359
360 The two-stage greedy optimizer is a general purpose framework for combining
361 two optimizers by making the first :math:`n` selections out of :math:`k`
362 total selections using one optimizer, and then making the remainder using
363 the other. When the first optimizer is random selection and the second
364 approach is naive/lazy greedy, this becomes partial enumeration. By
365 default, the first algorithm is the naive greedy optimizer and the second
366 algorithm is the lazy greedy. This combination results in the same
367 selection as either optimizer individually but replaces the
368 computationally intensive first few steps for the priority queue, where
369 the algorithm may require scanning through almost the entire queue, with
370 the parallelizable naive greedy algorithm. While, in theory, the lazy
371 greedy algorithm will never perform more function calls than the naive
372 greedy algorithm, there are costs associated both with maintaining a
373 priority queue and with evaluating a single example instead of a batch
374 of examples.
375
376 This optimizer, with the naive greedy optimizer first and the lazy greedy
377 optimizer second, is the default optimizer for apricot selectors.
378
379 .. code::python
380
381 from apricot import FeatureBasedSelection
382
383 X = numpy.random.randint(10, size=(10000, 100))
384
385 selector = FeatureBasedSelection(100, 'sqrt', optimizer='two-stage')
386 selector.fit(X)
387
388 Parameters
389 ----------
390 self.function : base.BaseSelection
391 A submodular function that implements the `_calculate_gains` and
392 `_select_next` methods. This is the function that will be
393 optimized.
394
395 self.n_first_selections : int
396 The number of selections to perform using the naive greedy algorithm
397 before populating the priority queue and using the lazy greedy
398 algorithm.
399
400 self.verbose : bool
401 Whether to display a progress bar during the optimization process.
402
403
404 Attributes
405 ----------
406 self.function : base.BaseSelection
407 A submodular function that implements the `_calculate_gains` and
408 `_select_next` methods. This is the function that will be
409 optimized.
410
411 self.verbose : bool
412 Whether to display a progress bar during the optimization process.
413 """
414
415 def __init__(self, function=None, n_first_selections=10,
416 optimizer1='naive', optimizer2='lazy', random_state=None,
417 n_jobs=None, verbose=False):
418 self.n_first_selections = n_first_selections
419 self.optimizer1 = optimizer1
420 self.optimizer2 = optimizer2
421 super(TwoStageGreedy, self).__init__(function=function,
422 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
423
424 def select(self, X, k, sample_cost=None):
425 if isinstance(self.optimizer1, str):
426 optimizer1 = OPTIMIZERS[self.optimizer1](function=self.function,
427 verbose=self.verbose)
428 elif not isinstance(self.optimizer1, BaseOptimizer):
429 raise ValueError("optimizer1 must be either a string or an " /
430 "optimized object.")
431 else:
432 optimizer1 = self.optimizer1
433
434 if isinstance(self.optimizer2, str):
435 optimizer2 = OPTIMIZERS[self.optimizer2](function=self.function,
436 verbose=self.verbose)
437 elif not isinstance(self.optimizer2, BaseOptimizer):
438 raise ValueError("optimizer1 must be either a string or an " /
439 "optimized object.")
440 else:
441 optimizer2 = self.optimizer2
442
443 optimizer1.select(X, min(self.n_first_selections, k), sample_cost=sample_cost)
444 if k > self.n_first_selections:
445 m = k - self.n_first_selections
446 optimizer2.select(X, m, sample_cost=sample_cost)
447
448
449 class StochasticGreedy(BaseOptimizer):
450 """The stochastic greedy algorithm for optimization.
451
452 The stochastic greedy algorithm is a simple approach that, for each
453 iteration, randomly selects a subset of data and then finds the best next
454 example within that subset. The distinction between this approach and the
455 sample greedy algorithm is that this subset changes at each iteration,
456 meaning that the algorithm does cover the entire data set. In contrast,
457 the sample greedy algorithm is equivalent to manually subsampling the data
458 before running a selector on it. The size of this subset is proportional
459 to the number of examples that are chosen and determined in a manner that
460 results in the same amount of computation being done no matter how many
461 elements are selected. A key idea from this approach is that, while the
462 exact ranking of the elements may differ from the naive/lazy greedy
463 approaches, the set of selected elements is likely to be similar despite
464 the limited amount of computation.
465
466 .. code::python
467
468 from apricot import FeatureBasedSelection
469
470 X = numpy.random.randint(10, size=(10000, 100))
471
472 selector = FeatureBasedSelection(100, 'sqrt', optimizer='stochastic')
473 selector.fit(X)
474
475 Parameters
476 ----------
477 self.function : base.BaseSelection
478 A submodular function that implements the `_calculate_gains` and
479 `_select_next` methods. This is the function that will be
480 optimized.
481
482 epsilon : float, optional
483 The inverse of the sampling probability of any particular point being
484 included in the subset, such that 1 - epsilon is the probability that
485 a point is included. Default is 0.9.
486
487 random_state : int or RandomState or None, optional
488 The random seed to use for the random selection process.
489
490 self.verbose : bool
491 Whether to display a progress bar during the optimization process.
492
493
494 Attributes
495 ----------
496 self.function : base.BaseSelection
497 A submodular function that implements the `_calculate_gains` and
498 `_select_next` methods. This is the function that will be
499 optimized.
500
501 self.verbose : bool
502 Whether to display a progress bar during the optimization process.
503
504 self.gains_ : numpy.ndarray or None
505 The gain that each example would give the last time that it was
506 evaluated.
507 """
508
509 def __init__(self, function=None, epsilon=0.9, random_state=None,
510 n_jobs=None, verbose=False):
511 self.epsilon = epsilon
512 super(StochasticGreedy, self).__init__(function=function,
513 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
514
515 def select(self, X, k, sample_cost=None):
516 cost = 0.0
517 if sample_cost is None:
518 sample_cost = numpy.ones(X.shape[0], dtype='float64')
519
520 n = X.shape[0]
521 subset_size = -numpy.log(self.epsilon) * n / k
522 subset_size = max(int(subset_size), 1)
523
524 while cost < k:
525 idxs = self.random_state.choice(self.function.idxs,
526 replace=False, size=min(subset_size,
527 self.function.idxs.shape[0]))
528
529 gains = self.function._calculate_gains(X, idxs) / sample_cost[idxs]
530 idxs_ = numpy.lexsort((numpy.arange(gains.shape[0]), -gains))
531
532 for idx in idxs_:
533 best_idx = idxs[idx]
534 if cost + sample_cost[best_idx] <= k:
535 break
536 else:
537 return
538
539 cost += sample_cost[best_idx]
540 self.function._select_next(X[best_idx], gains[idx], best_idx)
541
542 if self.verbose == True:
543 self.function.pbar.update(1)
544
545
546 class SampleGreedy(BaseOptimizer):
547 """The sample greedy algorithm for optimization.
548
549 The sample greedy algorithm is a simple approach that subsamples the full
550 data set with a user-defined sampling probability and then runs an
551 optimization on that subset. This subsampling can lead to obvious speed
552 improvements because fewer elements as selected, but will generally find
553 a lower quality subset because fewer elements are present. This approach
554 is typically used a baseline for other approaches but can save a lot of
555 time on massive data sets that are known to be highly redundant.
556
557 .. code::python
558
559 from apricot import FeatureBasedSelection
560
561 X = numpy.random.randint(10, size=(10000, 100))
562
563 selector = FeatureBasedSelection(100, 'sqrt', optimizer='sample')
564 selector.fit(X)
565
566 Parameters
567 ----------
568 self.function : base.BaseSelection
569 A submodular function that implements the `_calculate_gains` and
570 `_select_next` methods. This is the function that will be
571 optimized.
572
573 epsilon : float, optional
574 The sampling probability to use when constructing the subset. A
575 subset of size n * epsilon will be selected from.
576
577 random_state : int or RandomState or None, optional
578 The random seed to use for the random selection process.
579
580 self.verbose : bool
581 Whether to display a progress bar during the optimization process.
582
583
584 Attributes
585 ----------
586 self.function : base.BaseSelection
587 A submodular function that implements the `_calculate_gains` and
588 `_select_next` methods. This is the function that will be
589 optimized.
590
591 self.verbose : bool
592 Whether to display a progress bar during the optimization process.
593
594 self.gains_ : numpy.ndarray or None
595 The gain that each example would give the last time that it was
596 evaluated.
597 """
598
599 def __init__(self, function=None, epsilon=0.9, optimizer='lazy',
600 random_state=None, n_jobs=None, verbose=False):
601 self.epsilon = epsilon
602 self.optimizer = optimizer
603 super(SampleGreedy, self).__init__(function=function,
604 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
605
606 def select(self, X, k, sample_cost=None):
607 n = X.shape[0]
608 subset_size = max(int(n * self.epsilon), 1)
609
610 idxs = self.random_state.choice(self.function.idxs,
611 replace=False, size=n - subset_size)
612
613 if isinstance(self.optimizer, str):
614 optimizer = OPTIMIZERS[self.optimizer](function=self.function,
615 verbose=self.verbose)
616 elif not isinstance(self.optimizer, BaseOptimizer):
617 raise ValueError("optimizer must be either a string or an " /
618 "optimizer object.")
619 else:
620 optimizer = self.optimizer
621
622 self.function.mask[idxs] = 1
623 self.function.idxs = numpy.where(self.function.mask == 0)[0]
624 optimizer.select(X, k, sample_cost=sample_cost)
625
626
627 class GreeDi(BaseOptimizer):
628 """An approach for optimizing submodular functions on massive data sets.
629
630 GreeDi is an optimizer that was designed to work on data sets that are
631 too large to fit into memory. The approach involves first partitioning
632 the data into :math:`m` equally sized chunks without any overlap. Then,
633 :math:`l` elements are selected from each chunk using a standard optimizer
634 like naive or lazy greedy. Finally, these :math:`ml` examples are merged
635 and a standard optimizer selects :math:`k` examples from this set. In
636 this manner, the algorithm sacrifices exactness to ensure that memory
637 limitations are not an issue.
638
639 There are a few considerations to keep in mind when using GreeDi.
640 Naturally, :math:`ml` must both be larger than :math:`k` and also small
641 enough to fit into memory. The larger :math:`l`, the closer the solution
642 is to the exact solution but also the more compute time is required.
643 Conversely, the larger :math:`m` is, the less exact the solution is.
644 When using a graph-based function, increasing :math:`m` can dramatically
645 reduce the amount of computation that needs to be performed, as well as
646 the memory requirements, because the similarity matrix becomes smaller
647 in size. However, feature-based functions are likely to see less of a
648 speed improvement because the cost of evaluating an example is independent
649 of the size of ground set.
650
651 .. code::python
652
653 from apricot import FeatureBasedSelection
654
655 X = numpy.random.randint(10, size=(10000, 100))
656
657 selector = FeatureBasedSelection(100, 'sqrt', optimizer='greedi')
658 selector.fit(X)
659
660 Parameters
661 ----------
662 function : base.BaseSelection
663 A submodular function that implements the `_calculate_gains` and
664 `_select_next` methods. This is the function that will be
665 optimized.
666
667 m : int
668 The number of partitions to split the data into.
669
670 l : int
671 The number of exemplars to select from each partition. l*m must
672 be larger than the number of exemplars k that will be selected
673 later on.
674
675 optimizer1 : str or base.Optimizer, optional
676 The optimizer to use in the first stage of the process where l
677 exemplars are selected from each partition. Default is 'lazy'.
678
679 optimizer2 : str or base.Optimizer, optional
680 The optimizer to use in the second stage where k exemplars are
681 selected from the l*m exemplars returned from the first stage.
682 Default is 'lazy'.
683
684 random_state : int or RandomState or None, optional
685 The random seed to use for the random selection process.
686
687 verbose : bool
688 Whether to display a progress bar during the optimization process.
689
690
691 Attributes
692 ----------
693 self.function : base.BaseSelection or None
694 A submodular function that implements the `_calculate_gains` and
695 `_select_next` methods. This is the function that will be
696 optimized. If None, will be set by the selector when passed in.
697
698 self.m : int
699 The number of partitions that the data will be split into.
700
701 self.l : int
702 The number of exemplars that will be selected from each partition.
703
704 self.verbose : bool
705 Whether to display a progress bar during the optimization process.
706
707 self.gains_ : numpy.ndarray or None
708 The gain that each example would give the last time that it was
709 evaluated.
710 """
711
712 def __init__(self, function=None, m=None, l=None, optimizer1='lazy',
713 optimizer2='lazy', random_state=None, n_jobs=None, verbose=False):
714 self.m = m
715 self.l = l
716 self.optimizer1 = optimizer1
717 self.optimizer2 = optimizer2
718 super(GreeDi, self).__init__(function=function,
719 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
720
721 def select(self, X, k, sample_cost=None):
722 if self.m is None and self.l is None:
723 self.m = 8
724 self.l = min(k // 4, X.shape[0] // self.m)
725
726 if sample_cost is None:
727 sample_cost = numpy.ones(X.shape[0], dtype='float64')
728
729 if k > (self.m * self.l):
730 raise ValueError("k must be smaller than m * l")
731
732 partitions = numpy.arange(X.shape[0]) % self.m
733 self.random_state.shuffle(partitions)
734
735 optimizer1 = OPTIMIZERS[self.optimizer1](function=self.function,
736 verbose=self.verbose)
737 optimizer2 = OPTIMIZERS[self.optimizer2](function=self.function,
738 verbose=self.verbose)
739
740 rankings = []
741
742 for i in range(self.m):
743 idxs = numpy.where(partitions == i)[0]
744
745 X_subset = X[idxs]
746 if X.shape[0] == X.shape[1]:
747 X_subset = X_subset[:, idxs]
748
749 self.function._initialize(X_subset)
750 optimizer1.select(X_subset, self.l, sample_cost=sample_cost[idxs])
751
752 rankings.append(idxs[self.function.ranking])
753
754 rankings = numpy.concatenate(rankings)
755
756 if self.verbose:
757 self.function.pbar.close()
758 self.function.pbar = tqdm(total=k)
759
760 X_subset = X[rankings]
761 if X.shape[0] == X.shape[1]:
762 X_subset = X_subset[:, rankings]
763
764 self.function._initialize(X_subset)
765 optimizer2.select(X_subset, k, sample_cost=sample_cost[rankings])
766 rankings = rankings[self.function.ranking]
767
768 self.function._initialize(X)
769 for idx in rankings:
770 gain = self.function._calculate_gains(X, numpy.array([idx]))[0]
771 self.function._select_next(X[idx], gain, idx)
772
773
774 class RandomGreedy(BaseOptimizer):
775 """The naive greedy algorithm for optimization.
776
777 This optimization approach is the naive greedy algorithm. At each iteration
778 of selection it will simply calculate the gain one would get from adding
779 each example, and then will select the example that has the highest gain.
780 This algorithm is conceptually simple and easy to parallelize and put on a
781 GPU, but can be slower than other alternatives because it involves
782 repeatedly evaluating examples that are not likely to be selected next.
783
784 Parameters
785 ----------
786 self.function : base.BaseSelection
787 A submodular function that implements the `_calculate_gains` and
788 `_select_next` methods. This is the function that will be
789 optimized.
790
791 self.verbose : bool
792 Whether to display a progress bar during the optimization process.
793
794
795 Attributes
796 ----------
797 self.function : base.BaseSelection
798 A submodular function that implements the `_calculate_gains` and
799 `_select_next` methods. This is the function that will be
800 optimized.
801
802 self.verbose : bool
803 Whether to display a progress bar during the optimization process.
804 """
805
806 def __init__(self, function=None, random_state=None, n_jobs=None,
807 verbose=False):
808 super(NaiveGreedy, self).__init__(function=function,
809 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
810
811 def select(self, X, k, sample_cost=None):
812 cost = 0.0
813 if sample_cost is None:
814 sample_cost = numpy.ones(X.shape[0], dtype='float64')
815
816 i = 0
817 while cost < k:
818 idx = self.random_state.choice(self.random.idxs)
819
820 if cost + sample_cost[idx] > k:
821 continue
822
823 cost += sample_cost[idx]
824 gain = self.function._calculate_gains(X, idxs=numpy.array([idx]))[0]
825
826 self.function._select_next(X[idx], gain, idx)
827
828 if self.verbose == True:
829 self.function.pbar.update(round(sample_cost[idx], 2))
830
831
832 class ModularGreedy(BaseOptimizer):
833 """An approach that approximates a submodular function as modular.
834
835 This approach approximates the submodular function by using its modular
836 upper-bounds to do the selection. Essentially, a defining characteristic
837 of submodular functions is the *diminishing returns* property where the
838 gain of an example decreases with the number of selected examples. In
839 contrast, modular functions have constant gains for examples regardless
840 of the number of selected examples. Thus, approximating the submodular
841 function as a modular function can serve as an upper-bound to the gain
842 for each example during the selection process. This approximation makes
843 the function simple to optimize because one would simply calculate the
844 gain that each example yields before any examples are selected, sort the
845 examples by this gain, and select the top :math:`k` examples. While this
846 approach is fast, this approach is likely best paired with a traditional
847 optimization algorithm after the first few examples are selected.
848
849 .. code::python
850
851 from apricot import FeatureBasedSelection
852
853 X = numpy.random.randint(10, size=(10000, 100))
854
855 selector = FeatureBasedSelection(100, 'sqrt', optimizer='modular')
856 selector.fit(X)
857
858 Parameters
859 ----------
860 self.function : base.BaseSelection
861 A submodular function that implements the `_calculate_gains` and
862 `_select_next` methods. This is the function that will be
863 optimized.
864
865 epsilon : float, optional
866 The inverse of the sampling probability of any particular point being
867 included in the subset, such that 1 - epsilon is the probability that
868 a point is included. Default is 0.9.
869
870 random_state : int or RandomState or None, optional
871 The random seed to use for the random selection process.
872
873 self.verbose : bool
874 Whether to display a progress bar during the optimization process.
875
876
877 Attributes
878 ----------
879 self.function : base.BaseSelection
880 A submodular function that implements the `_calculate_gains` and
881 `_select_next` methods. This is the function that will be
882 optimized.
883
884 self.verbose : bool
885 Whether to display a progress bar during the optimization process.
886
887 self.gains_ : numpy.ndarray or None
888 The gain that each example would give the last time that it was
889 evaluated.
890 """
891
892 def __init__(self, function=None, random_state=None, n_jobs=None,
893 verbose=False):
894 super(ModularGreedy, self).__init__(function=function,
895 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
896
897 def select(self, X, k, sample_cost=None):
898 """Select elements in a naive greedy manner."""
899
900 cost = 0.0
901 if sample_cost is None:
902 sample_cost = numpy.ones(X.shape[0], dtype='float64')
903
904 gains = self.function._calculate_gains(X) / sample_cost[self.function.idxs]
905 idxs = gains.argsort()[::-1]
906
907 for idx in idxs:
908 if cost + sample_cost[idx] > k:
909 continue
910
911 cost += sample_cost[idx]
912 gain = self.function._calculate_gains(X, idxs=numpy.array([idx]))[0]
913
914 self.function._select_next(X[idx], gain, idx)
915
916 if self.verbose == True:
917 self.function.pbar.update(1)
918
919
920 class BidirectionalGreedy(BaseOptimizer):
921 """The bidirectional greedy algorithm.
922
923 Most submodular optimizers assume that the function is *monotone*, i.e.,
924 that the gain from each successive example is positive. However, there
925 are some cases where the key diminishing returns property holds, but
926 the gains are not necessarily positive. The most obvious of these is a
927 difference in submodular functions. In these cases, the naive greedy
928 algorithm is not guaranteed to return a good result.
929
930 The bidirectional greedy algorithm was developed to optimize non-monotone
931 submodular functions. While it has a guarantee that is lower than the
932 naive greedy algorithm has for monotone functions, it generally returns
933 better sets than the greedy algorithm.
934
935 .. code::python
936
937 from apricot import FeatureBasedSelection
938
939 X = numpy.random.randint(10, size=(10000, 100))
940
941 selector = FeatureBasedSelection(100, 'sqrt', optimizer='bidirectional')
942 selector.fit(X)
943
944 Parameters
945 ----------
946 self.function : base.BaseSelection
947 A submodular function that implements the `_calculate_gains` and
948 `_select_next` methods. This is the function that will be
949 optimized.
950
951 self.verbose : bool
952 Whether to display a progress bar during the optimization process.
953
954
955 Attributes
956 ----------
957 self.function : base.BaseSelection
958 A submodular function that implements the `_calculate_gains` and
959 `_select_next` methods. This is the function that will be
960 optimized.
961
962 self.verbose : bool
963 Whether to display a progress bar during the optimization process.
964
965 self.gains_ : numpy.ndarray or None
966 The gain that each example would give the last time that it was
967 evaluated.
968 """
969
970 def __init__(self, function=None, random_state=None, n_jobs=None,
971 verbose=False):
972 super(BidirectionalGreedy, self).__init__(function=function,
973 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
974
975 def select(self, X, k, sample_cost=None):
976 """Select elements in a naive greedy manner."""
977
978 cost = 0.0
979 if sample_cost is None:
980 sample_cost = numpy.ones(X.shape[0], dtype='float64')
981
982 A = numpy.zeros(X.shape[0], dtype=bool)
983 B = numpy.ones(X.shape[0], dtype=bool)
984
985 idxs = numpy.arange(X.shape[0])
986 self.random_state.shuffle(idxs)
987 gains = numpy.zeros(X.shape[0])
988
989 while True:
990 for i in idxs:
991 if A[i] == True:
992 continue
993
994 self.function.initial_subset = A
995 self.function._initialize(X)
996 gain_a = self.function._calculate_gains(X[i])
997
998
999 B[i] = False
1000 self.function.initial_subset = B
1001 self.function._initialize(X)
1002 gain_b = -self.function._calculate_gains(X[i])
1003 B[i] = True
1004
1005 if gain_a == gain_b == 0.0:
1006 p = 0.5
1007 else:
1008 p = gain_a / (gain_a + gain_b)
1009
1010 self.gains_[i] = p
1011
1012 if self.random_state.uniform(0, 1) <= p:
1013 A[i] = True
1014 self.function._select_next(X[i], gain_a, i)
1015 if A.sum() == k:
1016 return
1017
1018 else:
1019 B[i] = False
1020
1021
1022 class SieveGreedy(BaseOptimizer):
1023 """The sieve stream greedy algorithm.
1024
1025 Most submodular optimizers assume that the function is *monotone*, i.e.,
1026 that the gain from each successive example is positive. However, there
1027 are some cases where the key diminishing returns property holds, but
1028 the gains are not necessarily positive. The most obvious of these is a
1029 difference in submodular functions. In these cases, the naive greedy
1030 algorithm is not guaranteed to return a good result.
1031
1032 The bidirectional greedy algorithm was developed to optimize non-monotone
1033 submodular functions. While it has a guarantee that is lower than the
1034 naive greedy algorithm has for monotone functions, it generally returns
1035 better sets than the greedy algorithm.
1036
1037 .. code::python
1038
1039 from apricot import FeatureBasedSelection
1040
1041 X = numpy.random.randint(10, size=(10000, 100))
1042
1043 selector = FeatureBasedSelection(100, 'sqrt', optimizer='bidirectional')
1044 selector.fit(X)
1045
1046 Parameters
1047 ----------
1048 self.function : base.BaseSelection
1049 A submodular function that implements the `_calculate_gains` and
1050 `_select_next` methods. This is the function that will be
1051 optimized.
1052
1053 self.verbose : bool
1054 Whether to display a progress bar during the optimization process.
1055
1056
1057 Attributes
1058 ----------
1059 self.function : base.BaseSelection
1060 A submodular function that implements the `_calculate_gains` and
1061 `_select_next` methods. This is the function that will be
1062 optimized.
1063
1064 self.verbose : bool
1065 Whether to display a progress bar during the optimization process.
1066
1067 self.gains_ : numpy.ndarray or None
1068 The gain that each example would give the last time that it was
1069 evaluated.
1070 """
1071
1072 def __init__(self, function=None, epsilon=0.01, random_state=None,
1073 n_jobs=None, verbose=False):
1074 self.epsilon = epsilon
1075 self.n_seen_ = 0
1076 self.thresholds = [1]
1077 self.max_gain = -1
1078
1079 super(SieveGreedy, self).__init__(function=function,
1080 random_state=random_state, n_jobs=n_jobs, verbose=verbose)
1081
1082 def select(self, X, k, sample_cost=None):
1083 """Select elements in a naive greedy manner."""
1084
1085 # This is not a great use of the apricot API. An optimizer shouldn't
1086 # be using its own special gain calculating function. However, it is
1087 # much faster to do things this way so I'll keep it in for now.
1088
1089 n, d = X.shape
1090 if sample_cost is None:
1091 sample_cost = numpy.ones(n, dtype='float64')
1092
1093 r = X.shape[1] if self.function.reservoir is not None else 1
1094 marginal_gains = self.function._calculate_gains(X) / sample_cost / r
1095 max_marginal_gain = marginal_gains.max()
1096 if max_marginal_gain > self.max_gain:
1097 self.max_gain = max_marginal_gain
1098 j = len(self.thresholds)
1099 threshold = (1 + self.epsilon) ** j - 1
1100 while threshold <= self.max_gain * k:
1101 self.thresholds.append(threshold)
1102
1103 j += 1
1104 threshold = (1 + self.epsilon) ** j - 1
1105
1106 thresholds = numpy.array(self.thresholds, dtype='float64')
1107 idxs = numpy.arange(n, dtype='int64') + self.n_seen_
1108
1109 self.function._calculate_sieve_gains(X, thresholds, idxs)
1110
1111 best_idx = numpy.argmax(self.function.sieve_total_gains_)
1112 ranking = self.function.sieve_selections_[best_idx]
1113 ranking = ranking[:self.function.sieve_n_selected_[best_idx]]
1114 gain = self.function.sieve_gains_[best_idx]
1115 gain = gain[:self.function.sieve_n_selected_[best_idx]]
1116
1117 for i in range(len(self.thresholds)):
1118 for j in range(k):
1119 m = self.function.sieve_selections_[i, j]
1120 if m >= self.n_seen_:
1121 if isinstance(self.function._X, scipy.sparse.csr_matrix):
1122 self.function.sieve_subsets_[i, j] = self.function._X[m - self.n_seen_].toarray()[0]
1123 else:
1124 self.function.sieve_subsets_[i, j] = self.function._X[m - self.n_seen_]
1125
1126 self.function.ranking = ranking
1127 self.function.gains = gain
1128 self.function.subset = self.function.sieve_subsets_[best_idx]
1129 self.n_seen_ += X.shape[0]
1130
1131
1132 OPTIMIZERS = {
1133 'random' : RandomGreedy,
1134 'modular' : ModularGreedy,
1135 'naive' : NaiveGreedy,
1136 'lazy' : LazyGreedy,
1137 'approximate-lazy' : ApproximateLazyGreedy,
1138 'two-stage' : TwoStageGreedy,
1139 'stochastic' : StochasticGreedy,
1140 'sample' : SampleGreedy,
1141 'greedi' : GreeDi,
1142 'bidirectional' : BidirectionalGreedy,
1143 'sieve' : SieveGreedy,
1144 }