| 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] does the same as what's below |
| 906 |
# but is not stable. It requires numpy >= 2 to have the "stable" |
| 907 |
# parameter in np.argort. |
| 908 |
idxs = numpy.lexsort((numpy.arange(gains.shape[0]), -gains)) |
| 909 |
|
| 910 |
for idx in idxs: |
| 911 |
if cost + sample_cost[idx] > k: |
| 912 |
continue |
| 913 |
|
| 914 |
cost += sample_cost[idx] |
| 915 |
gain = self.function._calculate_gains(X, idxs=numpy.array([idx]))[0] |
| 916 |
|
| 917 |
self.function._select_next(X[idx], gain, idx) |
| 918 |
|
| 919 |
if self.verbose == True: |
| 920 |
self.function.pbar.update(1) |
| 921 |
|
| 922 |
|
| 923 |
class BidirectionalGreedy(BaseOptimizer): |
| 924 |
"""The bidirectional greedy algorithm. |
| 925 |
|
| 926 |
Most submodular optimizers assume that the function is *monotone*, i.e., |
| 927 |
that the gain from each successive example is positive. However, there |
| 928 |
are some cases where the key diminishing returns property holds, but |
| 929 |
the gains are not necessarily positive. The most obvious of these is a |
| 930 |
difference in submodular functions. In these cases, the naive greedy |
| 931 |
algorithm is not guaranteed to return a good result. |
| 932 |
|
| 933 |
The bidirectional greedy algorithm was developed to optimize non-monotone |
| 934 |
submodular functions. While it has a guarantee that is lower than the |
| 935 |
naive greedy algorithm has for monotone functions, it generally returns |
| 936 |
better sets than the greedy algorithm. |
| 937 |
|
| 938 |
.. code::python |
| 939 |
|
| 940 |
from apricot import FeatureBasedSelection |
| 941 |
|
| 942 |
X = numpy.random.randint(10, size=(10000, 100)) |
| 943 |
|
| 944 |
selector = FeatureBasedSelection(100, 'sqrt', optimizer='bidirectional') |
| 945 |
selector.fit(X) |
| 946 |
|
| 947 |
Parameters |
| 948 |
---------- |
| 949 |
self.function : base.BaseSelection |
| 950 |
A submodular function that implements the `_calculate_gains` and |
| 951 |
`_select_next` methods. This is the function that will be |
| 952 |
optimized. |
| 953 |
|
| 954 |
self.verbose : bool |
| 955 |
Whether to display a progress bar during the optimization process. |
| 956 |
|
| 957 |
|
| 958 |
Attributes |
| 959 |
---------- |
| 960 |
self.function : base.BaseSelection |
| 961 |
A submodular function that implements the `_calculate_gains` and |
| 962 |
`_select_next` methods. This is the function that will be |
| 963 |
optimized. |
| 964 |
|
| 965 |
self.verbose : bool |
| 966 |
Whether to display a progress bar during the optimization process. |
| 967 |
|
| 968 |
self.gains_ : numpy.ndarray or None |
| 969 |
The gain that each example would give the last time that it was |
| 970 |
evaluated. |
| 971 |
""" |
| 972 |
|
| 973 |
def __init__(self, function=None, random_state=None, n_jobs=None, |
| 974 |
verbose=False): |
| 975 |
super(BidirectionalGreedy, self).__init__(function=function, |
| 976 |
random_state=random_state, n_jobs=n_jobs, verbose=verbose) |
| 977 |
|
| 978 |
def select(self, X, k, sample_cost=None): |
| 979 |
"""Select elements in a naive greedy manner.""" |
| 980 |
|
| 981 |
cost = 0.0 |
| 982 |
if sample_cost is None: |
| 983 |
sample_cost = numpy.ones(X.shape[0], dtype='float64') |
| 984 |
|
| 985 |
A = numpy.zeros(X.shape[0], dtype=bool) |
| 986 |
B = numpy.ones(X.shape[0], dtype=bool) |
| 987 |
|
| 988 |
idxs = numpy.arange(X.shape[0]) |
| 989 |
self.random_state.shuffle(idxs) |
| 990 |
gains = numpy.zeros(X.shape[0]) |
| 991 |
|
| 992 |
while True: |
| 993 |
for i in idxs: |
| 994 |
if A[i] == True: |
| 995 |
continue |
| 996 |
|
| 997 |
self.function.initial_subset = A |
| 998 |
self.function._initialize(X) |
| 999 |
gain_a = self.function._calculate_gains(X[i]) |
| 1000 |
|
| 1001 |
|
| 1002 |
B[i] = False |
| 1003 |
self.function.initial_subset = B |
| 1004 |
self.function._initialize(X) |
| 1005 |
gain_b = -self.function._calculate_gains(X[i]) |
| 1006 |
B[i] = True |
| 1007 |
|
| 1008 |
if gain_a == gain_b == 0.0: |
| 1009 |
p = 0.5 |
| 1010 |
else: |
| 1011 |
p = gain_a / (gain_a + gain_b) |
| 1012 |
|
| 1013 |
self.gains_[i] = p |
| 1014 |
|
| 1015 |
if self.random_state.uniform(0, 1) <= p: |
| 1016 |
A[i] = True |
| 1017 |
self.function._select_next(X[i], gain_a, i) |
| 1018 |
if A.sum() == k: |
| 1019 |
return |
| 1020 |
|
| 1021 |
else: |
| 1022 |
B[i] = False |
| 1023 |
|
| 1024 |
|
| 1025 |
class SieveGreedy(BaseOptimizer): |
| 1026 |
"""The sieve stream greedy algorithm. |
| 1027 |
|
| 1028 |
Most submodular optimizers assume that the function is *monotone*, i.e., |
| 1029 |
that the gain from each successive example is positive. However, there |
| 1030 |
are some cases where the key diminishing returns property holds, but |
| 1031 |
the gains are not necessarily positive. The most obvious of these is a |
| 1032 |
difference in submodular functions. In these cases, the naive greedy |
| 1033 |
algorithm is not guaranteed to return a good result. |
| 1034 |
|
| 1035 |
The bidirectional greedy algorithm was developed to optimize non-monotone |
| 1036 |
submodular functions. While it has a guarantee that is lower than the |
| 1037 |
naive greedy algorithm has for monotone functions, it generally returns |
| 1038 |
better sets than the greedy algorithm. |
| 1039 |
|
| 1040 |
.. code::python |
| 1041 |
|
| 1042 |
from apricot import FeatureBasedSelection |
| 1043 |
|
| 1044 |
X = numpy.random.randint(10, size=(10000, 100)) |
| 1045 |
|
| 1046 |
selector = FeatureBasedSelection(100, 'sqrt', optimizer='bidirectional') |
| 1047 |
selector.fit(X) |
| 1048 |
|
| 1049 |
Parameters |
| 1050 |
---------- |
| 1051 |
self.function : base.BaseSelection |
| 1052 |
A submodular function that implements the `_calculate_gains` and |
| 1053 |
`_select_next` methods. This is the function that will be |
| 1054 |
optimized. |
| 1055 |
|
| 1056 |
self.verbose : bool |
| 1057 |
Whether to display a progress bar during the optimization process. |
| 1058 |
|
| 1059 |
|
| 1060 |
Attributes |
| 1061 |
---------- |
| 1062 |
self.function : base.BaseSelection |
| 1063 |
A submodular function that implements the `_calculate_gains` and |
| 1064 |
`_select_next` methods. This is the function that will be |
| 1065 |
optimized. |
| 1066 |
|
| 1067 |
self.verbose : bool |
| 1068 |
Whether to display a progress bar during the optimization process. |
| 1069 |
|
| 1070 |
self.gains_ : numpy.ndarray or None |
| 1071 |
The gain that each example would give the last time that it was |
| 1072 |
evaluated. |
| 1073 |
""" |
| 1074 |
|
| 1075 |
def __init__(self, function=None, epsilon=0.01, random_state=None, |
| 1076 |
n_jobs=None, verbose=False): |
| 1077 |
self.epsilon = epsilon |
| 1078 |
self.n_seen_ = 0 |
| 1079 |
self.thresholds = [1] |
| 1080 |
self.max_gain = -1 |
| 1081 |
|
| 1082 |
super(SieveGreedy, self).__init__(function=function, |
| 1083 |
random_state=random_state, n_jobs=n_jobs, verbose=verbose) |
| 1084 |
|
| 1085 |
def select(self, X, k, sample_cost=None): |
| 1086 |
"""Select elements in a naive greedy manner.""" |
| 1087 |
|
| 1088 |
# This is not a great use of the apricot API. An optimizer shouldn't |
| 1089 |
# be using its own special gain calculating function. However, it is |
| 1090 |
# much faster to do things this way so I'll keep it in for now. |
| 1091 |
|
| 1092 |
n, d = X.shape |
| 1093 |
if sample_cost is None: |
| 1094 |
sample_cost = numpy.ones(n, dtype='float64') |
| 1095 |
|
| 1096 |
r = X.shape[1] if self.function.reservoir is not None else 1 |
| 1097 |
marginal_gains = self.function._calculate_gains(X) / sample_cost / r |
| 1098 |
max_marginal_gain = marginal_gains.max() |
| 1099 |
if max_marginal_gain > self.max_gain: |
| 1100 |
self.max_gain = max_marginal_gain |
| 1101 |
j = len(self.thresholds) |
| 1102 |
threshold = (1 + self.epsilon) ** j - 1 |
| 1103 |
while threshold <= self.max_gain * k: |
| 1104 |
self.thresholds.append(threshold) |
| 1105 |
|
| 1106 |
j += 1 |
| 1107 |
threshold = (1 + self.epsilon) ** j - 1 |
| 1108 |
|
| 1109 |
thresholds = numpy.array(self.thresholds, dtype='float64') |
| 1110 |
idxs = numpy.arange(n, dtype='int64') + self.n_seen_ |
| 1111 |
|
| 1112 |
self.function._calculate_sieve_gains(X, thresholds, idxs) |
| 1113 |
|
| 1114 |
best_idx = numpy.argmax(self.function.sieve_total_gains_) |
| 1115 |
ranking = self.function.sieve_selections_[best_idx] |
| 1116 |
ranking = ranking[:self.function.sieve_n_selected_[best_idx]] |
| 1117 |
gain = self.function.sieve_gains_[best_idx] |
| 1118 |
gain = gain[:self.function.sieve_n_selected_[best_idx]] |
| 1119 |
|
| 1120 |
for i in range(len(self.thresholds)): |
| 1121 |
for j in range(k): |
| 1122 |
m = self.function.sieve_selections_[i, j] |
| 1123 |
if m >= self.n_seen_: |
| 1124 |
if isinstance(self.function._X, scipy.sparse.csr_matrix): |
| 1125 |
self.function.sieve_subsets_[i, j] = self.function._X[m - self.n_seen_].toarray()[0] |
| 1126 |
else: |
| 1127 |
self.function.sieve_subsets_[i, j] = self.function._X[m - self.n_seen_] |
| 1128 |
|
| 1129 |
self.function.ranking = ranking |
| 1130 |
self.function.gains = gain |
| 1131 |
self.function.subset = self.function.sieve_subsets_[best_idx] |
| 1132 |
self.n_seen_ += X.shape[0] |
| 1133 |
|
| 1134 |
|
| 1135 |
OPTIMIZERS = { |
| 1136 |
'random' : RandomGreedy, |
| 1137 |
'modular' : ModularGreedy, |
| 1138 |
'naive' : NaiveGreedy, |
| 1139 |
'lazy' : LazyGreedy, |
| 1140 |
'approximate-lazy' : ApproximateLazyGreedy, |
| 1141 |
'two-stage' : TwoStageGreedy, |
| 1142 |
'stochastic' : StochasticGreedy, |
| 1143 |
'sample' : SampleGreedy, |
| 1144 |
'greedi' : GreeDi, |
| 1145 |
'bidirectional' : BidirectionalGreedy, |
| 1146 |
'sieve' : SieveGreedy, |
| 1147 |
} |