| 1 |
# base.py |
| 2 |
# Author: Jacob Schreiber <[email protected]> |
| 3 |
|
| 4 |
""" |
| 5 |
This file contains code that implements the core of the submodular selection |
| 6 |
algorithms. |
| 7 |
""" |
| 8 |
|
| 9 |
import numpy |
| 10 |
from tqdm import tqdm |
| 11 |
|
| 12 |
from ..optimizers import BaseOptimizer |
| 13 |
from ..optimizers import NaiveGreedy |
| 14 |
from ..optimizers import LazyGreedy |
| 15 |
from ..optimizers import ApproximateLazyGreedy |
| 16 |
from ..optimizers import TwoStageGreedy |
| 17 |
from ..optimizers import StochasticGreedy |
| 18 |
from ..optimizers import BidirectionalGreedy |
| 19 |
from ..optimizers import GreeDi |
| 20 |
from ..optimizers import SieveGreedy |
| 21 |
from ..optimizers import OPTIMIZERS |
| 22 |
|
| 23 |
from ..utils import PriorityQueue |
| 24 |
from ..utils import check_random_state |
| 25 |
from ..utils import _calculate_pairwise_distances |
| 26 |
|
| 27 |
from scipy.sparse import csr_matrix |
| 28 |
|
| 29 |
|
| 30 |
class BaseSelection(object): |
| 31 |
"""The base selection object. |
| 32 |
|
| 33 |
This object defines the structures that all submodular selection algorithms |
| 34 |
should follow. All algorithms will have the same public methods and the |
| 35 |
same attributes. |
| 36 |
|
| 37 |
Parameters |
| 38 |
---------- |
| 39 |
n_samples : int |
| 40 |
The number of samples to return. |
| 41 |
|
| 42 |
initial_subset : list, numpy.ndarray or None, optional |
| 43 |
If provided, this should be a list of indices into the data matrix |
| 44 |
to use as the initial subset, or a group of examples that may not be |
| 45 |
in the provided data should beused as the initial subset. If indices, |
| 46 |
the provided array should be one-dimensional. If a group of examples, |
| 47 |
the data should be 2 dimensional. |
| 48 |
|
| 49 |
optimizer : string or optimizers.BaseOptimizer, optional |
| 50 |
The optimization approach to use for the selection. Default is |
| 51 |
'two-stage', which makes selections using the naive greedy algorithm |
| 52 |
initially and then switches to the lazy greedy algorithm. Must be |
| 53 |
one of |
| 54 |
|
| 55 |
'naive' : the naive greedy algorithm |
| 56 |
'lazy' : the lazy (or accelerated) greedy algorithm |
| 57 |
'approximate-lazy' : the approximate lazy greedy algorithm |
| 58 |
'two-stage' : starts with naive and switches to lazy |
| 59 |
'stochastic' : the stochastic greedy algorithm |
| 60 |
'greedi' : the GreeDi distributed algorithm |
| 61 |
'bidirectional' : the bidirectional greedy algorithm |
| 62 |
|
| 63 |
Default is 'naive'. |
| 64 |
|
| 65 |
optimizer_kwds : dict or None |
| 66 |
A dictionary of arguments to pass into the optimizer object. The keys |
| 67 |
of this dictionary should be the names of the parameters in the optimizer |
| 68 |
and the values in the dictionary should be the values that these |
| 69 |
parameters take. Default is None. |
| 70 |
|
| 71 |
reservoir : numpy.ndarray or None |
| 72 |
The reservoir to use when calculating gains in the sieve greedy |
| 73 |
streaming optimization algorithm in the `partial_fit` method. |
| 74 |
Currently only used for graph-based functions. If a numpy array |
| 75 |
is passed in, it will be used as the reservoir. If None is passed in, |
| 76 |
will use reservoir sampling to collect a reservoir. Default is None. |
| 77 |
|
| 78 |
max_reservoir_size : int |
| 79 |
The maximum size that the reservoir can take. If a reservoir is passed |
| 80 |
in, this value is set to the size of that array. Default is 1000. |
| 81 |
|
| 82 |
n_jobs : int |
| 83 |
The number of threads to use when performing computation in parallel. |
| 84 |
Currently, this parameter is exposed but does not actually do anything. |
| 85 |
This will be fixed soon. |
| 86 |
|
| 87 |
random_state : int or RandomState or None, optional |
| 88 |
The random seed to use for the random selection process. Only used |
| 89 |
for stochastic greedy. |
| 90 |
|
| 91 |
verbose : bool |
| 92 |
Whether to print output during the selection process. |
| 93 |
|
| 94 |
Attributes |
| 95 |
---------- |
| 96 |
n_samples : int |
| 97 |
The number of samples to select. |
| 98 |
|
| 99 |
ranking : numpy.array int |
| 100 |
The selected samples in the order of their gain with the first number in |
| 101 |
the ranking corresponding to the index of the first sample that was |
| 102 |
selected by the greedy procedure. |
| 103 |
|
| 104 |
gains : numpy.array float |
| 105 |
The gain of each sample in the returned set when it was added to the |
| 106 |
growing subset. The first number corresponds to the gain of the first |
| 107 |
added sample, the second corresponds to the gain of the second added |
| 108 |
sample, and so forth. |
| 109 |
""" |
| 110 |
|
| 111 |
def __init__(self, n_samples, initial_subset=None, optimizer='lazy', |
| 112 |
optimizer_kwds={}, reservoir=None, max_reservoir_size=1000, |
| 113 |
n_jobs=1, random_state=None, verbose=False): |
| 114 |
if n_samples <= 0: |
| 115 |
raise ValueError("n_samples must be a positive value.") |
| 116 |
|
| 117 |
if not isinstance(initial_subset, (list, numpy.ndarray)) and initial_subset is not None: |
| 118 |
raise ValueError("initial_subset must be a list, numpy array, or None") |
| 119 |
if isinstance(initial_subset, (list, numpy.ndarray)): |
| 120 |
initial_subset = numpy.array(initial_subset) |
| 121 |
|
| 122 |
if not isinstance(optimizer, BaseOptimizer): |
| 123 |
if optimizer not in OPTIMIZERS.keys(): |
| 124 |
raise ValueError("Optimizer must be an optimizer object or " \ |
| 125 |
"a str in {}.".format(str(OPTIMIZERS.keys()))) |
| 126 |
|
| 127 |
if isinstance(optimizer, BaseOptimizer): |
| 128 |
optimizer.function = self |
| 129 |
|
| 130 |
if verbose not in (True, False): |
| 131 |
raise ValueError("verbosity must be True or False") |
| 132 |
|
| 133 |
self.n_samples = n_samples |
| 134 |
self.metric = 'ignore' |
| 135 |
self.random_state = check_random_state(random_state) |
| 136 |
self.optimizer = optimizer |
| 137 |
self.optimizer_kwds = optimizer_kwds |
| 138 |
self.n_jobs = n_jobs |
| 139 |
self.verbose = verbose |
| 140 |
self.initial_subset = initial_subset |
| 141 |
|
| 142 |
self.ranking = None |
| 143 |
self.idxs = None |
| 144 |
self.gains = None |
| 145 |
self.subset = None |
| 146 |
self.sparse = None |
| 147 |
self._X = None |
| 148 |
|
| 149 |
self.sieve_current_values_ = None |
| 150 |
self.n_seen_ = 0 |
| 151 |
self.reservoir_size = 0 if reservoir is None else reservoir.shape[0] |
| 152 |
self.reservoir = reservoir |
| 153 |
self.max_reservoir_size = max_reservoir_size if reservoir is None else reservoir.shape[0] |
| 154 |
self.update_reservoir_ = reservoir is None |
| 155 |
|
| 156 |
def fit(self, X, y=None, sample_weight=None, sample_cost=None): |
| 157 |
"""Run submodular optimization to select a subset of examples. |
| 158 |
|
| 159 |
This method is a wrapper for the full submodular optimization process. |
| 160 |
It takes in some data set (and optionally labels that are ignored |
| 161 |
during this process) and selects `n_samples` from it in the greedy |
| 162 |
manner specified by the optimizer. |
| 163 |
|
| 164 |
This method will return the selector object itself, not the transformed |
| 165 |
data set. The `transform` method will then transform a data set to the |
| 166 |
selected points, or alternatively one can use the ranking stored in |
| 167 |
the `self.ranking` attribute. The `fit_transform` method will perform |
| 168 |
both optimization and selection and return the selected items. |
| 169 |
|
| 170 |
Parameters |
| 171 |
---------- |
| 172 |
X : list or numpy.ndarray, shape=(n, d) |
| 173 |
The data set to transform. Must be numeric. |
| 174 |
|
| 175 |
y : list or numpy.ndarray or None, shape=(n,), optional |
| 176 |
The labels to transform. If passed in this function will return |
| 177 |
both the data and th corresponding labels for the rows that have |
| 178 |
been selected. |
| 179 |
|
| 180 |
sample_weight : list or numpy.ndarray or None, shape=(n,), optional |
| 181 |
The weight of each example. Currently ignored in apricot but |
| 182 |
included to maintain compatibility with sklearn pipelines. |
| 183 |
|
| 184 |
sample_cost : list or numpy.ndarray or None, shape=(n,), optional |
| 185 |
The cost of each item. If set, indicates that optimization should |
| 186 |
be performed with respect to a knapsack constraint. |
| 187 |
|
| 188 |
Returns |
| 189 |
------- |
| 190 |
self : BaseGraphSelection |
| 191 |
The fit step returns this selector object. |
| 192 |
""" |
| 193 |
|
| 194 |
allowed_dtypes = list, numpy.ndarray, csr_matrix |
| 195 |
|
| 196 |
if not isinstance(X, allowed_dtypes): |
| 197 |
raise ValueError("X must be either a list of lists, a 2D numpy " \ |
| 198 |
"array, or a scipy.sparse.csr_matrix.") |
| 199 |
if isinstance(X, numpy.ndarray) and len(X.shape) != 2: |
| 200 |
raise ValueError("X must have exactly two dimensions.") |
| 201 |
if numpy.min(X) < 0.0 and numpy.max(X) > 0.: |
| 202 |
raise ValueError("X cannot contain negative values or must be entirely "\ |
| 203 |
"negative values.") |
| 204 |
if self.n_samples > X.shape[0]: |
| 205 |
raise ValueError("Cannot select more examples than the number in" \ |
| 206 |
" the data set.") |
| 207 |
|
| 208 |
if not self.sparse: |
| 209 |
if X.dtype != 'float64': |
| 210 |
X = X.astype('float64') |
| 211 |
|
| 212 |
if isinstance(self.optimizer, str): |
| 213 |
optimizer = OPTIMIZERS[self.optimizer](function=self, |
| 214 |
verbose=self.verbose, random_state=self.random_state, |
| 215 |
**self.optimizer_kwds) |
| 216 |
else: |
| 217 |
optimizer = self.optimizer |
| 218 |
|
| 219 |
self._X = X if self._X is None else self._X |
| 220 |
self._initialize(X) |
| 221 |
|
| 222 |
if self.verbose: |
| 223 |
self.pbar = tqdm(total=self.n_samples, unit_scale=True) |
| 224 |
|
| 225 |
optimizer.select(X, self.n_samples, sample_cost=sample_cost) |
| 226 |
|
| 227 |
if self.verbose == True: |
| 228 |
self.pbar.close() |
| 229 |
|
| 230 |
self.ranking = numpy.array(self.ranking) |
| 231 |
self.gains = numpy.array(self.gains) |
| 232 |
return self |
| 233 |
|
| 234 |
def partial_fit(self, X, y=None, sample_weight=None, sample_cost=None): |
| 235 |
allowed_dtypes = list, numpy.ndarray, csr_matrix |
| 236 |
|
| 237 |
if not isinstance(X, allowed_dtypes): |
| 238 |
raise ValueError("X must be either a list of lists, a 2D numpy " \ |
| 239 |
"array, or a scipy.sparse.csr_matrix.") |
| 240 |
if isinstance(X, numpy.ndarray) and len(X.shape) != 2: |
| 241 |
raise ValueError("X must have exactly two dimensions.") |
| 242 |
|
| 243 |
if not self.sparse: |
| 244 |
if X.dtype != 'float64': |
| 245 |
X = X.astype('float64') |
| 246 |
|
| 247 |
if not isinstance(self.optimizer, SieveGreedy): |
| 248 |
self.optimizer = OPTIMIZERS['sieve'](function=self, |
| 249 |
verbose=self.verbose, random_state=self.random_state, |
| 250 |
**self.optimizer_kwds) |
| 251 |
|
| 252 |
self._X = X if self._X is None else self._X |
| 253 |
self._initialize(X) |
| 254 |
|
| 255 |
if self.verbose: |
| 256 |
self.pbar = tqdm(total=self.n_samples, unit_scale=True) |
| 257 |
|
| 258 |
self.optimizer.select(X, self.n_samples, sample_cost=sample_cost) |
| 259 |
|
| 260 |
if self.verbose == True: |
| 261 |
self.pbar.close() |
| 262 |
|
| 263 |
self.ranking = numpy.array(self.ranking) |
| 264 |
self.gains = numpy.array(self.gains) |
| 265 |
self._X = None |
| 266 |
return self |
| 267 |
|
| 268 |
def transform(self, X, y=None, sample_weight=None): |
| 269 |
"""Transform a data set to include only the selected examples. |
| 270 |
|
| 271 |
This method will return a selection of X and optionally selections |
| 272 |
of y and sample_weight. The default setting is to select items based |
| 273 |
on the ranking determined in the `fit` step with examples in the same |
| 274 |
order as that ranking. Optionally, the whole data set can be returned, |
| 275 |
with the weights corresponding to samples that were not selected set |
| 276 |
to 0. This setting can be controlled by setting `pipeline=True`. |
| 277 |
|
| 278 |
Parameters |
| 279 |
---------- |
| 280 |
X : list or numpy.ndarray, shape=(n, d) |
| 281 |
The data set to transform. Must be numeric. |
| 282 |
|
| 283 |
y : list or numpy.ndarray or None, shape=(n,), optional |
| 284 |
The labels to transform. If passed in this function will return |
| 285 |
both the data and the corresponding labels for the rows that have |
| 286 |
been selected. Default is None. |
| 287 |
|
| 288 |
sample_weight : list or numpy.ndarray or None, shape=(n,), optional |
| 289 |
The sample weights to transform. If passed in this function will |
| 290 |
return the selected labels (y) and the selected samples, even |
| 291 |
if no labels were passed in. Default is None. |
| 292 |
|
| 293 |
Returns |
| 294 |
------- |
| 295 |
X_subset : numpy.ndarray, shape=(n_samples, d) |
| 296 |
A subset of the data such that n_samples < n and n_samples is the |
| 297 |
integer provided at initialization. |
| 298 |
|
| 299 |
y_subset : numpy.ndarray, shape=(n_samples,), optional |
| 300 |
The labels that match with the indices of the samples if y is |
| 301 |
passed in. Only returned if passed in. |
| 302 |
|
| 303 |
sample_weight_subset : numpy.ndarray, shape=(n_samples,), optional |
| 304 |
The weight of each example. |
| 305 |
""" |
| 306 |
|
| 307 |
r = self.ranking |
| 308 |
|
| 309 |
if sample_weight is not None: |
| 310 |
if y is None: |
| 311 |
return X[r], None, sample_weight[r] |
| 312 |
else: |
| 313 |
return X[r], y[r], sample_weight[r] |
| 314 |
|
| 315 |
else: |
| 316 |
if y is None: |
| 317 |
return X[r] |
| 318 |
else: |
| 319 |
return X[r], y[r] |
| 320 |
|
| 321 |
def fit_transform(self, X, y=None, sample_weight=None, sample_cost=None): |
| 322 |
"""Run optimization and select a subset of examples. |
| 323 |
|
| 324 |
This method will first perform the `fit` step and then perform the |
| 325 |
`transform` step, returning a transformed data set. |
| 326 |
|
| 327 |
Parameters |
| 328 |
---------- |
| 329 |
X : list or numpy.ndarray, shape=(n, d) |
| 330 |
The data set to transform. Must be numeric. |
| 331 |
|
| 332 |
y : list or numpy.ndarray or None, shape=(n,), optional |
| 333 |
The labels to transform. If passed in this function will return |
| 334 |
both the data and the corresponding labels for the rows that have |
| 335 |
been selected. Default is None. |
| 336 |
|
| 337 |
sample_weight : list or numpy.ndarray or None, shape=(n,), optional |
| 338 |
The sample weights to transform. If passed in this function will |
| 339 |
return the selected labels (y) and the selected samples, even |
| 340 |
if no labels were passed in. Default is None. |
| 341 |
|
| 342 |
sample_cost : list or numpy.ndarray or None, shape=(n,), optional |
| 343 |
The cost of each item. If set, indicates that optimization should |
| 344 |
be performed with respect to a knapsack constraint. |
| 345 |
|
| 346 |
Returns |
| 347 |
------- |
| 348 |
X_subset : numpy.ndarray, shape=(n_samples, d) |
| 349 |
A subset of the data such that n_samples < n and n_samples is the |
| 350 |
integer provided at initialization. |
| 351 |
|
| 352 |
y_subset : numpy.ndarray, shape=(n_samples,), optional |
| 353 |
The labels that match with the indices of the samples if y is |
| 354 |
passed in. Only returned if passed in. |
| 355 |
|
| 356 |
sample_weight_subset : numpy.ndarray, shape=(n_samples,), optional |
| 357 |
The weight of each example. |
| 358 |
""" |
| 359 |
|
| 360 |
return self.fit(X, y=y, sample_weight=sample_weight, |
| 361 |
sample_cost=sample_cost).transform(X, y=y, |
| 362 |
sample_weight=sample_weight) |
| 363 |
|
| 364 |
def _initialize(self, X, idxs=None): |
| 365 |
n, d = X.shape |
| 366 |
self._X = X if self._X is None else self._X |
| 367 |
|
| 368 |
self.sparse = isinstance(X, csr_matrix) |
| 369 |
self.ranking = [] |
| 370 |
self.gains = [] |
| 371 |
self.subset = numpy.zeros((0, self._X.shape[1]), dtype='float64') |
| 372 |
|
| 373 |
self.current_values = numpy.zeros(d, dtype='float64') |
| 374 |
self.current_concave_values = numpy.zeros(d, dtype='float64') |
| 375 |
self.mask = numpy.zeros(n, dtype='int8') |
| 376 |
|
| 377 |
if self.initial_subset is not None: |
| 378 |
if self.initial_subset.ndim == 1: |
| 379 |
if self.initial_subset.dtype == bool: |
| 380 |
self.initial_subset = numpy.where(self.initial_subset == 1)[0] |
| 381 |
|
| 382 |
if len(self.initial_subset) + self.n_samples > X.shape[0]: |
| 383 |
raise ValueError("When using a mask for the initial subset" \ |
| 384 |
" must selected fewer than the size of the subset minus" \ |
| 385 |
" the initial subset size, i.e., n_samples < X.shape[0] -"\ |
| 386 |
" initial_subset.shape[0].") |
| 387 |
|
| 388 |
if self.initial_subset.max() > X.shape[0]: |
| 389 |
raise ValueError("When passing in an integer mask for the initial subset"\ |
| 390 |
" the maximum value cannot exceed the size of the data set.") |
| 391 |
elif self.initial_subset.min() < 0: |
| 392 |
raise ValueError("When passing in an integer mask for the initial subset"\ |
| 393 |
" the minimum value cannot be negative.") |
| 394 |
|
| 395 |
self.mask[self.initial_subset] = 1 |
| 396 |
|
| 397 |
self.idxs = numpy.where(self.mask == 0)[0] |
| 398 |
|
| 399 |
def _calculate_gains(self, X, idxs=None): |
| 400 |
raise NotImplementedError |
| 401 |
|
| 402 |
def _calculate_sieve_gains(self, X, thresholds, idxs): |
| 403 |
n = X.shape[0] |
| 404 |
d = X.shape[1] if self.reservoir is None else self.max_reservoir_size |
| 405 |
l = len(thresholds) |
| 406 |
|
| 407 |
if self.sieve_current_values_ is None: |
| 408 |
self.sieve_current_values_ = numpy.zeros((l, d), |
| 409 |
dtype='float64') |
| 410 |
self.sieve_selections_ = numpy.zeros((l, self.n_samples), |
| 411 |
dtype='int64') - 1 |
| 412 |
self.sieve_gains_ = numpy.zeros((l, self.n_samples), |
| 413 |
dtype='float64') - 1 |
| 414 |
self.sieve_n_selected_ = numpy.zeros(l, |
| 415 |
dtype='int64') |
| 416 |
self.sieve_total_gains_ = numpy.zeros(l, |
| 417 |
dtype='float64') |
| 418 |
self.sieve_subsets_ = numpy.zeros((l, self.n_samples, |
| 419 |
self._X.shape[1]), dtype='float64') |
| 420 |
else: |
| 421 |
j = l - self.sieve_current_values_.shape[0] |
| 422 |
if j > 0: |
| 423 |
self.sieve_current_values_ = numpy.vstack([ |
| 424 |
self.sieve_current_values_, numpy.zeros((j, d), |
| 425 |
dtype='float64')]) |
| 426 |
self.sieve_selections_ = numpy.vstack([ |
| 427 |
self.sieve_selections_, numpy.zeros((j, self.n_samples), |
| 428 |
dtype='int64') - 1]) |
| 429 |
self.sieve_gains_ = numpy.vstack([self.sieve_gains_, |
| 430 |
numpy.zeros((j, self.n_samples), dtype='float64')]) |
| 431 |
self.sieve_n_selected_ = numpy.concatenate([ |
| 432 |
self.sieve_n_selected_, numpy.zeros(j, dtype='int64')]) |
| 433 |
self.sieve_total_gains_ = numpy.concatenate([ |
| 434 |
self.sieve_total_gains_, numpy.zeros(j, dtype='float64')]) |
| 435 |
self.sieve_subsets_ = numpy.concatenate([self.sieve_subsets_, |
| 436 |
numpy.zeros((j, self.n_samples, self._X.shape[1]), |
| 437 |
dtype='float64')]) |
| 438 |
|
| 439 |
def _select_next(self, X, gain, idx): |
| 440 |
self.ranking.append(idx) |
| 441 |
self.gains.append(gain) |
| 442 |
self.mask[idx] = True |
| 443 |
self.idxs = numpy.where(self.mask == 0)[0] |
| 444 |
|
| 445 |
if self.sparse: |
| 446 |
X = self._X[idx:idx+1].toarray() |
| 447 |
else: |
| 448 |
X = self._X[idx:idx+1] |
| 449 |
|
| 450 |
if self.metric != 'precomputed': |
| 451 |
self.subset = numpy.concatenate([self.subset, X]) |
| 452 |
|
| 453 |
|
| 454 |
class BaseGraphSelection(BaseSelection): |
| 455 |
"""The base graph selection object. |
| 456 |
|
| 457 |
This object defines the structures that all submodular selection algorithms |
| 458 |
should follow if they operate on a graph, such as pairwise similarity |
| 459 |
measurements. All algorithms will have the same public methods and the same |
| 460 |
attributes. |
| 461 |
|
| 462 |
NOTE: All ~pairwise~ values in your data must be positive for these |
| 463 |
selection methods to work. |
| 464 |
|
| 465 |
This implementation allows users to pass in either their own symmetric |
| 466 |
square matrix of similarity values, or a data matrix as normal and a function |
| 467 |
that calculates these pairwise values. |
| 468 |
|
| 469 |
Parameters |
| 470 |
---------- |
| 471 |
n_samples : int |
| 472 |
The number of samples to return. |
| 473 |
|
| 474 |
metric : str |
| 475 |
The method for converting a data matrix into a square symmetric matrix |
| 476 |
of pairwise similarities. If a string, can be any of the metrics |
| 477 |
implemented in sklearn (see https://scikit-learn.org/stable/modules/ |
| 478 |
generated/sklearn.metrics.pairwise_distances.html), including |
| 479 |
"precomputed" if one has already generated a similarity matrix. Note |
| 480 |
that sklearn calculates distance matrices whereas apricot operates on |
| 481 |
similarity matrices, and so a distances.max() - distances transformation |
| 482 |
is performed on the resulting distances. For backcompatibility, |
| 483 |
'corr' will be read as 'correlation'. |
| 484 |
|
| 485 |
initial_subset : list, numpy.ndarray or None |
| 486 |
If provided, this should be a list of indices into the data matrix |
| 487 |
to use as the initial subset, or a group of examples that may not be |
| 488 |
in the provided data should beused as the initial subset. If indices, |
| 489 |
the provided array should be one-dimensional. If a group of examples, |
| 490 |
the data should be 2 dimensional. |
| 491 |
|
| 492 |
optimizer : string or optimizers.BaseOptimizer, optional |
| 493 |
The optimization approach to use for the selection. Default is |
| 494 |
'two-stage', which makes selections using the naive greedy algorithm |
| 495 |
initially and then switches to the lazy greedy algorithm. Must be |
| 496 |
one of |
| 497 |
|
| 498 |
'naive' : the naive greedy algorithm |
| 499 |
'lazy' : the lazy (or accelerated) greedy algorithm |
| 500 |
'approximate-lazy' : the approximate lazy greedy algorithm |
| 501 |
'two-stage' : starts with naive and switches to lazy |
| 502 |
'stochastic' : the stochastic greedy algorithm |
| 503 |
'greedi' : the GreeDi distributed algorithm |
| 504 |
'bidirectional' : the bidirectional greedy algorithm |
| 505 |
|
| 506 |
Default is 'naive'. |
| 507 |
|
| 508 |
optimizer_kwds : dict or None |
| 509 |
A dictionary of arguments to pass into the optimizer object. The keys |
| 510 |
of this dictionary should be the names of the parameters in the optimizer |
| 511 |
and the values in the dictionary should be the values that these |
| 512 |
parameters take. Default is None. |
| 513 |
|
| 514 |
n_neighbors : int or None |
| 515 |
When constructing a similarity matrix, the number of nearest neighbors |
| 516 |
whose similarity values will be kept. The result is a sparse similarity |
| 517 |
matrix which can significantly speed up computation at the cost of |
| 518 |
accuracy. Default is None. |
| 519 |
|
| 520 |
reservoir : numpy.ndarray or None |
| 521 |
The reservoir to use when calculating gains in the sieve greedy |
| 522 |
streaming optimization algorithm in the `partial_fit` method. |
| 523 |
Currently only used for graph-based functions. If a numpy array |
| 524 |
is passed in, it will be used as the reservoir. If None is passed in, |
| 525 |
will use reservoir sampling to collect a reservoir. Default is None. |
| 526 |
|
| 527 |
max_reservoir_size : int |
| 528 |
The maximum size that the reservoir can take. If a reservoir is passed |
| 529 |
in, this value is set to the size of that array. Default is 1000. |
| 530 |
|
| 531 |
n_jobs : int |
| 532 |
The number of threads to use when performing computation in parallel. |
| 533 |
Currently, this parameter is exposed but does not actually do anything. |
| 534 |
This will be fixed soon. |
| 535 |
|
| 536 |
random_state : int or RandomState or None, optional |
| 537 |
The random seed to use for the random selection process. Only used |
| 538 |
for stochastic greedy. |
| 539 |
|
| 540 |
verbose : bool |
| 541 |
Whether to print output during the selection process. |
| 542 |
|
| 543 |
Attributes |
| 544 |
---------- |
| 545 |
n_samples : int |
| 546 |
The number of samples to select. |
| 547 |
|
| 548 |
metric : callable |
| 549 |
A function that takes in a data matrix and converts it to a square |
| 550 |
symmetric matrix. |
| 551 |
|
| 552 |
ranking : numpy.array int |
| 553 |
The selected samples in the order of their gain. |
| 554 |
|
| 555 |
gains : numpy.array float |
| 556 |
The gain of each sample in the returned set when it was added to the |
| 557 |
growing subset. The first number corresponds to the gain of the first |
| 558 |
added sample, the second corresponds to the gain of the second added |
| 559 |
sample, and so forth. |
| 560 |
""" |
| 561 |
|
| 562 |
def __init__(self, n_samples, metric='euclidean', |
| 563 |
initial_subset=None, optimizer='two-stage', optimizer_kwds={}, |
| 564 |
n_neighbors=None, reservoir=None, max_reservoir_size=1000, |
| 565 |
n_jobs=1, random_state=None, verbose=False): |
| 566 |
|
| 567 |
super(BaseGraphSelection, self).__init__(n_samples=n_samples, |
| 568 |
initial_subset=initial_subset, optimizer=optimizer, |
| 569 |
optimizer_kwds=optimizer_kwds, reservoir=reservoir, |
| 570 |
max_reservoir_size=max_reservoir_size, n_jobs=n_jobs, |
| 571 |
random_state=random_state, verbose=verbose) |
| 572 |
|
| 573 |
self.metric = metric.replace("corr", "correlation") |
| 574 |
self.n_neighbors = n_neighbors |
| 575 |
|
| 576 |
|
| 577 |
def fit(self, X, y=None, sample_weight=None, sample_cost=None): |
| 578 |
"""Run submodular optimization to select a subset of examples. |
| 579 |
|
| 580 |
This method is a wrapper for the full submodular optimization process. |
| 581 |
It takes in some data set (and optionally labels that are ignored |
| 582 |
during this process) and selects `n_samples` from it in the greedy |
| 583 |
manner specified by the optimizer. |
| 584 |
|
| 585 |
This method will return the selector object itself, not the transformed |
| 586 |
data set. The `transform` method will then transform a data set to the |
| 587 |
selected points, or alternatively one can use the ranking stored in |
| 588 |
the `self.ranking` attribute. The `fit_transform` method will perform |
| 589 |
both optimization and selection and return the selected items. |
| 590 |
|
| 591 |
Parameters |
| 592 |
---------- |
| 593 |
X : list or numpy.ndarray, shape=(n, d) |
| 594 |
The data set to transform. Must be numeric. |
| 595 |
|
| 596 |
y : list or numpy.ndarray or None, shape=(n,), optional |
| 597 |
The labels to transform. If passed in this function will return |
| 598 |
both the data and th corresponding labels for the rows that have |
| 599 |
been selected. |
| 600 |
|
| 601 |
sample_weight : list or numpy.ndarray or None, shape=(n,), optional |
| 602 |
The weight of each example. Currently ignored in apricot but |
| 603 |
included to maintain compatibility with sklearn pipelines. |
| 604 |
|
| 605 |
sample_cost : list or numpy.ndarray or None, shape=(n,), optional |
| 606 |
The cost of each item. If set, indicates that optimization should |
| 607 |
be performed with respect to a knapsack constraint. |
| 608 |
|
| 609 |
Returns |
| 610 |
------- |
| 611 |
self : BaseGraphSelection |
| 612 |
The fit step returns this selector object. |
| 613 |
""" |
| 614 |
|
| 615 |
if isinstance(X, csr_matrix) and self.metric not in ("precomputed", "ignore"): |
| 616 |
raise ValueError("Must passed in a precomputed sparse " \ |
| 617 |
"similarity matrix or a dense feature matrix.") |
| 618 |
if self.metric == 'precomputed' and X.shape[0] != X.shape[1]: |
| 619 |
raise ValueError("Precomputed similarity matrices " \ |
| 620 |
"must be square and symmetric.") |
| 621 |
|
| 622 |
X_pairwise = _calculate_pairwise_distances(X, metric=self.metric, |
| 623 |
n_neighbors=self.n_neighbors) |
| 624 |
|
| 625 |
self._X = X |
| 626 |
return super(BaseGraphSelection, self).fit(X_pairwise, y=y, |
| 627 |
sample_weight=sample_weight, sample_cost=sample_cost) |
| 628 |
|
| 629 |
def partial_fit(self, X, y=None, sample_weight=None, sample_cost=None): |
| 630 |
if self.reservoir is None: |
| 631 |
self.reservoir = numpy.empty((self.max_reservoir_size, X.shape[1])) |
| 632 |
|
| 633 |
if self.update_reservoir_: |
| 634 |
for i in range(X.shape[0]): |
| 635 |
if self.reservoir_size < self.max_reservoir_size: |
| 636 |
self.reservoir[self.reservoir_size] = X[i] |
| 637 |
self.reservoir_size += 1 |
| 638 |
else: |
| 639 |
r = self.random_state.choice(self.n_seen_ + i) |
| 640 |
if r < self.max_reservoir_size: |
| 641 |
self.reservoir[r] = X[i] |
| 642 |
#self.current_values_[:, r] = 0. |
| 643 |
|
| 644 |
X_pairwise = _calculate_pairwise_distances(X, |
| 645 |
Y=self.reservoir[:self.reservoir_size], metric=self.metric) |
| 646 |
|
| 647 |
self._X = X |
| 648 |
super(BaseGraphSelection, self).partial_fit(X_pairwise, y=y, |
| 649 |
sample_weight=sample_weight, sample_cost=sample_cost) |
| 650 |
|
| 651 |
self.current_values = numpy.zeros(self.reservoir_size, |
| 652 |
dtype='float64') |
| 653 |
self.n_seen_ += X.shape[0] |
| 654 |
|
| 655 |
def _initialize(self, X_pairwise, idxs=None): |
| 656 |
super(BaseGraphSelection, self)._initialize(X_pairwise, idxs=idxs) |
| 657 |
|
| 658 |
def _calculate_gains(self, X_pairwise): |
| 659 |
super(BaseGraphSelection, self)._calculate_gains(X_pairwise) |
| 660 |
|
| 661 |
def _calculate_sieve_gains(self, X, thresholds, idxs): |
| 662 |
super(BaseGraphSelection, self)._calculate_sieve_gains(X, thresholds, |
| 663 |
idxs) |
| 664 |
|
| 665 |
def _select_next(self, X_pairwise, gain, idx): |
| 666 |
super(BaseGraphSelection, self)._select_next(X_pairwise, gain, idx) |