| 1 |
# saturatedCoverage.py |
| 2 |
# Author: Jacob Schreiber <[email protected]> |
| 3 |
|
| 4 |
import numpy |
| 5 |
|
| 6 |
from .base import BaseGraphSelection |
| 7 |
|
| 8 |
from tqdm import tqdm |
| 9 |
|
| 10 |
from numba import njit |
| 11 |
from numba import prange |
| 12 |
|
| 13 |
from scipy.sparse import csr_matrix |
| 14 |
|
| 15 |
dtypes = 'void(float64[:,:], float64[:], float64[:], float64[:], int64[:])' |
| 16 |
sdtypes = 'void(float64[:], int32[:], int32[:], float64[:], float64[:], float64[:], int64[:])' |
| 17 |
|
| 18 |
@njit(dtypes, nogil=True, parallel=True) |
| 19 |
def select_next(X, gains, current_values, max_values, idxs): |
| 20 |
for i in prange(idxs.shape[0]): |
| 21 |
idx = idxs[i] |
| 22 |
gains[i] = numpy.minimum(current_values + X[idx], max_values).sum() |
| 23 |
|
| 24 |
@njit(sdtypes, nogil=True, parallel=True) |
| 25 |
def select_next_sparse(X_data, X_indices, X_indptr, gains, current_values, max_values, idxs): |
| 26 |
for i in prange(idxs.shape[0]): |
| 27 |
idx = idxs[i] |
| 28 |
|
| 29 |
start = X_indptr[idx] |
| 30 |
end = X_indptr[idx+1] |
| 31 |
|
| 32 |
for j in range(start, end): |
| 33 |
k = X_indices[j] |
| 34 |
gains[i] += min(X_data[j] + current_values[k], max_values[k]) - current_values[k] |
| 35 |
|
| 36 |
class SaturatedCoverageSelection(BaseGraphSelection): |
| 37 |
"""A saturated coverage submodular selection algorithm. |
| 38 |
|
| 39 |
The saturated coverage function is a graph-based function where the gain |
| 40 |
is the sum of the similarities between the candidate example and the |
| 41 |
entire ground set up until a certain point. Essentially, each example in |
| 42 |
the ground set contributes to the overall function until some prespecified |
| 43 |
level of "coverage" is met. Once an example is similar enough to the |
| 44 |
selected examples, it stops contributing to the function. |
| 45 |
|
| 46 |
.. note:: |
| 47 |
All ~pairwise~ values in your data must be positive for this |
| 48 |
selection to work. |
| 49 |
|
| 50 |
The general form of a saturated coverage function is |
| 51 |
|
| 52 |
.. math:: |
| 53 |
f(X, V) = \\sum_{v \\in V} \\min\\{\\sum_{x \\in X} \\phi(x, v), \\alpha\\} |
| 54 |
|
| 55 |
where :math:`f` indicates the function, :math:`X` is a subset, :math:`V` |
| 56 |
is the ground set, and :math:`\\phi` is the similarity measure between two |
| 57 |
examples, and :math:`\\alpha` is a parameter that, for each point in the |
| 58 |
ground set, specifies the maximum similarity that each example can have |
| 59 |
to the selected set (the saturation). Like most graph-based functons, |
| 60 |
the saturated coverage function requires access to the full ground set. |
| 61 |
|
| 62 |
Parameters |
| 63 |
---------- |
| 64 |
n_samples : int |
| 65 |
The number of samples to return. |
| 66 |
|
| 67 |
metric : str, optional |
| 68 |
The method for converting a data matrix into a square symmetric matrix |
| 69 |
of pairwise similarities. If a string, can be any of the metrics |
| 70 |
implemented in sklearn (see |
| 71 |
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise_distances.html), |
| 72 |
including "precomputed" if one has already generated a similarity |
| 73 |
matrix. Note that sklearn calculates distance matrices whereas apricot |
| 74 |
operates on similarity matrices, and so a distances.max() - distances |
| 75 |
transformation is performed on the resulting distances. For |
| 76 |
backcompatibility, 'corr' will be read as 'correlation'. Default is |
| 77 |
'euclidean'. |
| 78 |
|
| 79 |
alpha : float |
| 80 |
The threshold at which to saturate. Larger values of alpha are closer |
| 81 |
to a modular function and smaller values of alpha are closer to all |
| 82 |
examples providing the same, small, gain. Default is 0.1. |
| 83 |
|
| 84 |
initial_subset : list, numpy.ndarray or None, optional |
| 85 |
If provided, this should be a list of indices into the data matrix |
| 86 |
to use as the initial subset, or a group of examples that may not be |
| 87 |
in the provided data should beused as the initial subset. If indices, |
| 88 |
the provided array should be one-dimensional. If a group of examples, |
| 89 |
the data should be 2 dimensional. Default is None. |
| 90 |
|
| 91 |
optimizer : string or optimizers.BaseOptimizer, optional |
| 92 |
The optimization approach to use for the selection. Default is |
| 93 |
'two-stage', which makes selections using the naive greedy algorithm |
| 94 |
initially and then switches to the lazy greedy algorithm. Must be |
| 95 |
one of |
| 96 |
|
| 97 |
'random' : randomly select elements (dummy optimizer) |
| 98 |
'modular' : approximate the function using its modular upper bound |
| 99 |
'naive' : the naive greedy algorithm |
| 100 |
'lazy' : the lazy (or accelerated) greedy algorithm |
| 101 |
'approximate-lazy' : the approximate lazy greedy algorithm |
| 102 |
'two-stage' : starts with naive and switches to lazy |
| 103 |
'stochastic' : the stochastic greedy algorithm |
| 104 |
'sample' : randomly take a subset and perform selection on that |
| 105 |
'greedi' : the GreeDi distributed algorithm |
| 106 |
'bidirectional' : the bidirectional greedy algorithm |
| 107 |
|
| 108 |
Default is 'two-stage'. |
| 109 |
|
| 110 |
optimizer_kwds : dict or None |
| 111 |
A dictionary of arguments to pass into the optimizer object. The keys |
| 112 |
of this dictionary should be the names of the parameters in the optimizer |
| 113 |
and the values in the dictionary should be the values that these |
| 114 |
parameters take. Default is None. |
| 115 |
|
| 116 |
n_neighbors : int or None |
| 117 |
When constructing a similarity matrix, the number of nearest neighbors |
| 118 |
whose similarity values will be kept. The result is a sparse similarity |
| 119 |
matrix which can significantly speed up computation at the cost of |
| 120 |
accuracy. Default is None. |
| 121 |
|
| 122 |
reservoir : numpy.ndarray or None |
| 123 |
The reservoir to use when calculating gains in the sieve greedy |
| 124 |
streaming optimization algorithm in the `partial_fit` method. |
| 125 |
Currently only used for graph-based functions. If a numpy array |
| 126 |
is passed in, it will be used as the reservoir. If None is passed in, |
| 127 |
will use reservoir sampling to collect a reservoir. Default is None. |
| 128 |
|
| 129 |
max_reservoir_size : int |
| 130 |
The maximum size that the reservoir can take. If a reservoir is passed |
| 131 |
in, this value is set to the size of that array. Default is 1000. |
| 132 |
|
| 133 |
n_jobs : int |
| 134 |
The number of threads to use when performing computation in parallel. |
| 135 |
Currently, this parameter is exposed but does not actually do anything. |
| 136 |
This will be fixed soon. |
| 137 |
|
| 138 |
random_state : int or RandomState or None, optional |
| 139 |
The random seed to use for the random selection process. Only used |
| 140 |
for stochastic greedy. |
| 141 |
|
| 142 |
verbose : bool |
| 143 |
Whether to print output during the selection process. |
| 144 |
|
| 145 |
Attributes |
| 146 |
---------- |
| 147 |
n_samples : int |
| 148 |
The number of samples to select. |
| 149 |
|
| 150 |
pairwise_func : callable |
| 151 |
A function that takes in a data matrix and converts it to a square |
| 152 |
symmetric matrix. |
| 153 |
|
| 154 |
ranking : numpy.array int |
| 155 |
The selected samples in the order of their gain. |
| 156 |
|
| 157 |
gains : numpy.array float |
| 158 |
The gain of each sample in the returned set when it was added to the |
| 159 |
growing subset. The first number corresponds to the gain of the first |
| 160 |
added sample, the second corresponds to the gain of the second added |
| 161 |
sample, and so forth. |
| 162 |
""" |
| 163 |
|
| 164 |
def __init__(self, n_samples=10, metric='euclidean', alpha=0.1, |
| 165 |
initial_subset=None, optimizer='two-stage', n_neighbors=None, n_jobs=1, |
| 166 |
random_state=None, reservoir=None, max_reservoir_size=None, |
| 167 |
optimizer_kwds={}, verbose=False): |
| 168 |
self.alpha = alpha |
| 169 |
|
| 170 |
super(SaturatedCoverageSelection, self).__init__(n_samples=n_samples, |
| 171 |
metric=metric,initial_subset=initial_subset, optimizer=optimizer, |
| 172 |
optimizer_kwds=optimizer_kwds, n_neighbors=n_neighbors, |
| 173 |
reservoir=reservoir, max_reservoir_size=max_reservoir_size, |
| 174 |
n_jobs=n_jobs, random_state=random_state, verbose=verbose) |
| 175 |
|
| 176 |
def fit(self, X, y=None, sample_weight=None, sample_cost=None): |
| 177 |
"""Run submodular optimization to select the examples. |
| 178 |
|
| 179 |
This method is a wrapper for the full submodular optimization process. |
| 180 |
It takes in some data set (and optionally labels that are ignored |
| 181 |
during this process) and selects `n_samples` from it in the greedy |
| 182 |
manner specified by the optimizer. |
| 183 |
|
| 184 |
This method will return the selector object itself, not the transformed |
| 185 |
data set. The `transform` method will then transform a data set to the |
| 186 |
selected points, or alternatively one can use the ranking stored in |
| 187 |
the `self.ranking` attribute. The `fit_transform` method will perform |
| 188 |
both optimization and selection and return the selected items. |
| 189 |
|
| 190 |
Parameters |
| 191 |
---------- |
| 192 |
X : list or numpy.ndarray, shape=(n, d) |
| 193 |
The data set to transform. Must be numeric. |
| 194 |
|
| 195 |
y : list or numpy.ndarray or None, shape=(n,), optional |
| 196 |
The labels to transform. If passed in this function will return |
| 197 |
both the data and th corresponding labels for the rows that have |
| 198 |
been selected. |
| 199 |
|
| 200 |
sample_weight : list or numpy.ndarray or None, shape=(n,), optional |
| 201 |
The weight of each example. Currently ignored in apricot but |
| 202 |
included to maintain compatibility with sklearn pipelines. |
| 203 |
|
| 204 |
sample_cost : list or numpy.ndarray or None, shape=(n,), optional |
| 205 |
The cost of each item. If set, indicates that optimization should |
| 206 |
be performed with respect to a knapsack constraint. |
| 207 |
|
| 208 |
Returns |
| 209 |
------- |
| 210 |
self : SaturatedCoverageSelection |
| 211 |
The fit step returns this selector object. |
| 212 |
""" |
| 213 |
|
| 214 |
return super(SaturatedCoverageSelection, self).fit(X, y=y, |
| 215 |
sample_weight=sample_weight, sample_cost=sample_cost) |
| 216 |
|
| 217 |
def _initialize(self, X_pairwise): |
| 218 |
super(SaturatedCoverageSelection, self)._initialize(X_pairwise) |
| 219 |
|
| 220 |
if self.sparse: |
| 221 |
self.max_values = self.alpha * numpy.array( |
| 222 |
X_pairwise.sum(axis=1))[:,0] |
| 223 |
else: |
| 224 |
self.max_values = self.alpha * X_pairwise.sum(axis=1) |
| 225 |
|
| 226 |
if self.initial_subset is None: |
| 227 |
return |
| 228 |
elif self.initial_subset.ndim == 2: |
| 229 |
raise ValueError("When using saturated coverage, the initial subset"\ |
| 230 |
" must be a one dimensional array of indices.") |
| 231 |
elif self.initial_subset.ndim == 1: |
| 232 |
if not self.sparse: |
| 233 |
for i in self.initial_subset: |
| 234 |
self.current_values = numpy.minimum(self.max_values, |
| 235 |
self.current_values + X_pairwise[i]) |
| 236 |
else: |
| 237 |
for i in self.initial_subset: |
| 238 |
self.current_values = numpy.minimum(self.max_values, |
| 239 |
self.current_values + X_pairwise[i].toaray()[0]) |
| 240 |
else: |
| 241 |
raise ValueError("The initial subset must be either a two dimensional" \ |
| 242 |
" matrix of examples or a one dimensional mask.") |
| 243 |
|
| 244 |
def _calculate_gains(self, X_pairwise, idxs=None): |
| 245 |
idxs = idxs if idxs is not None else self.idxs |
| 246 |
gains = numpy.zeros(idxs.shape[0], dtype='float64') |
| 247 |
|
| 248 |
if self.sparse: |
| 249 |
select_next_sparse(X_pairwise.data, |
| 250 |
X_pairwise.indices, X_pairwise.indptr, gains, |
| 251 |
self.current_values, self.max_values, idxs) |
| 252 |
else: |
| 253 |
select_next(X_pairwise, gains, self.current_values, |
| 254 |
self.max_values, idxs) |
| 255 |
gains -= self.current_values.sum() |
| 256 |
|
| 257 |
return gains |
| 258 |
|
| 259 |
def _select_next(self, X_pairwise, gain, idx): |
| 260 |
"""This function will add the given item to the selected set.""" |
| 261 |
|
| 262 |
if self.sparse: |
| 263 |
self.current_values = numpy.minimum(self.max_values, |
| 264 |
X_pairwise.toarray()[0] + self.current_values) |
| 265 |
else: |
| 266 |
self.current_values = numpy.minimum(self.max_values, |
| 267 |
self.current_values + X_pairwise) |
| 268 |
|
| 269 |
super(SaturatedCoverageSelection, self)._select_next( |
| 270 |
X_pairwise, gain, idx) |