| 1 |
# maxCoverage.py |
| 2 |
# Author: Jacob Schreiber <[email protected]> |
| 3 |
|
| 4 |
import numpy |
| 5 |
|
| 6 |
from .base import BaseSelection |
| 7 |
from ..optimizers import LazyGreedy |
| 8 |
from ..optimizers import ApproximateLazyGreedy |
| 9 |
from ..optimizers import SieveGreedy |
| 10 |
|
| 11 |
from numba import njit |
| 12 |
from numba import prange |
| 13 |
|
| 14 |
dtypes = 'void(float64[:,:], float64[:], float64[:], float64, int64[:])' |
| 15 |
sdtypes = 'void(float64[:], int32[:], int32[:], float64[:], float64[:], float64, int64[:])' |
| 16 |
sieve_dtypes = 'void(float64[:,:], int64, float64[:,:], int64[:,:],' \ |
| 17 |
'float64[:,:], float64[:], float64[:], int64[:], float64, int64[:])' |
| 18 |
sieve_sparse_dtypes = 'void(float64[:], int32[:], int32[:], int64,' \ |
| 19 |
'float64[:,:], int64[:,:], float64[:,:], float64[:], float64[:],' \ |
| 20 |
'int64[:], float64, int64[:])' |
| 21 |
|
| 22 |
def calculate_gains(dtypes, parallel, fastmath, cache): |
| 23 |
@njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache) |
| 24 |
def calculate_gains_(X, gains, current_values, threshold, idxs): |
| 25 |
for i in prange(idxs.shape[0]): |
| 26 |
idx = idxs[i] |
| 27 |
gains[i] = numpy.fmin(current_values + X[idx], threshold).sum() |
| 28 |
return calculate_gains_ |
| 29 |
|
| 30 |
|
| 31 |
def calculate_gains_sparse(dtypes, parallel, fastmath, cache): |
| 32 |
@njit(sdtypes, parallel=parallel, fastmath=fastmath, cache=cache) |
| 33 |
def calculate_gains_sparse_(X_data, X_indices, X_indptr, gains, |
| 34 |
current_values, threshold, idxs): |
| 35 |
for i in prange(idxs.shape[0]): |
| 36 |
idx = idxs[i] |
| 37 |
start = X_indptr[idx] |
| 38 |
end = X_indptr[idx+1] |
| 39 |
|
| 40 |
for j in range(start, end): |
| 41 |
k = X_indices[j] |
| 42 |
gains[i] += min(X_data[j] + current_values[k], threshold) - current_values[k] |
| 43 |
return calculate_gains_sparse_ |
| 44 |
|
| 45 |
|
| 46 |
def calculate_gains_sieve(dtypes, parallel, fastmath, cache): |
| 47 |
@njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache) |
| 48 |
def calculate_gains_sieve_(X, k, current_values, selections, gains, |
| 49 |
total_gains, max_values, n_selected, thresh, idxs): |
| 50 |
n = X.shape[0] |
| 51 |
d = max_values.shape[0] |
| 52 |
|
| 53 |
for j in prange(d): |
| 54 |
for i in range(n): |
| 55 |
if n_selected[j] == k: |
| 56 |
break |
| 57 |
|
| 58 |
idx = idxs[i] |
| 59 |
threshold = (max_values[j] / 2. - total_gains[j]) / (k - n_selected[j]) |
| 60 |
gain = (numpy.fmin(current_values[j] + X[i], thresh).sum() - |
| 61 |
total_gains[j]) |
| 62 |
|
| 63 |
if gain > threshold: |
| 64 |
current_values[j] += X[i] |
| 65 |
total_gains[j] += gain |
| 66 |
|
| 67 |
selections[j, n_selected[j]] = idx |
| 68 |
gains[j, n_selected[j]] = gain |
| 69 |
n_selected[j] += 1 |
| 70 |
|
| 71 |
return calculate_gains_sieve_ |
| 72 |
|
| 73 |
|
| 74 |
def calculate_gains_sieve_sparse(dtypes, parallel, fastmath, cache): |
| 75 |
@njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache) |
| 76 |
def calculate_gains_sieve_sparse_(X_data, X_indices, X_indptr, k, |
| 77 |
current_values, selections, gains, total_gains, max_values, |
| 78 |
n_selected, thresh, idxs): |
| 79 |
d = max_values.shape[0] |
| 80 |
|
| 81 |
for j in prange(d): |
| 82 |
for i in range(idxs.shape[0]): |
| 83 |
if n_selected[j] == k: |
| 84 |
break |
| 85 |
|
| 86 |
idx = idxs[i] |
| 87 |
start = X_indptr[i] |
| 88 |
end = X_indptr[i+1] |
| 89 |
threshold = (max_values[j] / 2. - total_gains[j]) / (k - n_selected[j]) |
| 90 |
|
| 91 |
gain = 0.0 |
| 92 |
for l in range(start, end): |
| 93 |
m = X_indices[l] |
| 94 |
gain += (min(current_values[j, m] + X_data[l], thresh) - |
| 95 |
current_values[j, m]) |
| 96 |
|
| 97 |
if gain > threshold: |
| 98 |
for l in range(start, end): |
| 99 |
m = X_indices[l] |
| 100 |
current_values[j, m] = min(current_values[j, m] + X_data[l], |
| 101 |
thresh) |
| 102 |
|
| 103 |
total_gains[j] += gain |
| 104 |
selections[j, n_selected[j]] = idx |
| 105 |
gains[j, n_selected[j]] = gain |
| 106 |
n_selected[j] += 1 |
| 107 |
|
| 108 |
return calculate_gains_sieve_sparse_ |
| 109 |
|
| 110 |
class MaxCoverageSelection(BaseSelection): |
| 111 |
"""A selector based off a coverage function. |
| 112 |
|
| 113 |
Maximum coverage functions aim to maximize the number of features that |
| 114 |
have a non-zero element in at least one selected example---there is no |
| 115 |
marginal benefit to observing a variable in two examples. If each variable |
| 116 |
is thought to be an item in a set, and the data is a binary matrix where a |
| 117 |
1 indicates the item is present in the example and 0 indicates it is not, |
| 118 |
optimizing a maximum coverage function is a solution to the set coverage |
| 119 |
problem. These functions are useful when the space of variables is massive |
| 120 |
and each example only sees a small subset of them, which is a common |
| 121 |
situation when analyzing text data when the variables are words. The |
| 122 |
maximum coverage function is an instance of a feature-based function |
| 123 |
when the concave function is minimum. |
| 124 |
|
| 125 |
.. note:: |
| 126 |
All values in your data must be binary for this selection to work. |
| 127 |
|
| 128 |
The general form of a coverage function is: |
| 129 |
|
| 130 |
.. math:: |
| 131 |
f(X) = \\sum\\limits_{d=1}^{D} \\min \\left( \\sum\\limits_{n=1}^{N} X_{i, d}, 1 \\right) |
| 132 |
|
| 133 |
where :math:`f` indicates the function that operates on a subset :math:`X` |
| 134 |
that has :math:`N` examples and :math:`D` dimensions. Importantly, |
| 135 |
:math:`X` is the subset and not the ground set, meaning that the time it |
| 136 |
takes to evaluate this function is proportional only to the size of the |
| 137 |
selected subset and not the size of the full data set, like it is for |
| 138 |
graph-based functions. |
| 139 |
|
| 140 |
See https://www2.cs.duke.edu/courses/fall17/compsci632/scribing/scribe2.pdf |
| 141 |
where the problem is described as maximum coverage. |
| 142 |
|
| 143 |
Parameters |
| 144 |
---------- |
| 145 |
n_samples : int |
| 146 |
The number of examples to return. |
| 147 |
|
| 148 |
initial_subset : list, numpy.ndarray or None |
| 149 |
If provided, this should be a list of indices into the data matrix |
| 150 |
to use as the initial subset, or a group of examples that may not be |
| 151 |
in the provided data should beused as the initial subset. If indices, |
| 152 |
the provided array should be one-dimensional. If a group of examples, |
| 153 |
the data should be 2 dimensional. |
| 154 |
|
| 155 |
optimizer : string or optimizers.BaseOptimizer, optional |
| 156 |
The optimization approach to use for the selection. Default is |
| 157 |
'two-stage', which makes selections using the naive greedy algorithm |
| 158 |
initially and then switches to the lazy greedy algorithm. Must be |
| 159 |
one of |
| 160 |
|
| 161 |
'random' : randomly select elements (dummy optimizer) |
| 162 |
'modular' : approximate the function using its modular upper bound |
| 163 |
'naive' : the naive greedy algorithm |
| 164 |
'lazy' : the lazy (or accelerated) greedy algorithm |
| 165 |
'approximate-lazy' : the approximate lazy greedy algorithm |
| 166 |
'two-stage' : starts with naive and switches to lazy |
| 167 |
'stochastic' : the stochastic greedy algorithm |
| 168 |
'sample' : randomly take a subset and perform selection on that |
| 169 |
'greedi' : the GreeDi distributed algorithm |
| 170 |
'bidirectional' : the bidirectional greedy algorithm |
| 171 |
|
| 172 |
Default is 'two-stage'. |
| 173 |
|
| 174 |
optimizer_kwds : dict, optional |
| 175 |
Arguments to pass into the optimizer object upon initialization. |
| 176 |
Default is {}. |
| 177 |
|
| 178 |
n_jobs : int, optional |
| 179 |
The number of cores to use for processing. This value is multiplied |
| 180 |
by 2 when used to set the number of threads. If set to -1, use all |
| 181 |
cores and threads. Default is -1. |
| 182 |
|
| 183 |
random_state : int or RandomState or None, optional |
| 184 |
The random seed to use for the random selection process. Only used |
| 185 |
for stochastic greedy. |
| 186 |
|
| 187 |
verbose : bool |
| 188 |
Whether to print output during the selection process. |
| 189 |
|
| 190 |
Attributes |
| 191 |
---------- |
| 192 |
n_samples : int |
| 193 |
The number of samples to select. |
| 194 |
|
| 195 |
ranking : numpy.array int |
| 196 |
The selected samples in the order of their gain with the first number in |
| 197 |
the ranking corresponding to the index of the first sample that was |
| 198 |
selected by the greedy procedure. |
| 199 |
|
| 200 |
gains : numpy.array float |
| 201 |
The gain of each sample in the returned set when it was added to the |
| 202 |
growing subset. The first number corresponds to the gain of the first |
| 203 |
added sample, the second corresponds to the gain of the second added |
| 204 |
sample, and so forth. |
| 205 |
""" |
| 206 |
|
| 207 |
def __init__(self, n_samples, threshold=1.0, initial_subset=None, |
| 208 |
optimizer='two-stage', optimizer_kwds={}, n_jobs=1, random_state=None, |
| 209 |
verbose=False): |
| 210 |
self.threshold = threshold |
| 211 |
|
| 212 |
super(MaxCoverageSelection, self).__init__(n_samples=n_samples, |
| 213 |
initial_subset=initial_subset, optimizer=optimizer, |
| 214 |
optimizer_kwds=optimizer_kwds, n_jobs=n_jobs, |
| 215 |
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 : FeatureBasedSelection |
| 252 |
The fit step returns this selector object. |
| 253 |
""" |
| 254 |
|
| 255 |
return super(MaxCoverageSelection, self).fit(X, y=y, |
| 256 |
sample_weight=sample_weight, sample_cost=sample_cost) |
| 257 |
|
| 258 |
def _initialize(self, X): |
| 259 |
super(MaxCoverageSelection, self)._initialize(X) |
| 260 |
|
| 261 |
if self.initial_subset is None: |
| 262 |
self.current_values = numpy.zeros(X.shape[1], dtype='float64') |
| 263 |
elif self.initial_subset.ndim == 2: |
| 264 |
self.current_values = numpy.fmin(self.threshold, |
| 265 |
self.initial_subset.sum(axis=0).astype('float64')) |
| 266 |
elif self.initial_subset.ndim == 1: |
| 267 |
self.current_values = numpy.fmin(self.threshold, |
| 268 |
X[self.initial_subset].sum(axis=0).astype('float64')) |
| 269 |
else: |
| 270 |
raise ValueError("The initial subset must be either a two dimensional" \ |
| 271 |
" matrix of examples or a one dimensional mask.") |
| 272 |
|
| 273 |
self.current_values_sum = self.current_values.sum() |
| 274 |
|
| 275 |
calculate_gains_ = calculate_gains_sparse if self.sparse else calculate_gains |
| 276 |
dtypes_ = sdtypes if self.sparse else dtypes |
| 277 |
|
| 278 |
if self.optimizer in (LazyGreedy, ApproximateLazyGreedy): |
| 279 |
self.calculate_gains_ = calculate_gains_(dtypes_, False, True, False) |
| 280 |
elif self.optimizer in ('lazy', 'approimate-lazy'): |
| 281 |
self.calculate_gains_ = calculate_gains_(dtypes_, False, True, False) |
| 282 |
else: |
| 283 |
self.calculate_gains_ = calculate_gains_(dtypes_, True, True, False) |
| 284 |
|
| 285 |
calculate_sieve_gains_ = calculate_gains_sieve_sparse if self.sparse else calculate_gains_sieve |
| 286 |
dtypes_ = sieve_sparse_dtypes if self.sparse else sieve_dtypes |
| 287 |
self.calculate_sieve_gains_ = calculate_sieve_gains_(dtypes_, True, |
| 288 |
True, False) |
| 289 |
|
| 290 |
def _calculate_gains(self, X, idxs=None): |
| 291 |
"""This function will return the gain that each example would give. |
| 292 |
|
| 293 |
This function will return the gains that each example would give if |
| 294 |
added to the selected set. When a matrix of examples is given, a |
| 295 |
vector will be returned showing the gain for each example. When |
| 296 |
a single element is passed in, it will return a singe value.""" |
| 297 |
|
| 298 |
idxs = idxs if idxs is not None else self.idxs |
| 299 |
gains = numpy.zeros(idxs.shape[0], dtype='float64') |
| 300 |
|
| 301 |
if self.sparse: |
| 302 |
self.calculate_gains_(X.data, X.indices, X.indptr, gains, |
| 303 |
self.current_values, self.threshold, idxs) |
| 304 |
else: |
| 305 |
self.calculate_gains_(X, gains, self.current_values, |
| 306 |
self.threshold, idxs) |
| 307 |
gains -= self.current_values_sum |
| 308 |
|
| 309 |
return gains |
| 310 |
|
| 311 |
def _calculate_sieve_gains(self, X, 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(MaxCoverageSelection, self)._calculate_sieve_gains(X, |
| 321 |
thresholds, idxs) |
| 322 |
|
| 323 |
if self.sparse: |
| 324 |
self.calculate_sieve_gains_(X.data, X.indices, X.indptr, |
| 325 |
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_, self.threshold, idxs) |
| 329 |
else: |
| 330 |
self.calculate_sieve_gains_(X, 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_, self.threshold, idxs) |
| 334 |
|
| 335 |
def _select_next(self, X, gain, idx): |
| 336 |
"""This function will add the given item to the selected set.""" |
| 337 |
|
| 338 |
if self.sparse: |
| 339 |
self.current_values = numpy.fmin(self.threshold, |
| 340 |
self.current_values + X.toarray()[0]) |
| 341 |
else: |
| 342 |
self.current_values = numpy.fmin(self.threshold, |
| 343 |
self.current_values + X) |
| 344 |
|
| 345 |
self.current_values_sum = self.current_values.sum() |
| 346 |
|
| 347 |
super(MaxCoverageSelection, self)._select_next( |
| 348 |
X, gain, idx) |