| 1 |
# facilityLocation.py |
| 2 |
# Author: Jacob Schreiber <[email protected]> |
| 3 |
|
| 4 |
import numpy |
| 5 |
|
| 6 |
from .base import BaseGraphSelection |
| 7 |
from ..optimizers import LazyGreedy |
| 8 |
from ..optimizers import ApproximateLazyGreedy |
| 9 |
from ..optimizers import SieveGreedy |
| 10 |
|
| 11 |
from tqdm import tqdm |
| 12 |
|
| 13 |
from numba import njit |
| 14 |
from numba import prange |
| 15 |
|
| 16 |
dtypes = 'void(float64[:,:], float64[:], float64[:], int64[:])' |
| 17 |
sdtypes = 'void(float64[:], int32[:], int32[:], float64[:], float64[:], int64[:])' |
| 18 |
sieve_dtypes = 'void(float64[:,:], int64, float64[:,:], int64[:,:],' \ |
| 19 |
'float64[:,:], float64[:], float64[:], int64[:], int64[:])' |
| 20 |
|
| 21 |
def calculate_gains(dtypes, parallel, fastmath, cache): |
| 22 |
@njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache) |
| 23 |
def calculate_gains_(X, gains, current_values, idxs): |
| 24 |
for i in prange(idxs.shape[0]): |
| 25 |
idx = idxs[i] |
| 26 |
gains[i] = numpy.maximum(X[idx], current_values).sum() |
| 27 |
return calculate_gains_ |
| 28 |
|
| 29 |
|
| 30 |
def calculate_gains_sparse(dtypes, parallel, fastmath, cache): |
| 31 |
@njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache) |
| 32 |
def calculate_gains_sparse_(X_data, X_indices, X_indptr, gains, current_values, idxs): |
| 33 |
for i in prange(idxs.shape[0]): |
| 34 |
idx = idxs[i] |
| 35 |
|
| 36 |
start = X_indptr[idx] |
| 37 |
end = X_indptr[idx+1] |
| 38 |
|
| 39 |
for j in range(start, end): |
| 40 |
k = X_indices[j] |
| 41 |
gains[i] += max(X_data[j], current_values[k]) - current_values[k] |
| 42 |
return calculate_gains_sparse_ |
| 43 |
|
| 44 |
|
| 45 |
def calculate_gains_sieve(dtypes, parallel, fastmath, cache): |
| 46 |
@njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache) |
| 47 |
def calculate_gains_sieve_(X, k, current_values, selections, gains, |
| 48 |
total_gains, max_values, n_selected, idxs): |
| 49 |
n, d = X.shape |
| 50 |
t = max_values.shape[0] |
| 51 |
|
| 52 |
for j in prange(t): |
| 53 |
for i in range(n): |
| 54 |
if n_selected[j] == k: |
| 55 |
break |
| 56 |
|
| 57 |
idx = idxs[i] |
| 58 |
threshold = (max_values[j] / 2. - total_gains[j]) / (k - n_selected[j]) |
| 59 |
maximum = numpy.maximum(X[i][:d], current_values[j][:d]) |
| 60 |
gain = maximum.mean() - total_gains[j] |
| 61 |
|
| 62 |
if gain > threshold: |
| 63 |
current_values[j][:d] = maximum |
| 64 |
total_gains[j] = maximum.mean() |
| 65 |
|
| 66 |
selections[j, n_selected[j]] = idx |
| 67 |
gains[j, n_selected[j]] = gain |
| 68 |
n_selected[j] += 1 |
| 69 |
|
| 70 |
return calculate_gains_sieve_ |
| 71 |
|
| 72 |
|
| 73 |
class FacilityLocationSelection(BaseGraphSelection): |
| 74 |
"""A selector based off a facility location submodular function. |
| 75 |
|
| 76 |
Facility location functions are general purpose submodular functions that, |
| 77 |
when maximized, choose examples that represent the space of the data well. |
| 78 |
The facility location function is based on maximizing the pairwise |
| 79 |
similarities between the points in the data set and their nearest chosen |
| 80 |
point. The similarity function can be specified by the user but must be |
| 81 |
non-negative where a higher value indicates more similar. |
| 82 |
|
| 83 |
.. note:: |
| 84 |
All ~pairwise~ values in your data must be non-negative for this |
| 85 |
selection to work. |
| 86 |
|
| 87 |
In many ways, optimizing a facility location function is simply a greedy |
| 88 |
version of k-medoids, where after the first few examples are selected, the |
| 89 |
subsequent ones are at the center of clusters. The function, like most |
| 90 |
graph-based functions, operates on a pairwise similarity matrix, and |
| 91 |
successively chooses examples that are similar to examples whose current |
| 92 |
most-similar example is still very dissimilar. Phrased another way, |
| 93 |
successively chosen examples are representative of underrepresented |
| 94 |
examples. |
| 95 |
|
| 96 |
The general form of a facility location function is |
| 97 |
|
| 98 |
.. math:: |
| 99 |
f(X, Y) = \\sum\\limits_{y in Y} \\max_{x in X} \\phi(x, y) |
| 100 |
|
| 101 |
where :math:`f` indicates the function, :math:`X` is a subset, :math:`Y` |
| 102 |
is the ground set, and :math:`\\phi` is the similarity measure between two |
| 103 |
examples. Like most graph-based functons, the facility location function |
| 104 |
requires access to the full ground set. |
| 105 |
|
| 106 |
This implementation allows users to pass in either their own symmetric |
| 107 |
square matrix of similarity values, or a data matrix as normal and a function |
| 108 |
that calculates these pairwise values. |
| 109 |
|
| 110 |
For more details, see https://las.inf.ethz.ch/files/krause12survey.pdf |
| 111 |
page 4. |
| 112 |
|
| 113 |
Parameters |
| 114 |
---------- |
| 115 |
n_samples : int |
| 116 |
The number of samples to return. |
| 117 |
|
| 118 |
metric : str, optional |
| 119 |
The method for converting a data matrix into a square symmetric matrix |
| 120 |
of pairwise similarities. If a string, can be any of the metrics |
| 121 |
implemented in sklearn (see |
| 122 |
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise_distances.html), |
| 123 |
including "precomputed" if one has already generated a similarity |
| 124 |
matrix. Note that sklearn calculates distance matrices whereas apricot |
| 125 |
operates on similarity matrices, and so a distances.max() - distances |
| 126 |
transformation is performed on the resulting distances. For |
| 127 |
backcompatibility, 'corr' will be read as 'correlation'. Default is |
| 128 |
'euclidean'. |
| 129 |
|
| 130 |
initial_subset : list, numpy.ndarray or None, optional |
| 131 |
If provided, this should be a list of indices into the data matrix |
| 132 |
to use as the initial subset, or a group of examples that may not be |
| 133 |
in the provided data should beused as the initial subset. If indices, |
| 134 |
the provided array should be one-dimensional. If a group of examples, |
| 135 |
the data should be 2 dimensional. Default is None. |
| 136 |
|
| 137 |
optimizer : string or optimizers.BaseOptimizer, optional |
| 138 |
The optimization approach to use for the selection. Default is |
| 139 |
'two-stage', which makes selections using the naive greedy algorithm |
| 140 |
initially and then switches to the lazy greedy algorithm. Must be |
| 141 |
one of |
| 142 |
|
| 143 |
'random' : randomly select elements (dummy optimizer) |
| 144 |
'modular' : approximate the function using its modular upper bound |
| 145 |
'naive' : the naive greedy algorithm |
| 146 |
'lazy' : the lazy (or accelerated) greedy algorithm |
| 147 |
'approximate-lazy' : the approximate lazy greedy algorithm |
| 148 |
'two-stage' : starts with naive and switches to lazy |
| 149 |
'stochastic' : the stochastic greedy algorithm |
| 150 |
'sample' : randomly take a subset and perform selection on that |
| 151 |
'greedi' : the GreeDi distributed algorithm |
| 152 |
'bidirectional' : the bidirectional greedy algorithm |
| 153 |
|
| 154 |
Default is 'two-stage'. |
| 155 |
|
| 156 |
optimizer_kwds : dict or None |
| 157 |
A dictionary of arguments to pass into the optimizer object. The keys |
| 158 |
of this dictionary should be the names of the parameters in the optimizer |
| 159 |
and the values in the dictionary should be the values that these |
| 160 |
parameters take. Default is None. |
| 161 |
|
| 162 |
n_neighbors : int or None |
| 163 |
When constructing a similarity matrix, the number of nearest neighbors |
| 164 |
whose similarity values will be kept. The result is a sparse similarity |
| 165 |
matrix which can significantly speed up computation at the cost of |
| 166 |
accuracy. Default is None. |
| 167 |
|
| 168 |
reservoir : numpy.ndarray or None |
| 169 |
The reservoir to use when calculating gains in the sieve greedy |
| 170 |
streaming optimization algorithm in the `partial_fit` method. |
| 171 |
Currently only used for graph-based functions. If a numpy array |
| 172 |
is passed in, it will be used as the reservoir. If None is passed in, |
| 173 |
will use reservoir sampling to collect a reservoir. Default is None. |
| 174 |
|
| 175 |
max_reservoir_size : int |
| 176 |
The maximum size that the reservoir can take. If a reservoir is passed |
| 177 |
in, this value is set to the size of that array. Default is 1000. |
| 178 |
|
| 179 |
n_jobs : int |
| 180 |
The number of threads to use when performing computation in parallel. |
| 181 |
Currently, this parameter is exposed but does not actually do anything. |
| 182 |
This will be fixed soon. |
| 183 |
|
| 184 |
random_state : int or RandomState or None, optional |
| 185 |
The random seed to use for the random selection process. Only used |
| 186 |
for stochastic greedy. |
| 187 |
|
| 188 |
verbose : bool |
| 189 |
Whether to print output during the selection process. |
| 190 |
|
| 191 |
Attributes |
| 192 |
---------- |
| 193 |
n_samples : int |
| 194 |
The number of samples to select. |
| 195 |
|
| 196 |
ranking : numpy.array int |
| 197 |
The selected samples in the order of their gain. |
| 198 |
|
| 199 |
gains : numpy.array float |
| 200 |
The gain of each sample in the returned set when it was added to the |
| 201 |
growing subset. The first number corresponds to the gain of the first |
| 202 |
added sample, the second corresponds to the gain of the second added |
| 203 |
sample, and so forth. |
| 204 |
""" |
| 205 |
|
| 206 |
def __init__(self, n_samples, metric='euclidean', |
| 207 |
initial_subset=None, optimizer='lazy', optimizer_kwds={}, |
| 208 |
n_neighbors=None, reservoir=None, max_reservoir_size=1000, |
| 209 |
n_jobs=1, random_state=None, verbose=False): |
| 210 |
|
| 211 |
super(FacilityLocationSelection, self).__init__(n_samples=n_samples, |
| 212 |
metric=metric, initial_subset=initial_subset, optimizer=optimizer, |
| 213 |
optimizer_kwds=optimizer_kwds, n_neighbors=n_neighbors, |
| 214 |
reservoir=reservoir, max_reservoir_size=max_reservoir_size, |
| 215 |
n_jobs=n_jobs, random_state=random_state, verbose=verbose) |
| 216 |
|
| 217 |
def fit(self, X, y=None, sample_weight=None, sample_cost=None): |
| 218 |
"""Run submodular optimization to select the examples. |
| 219 |
|
| 220 |
This method is a wrapper for the full submodular optimization process. |
| 221 |
It takes in some data set (and optionally labels that are ignored |
| 222 |
during this process) and selects `n_samples` from it in the greedy |
| 223 |
manner specified by the optimizer. |
| 224 |
|
| 225 |
This method will return the selector object itself, not the transformed |
| 226 |
data set. The `transform` method will then transform a data set to the |
| 227 |
selected points, or alternatively one can use the ranking stored in |
| 228 |
the `self.ranking` attribute. The `fit_transform` method will perform |
| 229 |
both optimization and selection and return the selected items. |
| 230 |
|
| 231 |
Parameters |
| 232 |
---------- |
| 233 |
X : list or numpy.ndarray, shape=(n, d) |
| 234 |
The data set to transform. Must be numeric. |
| 235 |
|
| 236 |
y : list or numpy.ndarray or None, shape=(n,), optional |
| 237 |
The labels to transform. If passed in this function will return |
| 238 |
both the data and th corresponding labels for the rows that have |
| 239 |
been selected. |
| 240 |
|
| 241 |
sample_weight : list or numpy.ndarray or None, shape=(n,), optional |
| 242 |
The weight of each example. Currently ignored in apricot but |
| 243 |
included to maintain compatibility with sklearn pipelines. |
| 244 |
|
| 245 |
sample_cost : list or numpy.ndarray or None, shape=(n,), optional |
| 246 |
The cost of each item. If set, indicates that optimization should |
| 247 |
be performed with respect to a knapsack constraint. |
| 248 |
|
| 249 |
Returns |
| 250 |
------- |
| 251 |
self : FacilityLocationSelection |
| 252 |
The fit step returns this selector object. |
| 253 |
""" |
| 254 |
|
| 255 |
return super(FacilityLocationSelection, self).fit(X, y=y, |
| 256 |
sample_weight=sample_weight, sample_cost=sample_cost) |
| 257 |
|
| 258 |
def _initialize(self, X_pairwise): |
| 259 |
super(FacilityLocationSelection, self)._initialize(X_pairwise) |
| 260 |
|
| 261 |
if self.initial_subset is None: |
| 262 |
pass |
| 263 |
elif self.initial_subset.ndim == 2: |
| 264 |
raise ValueError("When using facility location, the initial subset"\ |
| 265 |
" must be a one dimensional array of indices.") |
| 266 |
elif self.initial_subset.ndim == 1: |
| 267 |
if not self.sparse: |
| 268 |
for i in self.initial_subset: |
| 269 |
self.current_values = numpy.maximum(X_pairwise[i], |
| 270 |
self.current_values).astype('float64') |
| 271 |
else: |
| 272 |
for i in self.initial_subset: |
| 273 |
self.current_values = numpy.maximum( |
| 274 |
X_pairwise[i].toarray()[0], self.current_values).astype('float64') |
| 275 |
else: |
| 276 |
raise ValueError("The initial subset must be either a two dimensional" \ |
| 277 |
" matrix of examples or a one dimensional mask.") |
| 278 |
|
| 279 |
self.current_values_sum = self.current_values.sum() |
| 280 |
self.calculate_gains_ = calculate_gains_sparse if self.sparse else calculate_gains |
| 281 |
dtypes_ = sdtypes if self.sparse else dtypes |
| 282 |
|
| 283 |
if self.optimizer in (LazyGreedy, ApproximateLazyGreedy): |
| 284 |
self.calculate_gains_ = self.calculate_gains_(dtypes_, False, True, False) |
| 285 |
elif self.optimizer in ('lazy', 'approimate-lazy'): |
| 286 |
self.calculate_gains_ = self.calculate_gains_(dtypes_, False, True, False) |
| 287 |
else: |
| 288 |
self.calculate_gains_ = self.calculate_gains_(dtypes_, True, True, False) |
| 289 |
|
| 290 |
#calculate_sieve_gains_ = calculate_gains_sieve_sparse if self.sparse else calculate_gains_sieve |
| 291 |
#dtypes_ = sieve_sparse_dtypes if self.sparse else sieve_dtypes |
| 292 |
#self.calculate_sieve_gains_ = calculate_sieve_gains_(dtypes_, |
| 293 |
# True, True, False) |
| 294 |
|
| 295 |
self.calculate_sieve_gains_ = calculate_gains_sieve(sieve_dtypes, |
| 296 |
True, True, False) |
| 297 |
|
| 298 |
def _calculate_gains(self, X_pairwise, idxs=None): |
| 299 |
idxs = idxs if idxs is not None else self.idxs |
| 300 |
gains = numpy.zeros(idxs.shape[0], dtype='float64') |
| 301 |
|
| 302 |
if self.sparse: |
| 303 |
self.calculate_gains_(X_pairwise.data, X_pairwise.indices, |
| 304 |
X_pairwise.indptr, gains, self.current_values, idxs) |
| 305 |
else: |
| 306 |
self.calculate_gains_(X_pairwise, gains, self.current_values, idxs) |
| 307 |
gains -= self.current_values_sum |
| 308 |
|
| 309 |
return gains |
| 310 |
|
| 311 |
def _calculate_sieve_gains(self, X_pairwise, thresholds, idxs): |
| 312 |
"""This function will update the internal statistics from a stream. |
| 313 |
|
| 314 |
This function will update the various internal statistics that are a |
| 315 |
part of the sieve algorithm for streaming submodular optimization. This |
| 316 |
function does not directly return gains but it updates the values |
| 317 |
used by a streaming optimizer. |
| 318 |
""" |
| 319 |
|
| 320 |
super(FacilityLocationSelection, self)._calculate_sieve_gains( |
| 321 |
X_pairwise,thresholds, idxs) |
| 322 |
|
| 323 |
if self.sparse: |
| 324 |
self.calculate_sieve_gains_(X_pairwise.data, X_pairwise.indices, |
| 325 |
X_pairwise.indptr, self.n_samples, self.sieve_current_values_, |
| 326 |
self.sieve_selections_, self.sieve_gains_, |
| 327 |
self.sieve_total_gains_, thresholds, |
| 328 |
self.sieve_n_selected_, idxs) |
| 329 |
else: |
| 330 |
self.calculate_sieve_gains_(X_pairwise, self.n_samples, |
| 331 |
self.sieve_current_values_, self.sieve_selections_, |
| 332 |
self.sieve_gains_, self.sieve_total_gains_, thresholds, |
| 333 |
self.sieve_n_selected_, idxs) |
| 334 |
|
| 335 |
def _select_next(self, X_pairwise, gain, idx): |
| 336 |
"""This function will add the given item to the selected set.""" |
| 337 |
|
| 338 |
if self.sparse: |
| 339 |
self.current_values = numpy.maximum( |
| 340 |
X_pairwise.toarray()[0], self.current_values) |
| 341 |
else: |
| 342 |
self.current_values = numpy.maximum(X_pairwise, |
| 343 |
self.current_values) |
| 344 |
|
| 345 |
self.current_values_sum = self.current_values.sum() |
| 346 |
|
| 347 |
super(FacilityLocationSelection, self)._select_next( |
| 348 |
X_pairwise, gain, idx) |