Debian Codegraph @

apricot/functions/featureBased.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # featureBased.py
2 # Author: Jacob Schreiber <[email protected]>
3
4 import math
5 import numpy
6
7 from .base import BaseSelection
8 from ..optimizers import LazyGreedy
9 from ..optimizers import ApproximateLazyGreedy
10
11 from tqdm import tqdm
12
13 from numba import njit
14 from numba import prange
15 import torch
16
17 @njit('float64[:](float64[:])', fastmath=True)
18 def sigmoid(X):
19 return X / (1. + X)
20
21 dtypes = 'void(float64[:,:], float64[:], float64[:], int64[:])'
22 sparse_dtypes = 'void(float64[:], int32[:], int32[:], float64[:],' \
23 'float64[:], float64[:], int64[:])'
24 sieve_dtypes = 'void(float64[:,:], int64, float64[:,:], int64[:,:],' \
25 'float64[:,:], float64[:], float64[:], int64[:], int64[:])'
26 sieve_sparse_dtypes = 'void(float64[:], int32[:], int32[:], int64,' \
27 'float64[:,:], int64[:,:], float64[:,:], float64[:], float64[:],' \
28 'int64[:], int64[:])'
29
30 def calculate_gains(func, dtypes, parallel, fastmath, cache):
31 @njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache)
32 def calculate_gains_(X, gains, current_values, idxs):
33 for i in prange(idxs.shape[0]):
34 idx = idxs[i]
35 gains[i] = func(current_values + X[idx]).sum()
36
37 return calculate_gains_
38
39 def calculate_gains_sparse(func, dtypes, parallel, fastmath, cache):
40 @njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache)
41 def calculate_gains_sparse_(X_data, X_indices, X_indptr, gains,
42 current_values, current_concave_values, idxs):
43 for i in prange(idxs.shape[0]):
44 idx = idxs[i]
45 start = X_indptr[idx]
46 end = X_indptr[idx+1]
47
48 for j in range(start, end):
49 k = X_indices[j]
50 gains[i] += (func(X_data[j] + current_values[k])
51 - current_concave_values[k])
52
53 return calculate_gains_sparse_
54
55
56 def calculate_gains_sieve(func, dtypes, parallel, fastmath, cache):
57 @njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache)
58 def calculate_gains_sieve_(X, k, current_values, selections, gains,
59 total_gains, max_values, n_selected, idxs):
60 n = X.shape[0]
61 d = max_values.shape[0]
62
63 for j in prange(d):
64 for i in range(n):
65 if n_selected[j] == k:
66 break
67
68 idx = idxs[i]
69 threshold = (max_values[j] / 2. - total_gains[j]) / (k - n_selected[j])
70 gain = func(current_values[j] + X[i]).sum() - total_gains[j]
71
72 if gain > threshold:
73 current_values[j] += X[i]
74 total_gains[j] += gain
75
76 selections[j, n_selected[j]] = idx
77 gains[j, n_selected[j]] = gain
78 n_selected[j] += 1
79
80 return calculate_gains_sieve_
81
82
83 def calculate_gains_sieve_sparse(func, dtypes, parallel, fastmath, cache):
84 @njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache)
85 def calculate_gains_sieve_sparse_(X_data, X_indices, X_indptr, k,
86 current_values, selections, gains, total_gains, max_values,
87 n_selected, idxs):
88 d = max_values.shape[0]
89
90 for j in prange(d):
91 for i in range(idxs.shape[0]):
92 if n_selected[j] == k:
93 break
94
95 idx = idxs[i]
96 start = X_indptr[i]
97 end = X_indptr[i+1]
98 threshold = (max_values[j] / 2. - total_gains[j]) / (k - n_selected[j])
99
100 gain = 0.0
101 for l in range(start, end):
102 m = X_indices[l]
103 gain += (func(current_values[j, m] + X_data[l]) -
104 func(current_values[j, m]))
105
106 if gain > threshold:
107 for l in range(start, end):
108 m = X_indices[l]
109 current_values[j, m] += X_data[l]
110
111 total_gains[j] += gain
112 selections[j, n_selected[j]] = idx
113 gains[j, n_selected[j]] = gain
114 n_selected[j] += 1
115
116 return calculate_gains_sieve_sparse_
117
118
119 class FeatureBasedSelection(BaseSelection):
120 """A selector based off a feature based submodular function.
121
122 Feature-based functions are those that operate on the feature values of
123 examples directly, rather than on a similarity matrix (or graph) derived
124 from those features, as graph-based functions do. Because these functions
125 do not require calculating and storing a :math:`\\mathcal{O}(n^{2})` sized
126 matrix of similarities, they can easily scale to data sets with millions of
127 examples.
128
129 .. note::
130 All values in your data must be positive for this selection to work.
131
132 The general form of a feature-based function is:
133
134 .. math::
135 f(X) = \\sum\\limits_{d=1}^{D}\\phi\\left(\\sum\\limits_{i=1}^{N} X_{i, d}\\right)
136
137 where :math:`f` indicates the function that uses the concave function
138 :math:`\\phi` and is operating on a subset :math:`X` that has :math:`N`
139 examples and :math:`D` dimensions. Importantly, :math:`X` is the subset
140 and not the ground set, meaning that the time it takes to evaluate this
141 function is proportional only to the size of the selected subset and not
142 the size of the full data set, like it is for graph-based functions.
143
144 See https://ieeexplore.ieee.org/document/6854213 for more details on
145 feature based functions.
146
147 Parameters
148 ----------
149 n_samples : int
150 The number of samples to return.
151
152 concave_func : str or callable
153 The type of concave function to apply to the feature values. You can
154 pass in your own function to apply. Otherwise must be one of the
155 following:
156
157 'log' : log(1 + X)
158 'sqrt' : sqrt(X)
159 'sigmoid' : X / (1 + X)
160
161 initial_subset : list, numpy.ndarray or None
162 If provided, this should be a list of indices into the data matrix
163 to use as the initial subset, or a group of examples that may not be
164 in the provided data should beused as the initial subset. If indices,
165 the provided array should be one-dimensional. If a group of examples,
166 the data should be 2 dimensional.
167
168 optimizer : string or optimizers.BaseOptimizer, optional
169 The optimization approach to use for the selection. Default is
170 'two-stage', which makes selections using the naive greedy algorithm
171 initially and then switches to the lazy greedy algorithm. Must be
172 one of
173
174 'random' : randomly select elements (dummy optimizer)
175 'modular' : approximate the function using its modular upper bound
176 'naive' : the naive greedy algorithm
177 'lazy' : the lazy (or accelerated) greedy algorithm
178 'approximate-lazy' : the approximate lazy greedy algorithm
179 'two-stage' : starts with naive and switches to lazy
180 'stochastic' : the stochastic greedy algorithm
181 'sample' : randomly take a subset and perform selection on that
182 'greedi' : the GreeDi distributed algorithm
183 'bidirectional' : the bidirectional greedy algorithm
184
185 Default is 'two-stage'.
186
187 optimizer_kwds : dict or None
188 A dictionary of arguments to pass into the optimizer object. The keys
189 of this dictionary should be the names of the parameters in the optimizer
190 and the values in the dictionary should be the values that these
191 parameters take. Default is None.
192
193 reservoir : numpy.ndarray or None
194 The reservoir to use when calculating gains in the sieve greedy
195 streaming optimization algorithm in the `partial_fit` method.
196 Currently only used for graph-based functions. If a numpy array
197 is passed in, it will be used as the reservoir. If None is passed in,
198 will use reservoir sampling to collect a reservoir. Default is None.
199
200 max_reservoir_size : int
201 The maximum size that the reservoir can take. If a reservoir is passed
202 in, this value is set to the size of that array. Default is 1000.
203
204 n_jobs : int
205 The number of threads to use when performing computation in parallel.
206 Currently, this parameter is exposed but does not actually do anything.
207 This will be fixed soon.
208
209 random_state : int or RandomState or None, optional
210 The random seed to use for the random selection process. Only used
211 for stochastic greedy.
212
213 verbose : bool
214 Whether to print output during the selection process.
215
216 Attributes
217 ----------
218 n_samples : int
219 The number of samples to select.
220
221 ranking : numpy.array int
222 The selected samples in the order of their gain with the first number in
223 the ranking corresponding to the index of the first sample that was
224 selected by the greedy procedure.
225
226 gains : numpy.array float
227 The gain of each sample in the returned set when it was added to the
228 growing subset. The first number corresponds to the gain of the first
229 added sample, the second corresponds to the gain of the second added
230 sample, and so forth.
231 """
232
233 def __init__(self, n_samples, concave_func='sqrt', initial_subset=None,
234 optimizer='two-stage', optimizer_kwds={}, reservoir=None,
235 max_reservoir_size=1000, n_jobs=1, random_state=None,
236 verbose=False):
237 self.concave_func_name = concave_func
238
239 if concave_func == 'log':
240 self.concave_func = numpy.log1p
241 elif concave_func == 'sqrt':
242 self.concave_func = numpy.sqrt
243 elif concave_func == 'sigmoid':
244 self.concave_func = sigmoid
245 elif callable(concave_func):
246 self.concave_func = concave_func
247 else:
248 raise KeyError("Must be one of 'log', 'sqrt', 'sigmoid', or a any other numpy, scipy, or numba-compiled function.")
249
250 super(FeatureBasedSelection, self).__init__(n_samples=n_samples,
251 initial_subset=initial_subset, optimizer=optimizer,
252 optimizer_kwds=optimizer_kwds, reservoir=reservoir,
253 max_reservoir_size=max_reservoir_size, n_jobs=n_jobs,
254 random_state=random_state, verbose=verbose)
255
256 def fit(self, X, y=None, sample_weight=None, sample_cost=None):
257 """Run submodular optimization to select the examples.
258
259 This method is a wrapper for the full submodular optimization process.
260 It takes in some data set (and optionally labels that are ignored
261 during this process) and selects `n_samples` from it in the greedy
262 manner specified by the optimizer.
263
264 This method will return the selector object itself, not the transformed
265 data set. The `transform` method will then transform a data set to the
266 selected points, or alternatively one can use the ranking stored in
267 the `self.ranking` attribute. The `fit_transform` method will perform
268 both optimization and selection and return the selected items.
269
270 Parameters
271 ----------
272 X : list or numpy.ndarray, shape=(n, d)
273 The data set to transform. Must be numeric.
274
275 y : list or numpy.ndarray or None, shape=(n,), optional
276 The labels to transform. If passed in this function will return
277 both the data and th corresponding labels for the rows that have
278 been selected.
279
280 sample_weight : list or numpy.ndarray or None, shape=(n,), optional
281 The weight of each example. Currently ignored in apricot but
282 included to maintain compatibility with sklearn pipelines.
283
284 sample_cost : list or numpy.ndarray or None, shape=(n,), optional
285 The cost of each item. If set, indicates that optimization should
286 be performed with respect to a knapsack constraint.
287
288 Returns
289 -------
290 self : FeatureBasedSelection
291 The fit step returns this selector object.
292 """
293
294 return super(FeatureBasedSelection, self).fit(X, y=y,
295 sample_weight=sample_weight, sample_cost=sample_cost)
296
297 def _initialize(self, X):
298 super(FeatureBasedSelection, self)._initialize(X)
299
300 if self.initial_subset is None:
301 pass
302 elif self.initial_subset.ndim == 2:
303 self.current_values = self.initial_subset.sum(axis=0).astype('float64')
304 elif self.initial_subset.ndim == 1:
305 self.current_values = X[self.initial_subset].sum(axis=0).astype('float64')
306 else:
307 raise ValueError("The initial subset must be either a two dimensional" \
308 " matrix of examples or a one dimensional mask.")
309
310 self.current_concave_values = self.concave_func(self.current_values)
311 self.current_concave_values_sum = self.current_concave_values.sum()
312
313 calculate_gains_ = calculate_gains_sparse if self.sparse else calculate_gains
314 dtypes_ = sparse_dtypes if self.sparse else dtypes
315
316 if self.optimizer in (LazyGreedy, ApproximateLazyGreedy, 'lazy', 'approximate-lazy'):
317 self.calculate_gains_ = calculate_gains_(self.concave_func,
318 dtypes_, False, True, False)
319 else:
320 self.calculate_gains_ = calculate_gains_(self.concave_func,
321 dtypes_, True, True, False)
322
323 calculate_sieve_gains_ = calculate_gains_sieve_sparse if self.sparse else calculate_gains_sieve
324 dtypes_ = sieve_sparse_dtypes if self.sparse else sieve_dtypes
325 self.calculate_sieve_gains_ = calculate_sieve_gains_(self.concave_func,
326 dtypes_, True, True, False)
327
328 def _calculate_gains(self, X, idxs=None):
329 """This function will return the gain that each example would give.
330
331 This function will return the gains that each example would give if
332 added to the selected set. When a matrix of examples is given, a
333 vector will be returned showing the gain for each example. When
334 a single element is passed in, it will return a singe value."""
335
336 idxs = idxs if idxs is not None else self.idxs
337 gains = numpy.zeros(idxs.shape[0], dtype='float64')
338
339 if self.sparse:
340 self.calculate_gains_(X.data, X.indices, X.indptr, gains,
341 self.current_values, self.current_concave_values, idxs)
342 else:
343 self.calculate_gains_(X, gains, self.current_values, idxs)
344 gains -= self.current_concave_values_sum
345
346 return gains
347
348 def _calculate_sieve_gains(self, X, thresholds, idxs):
349 """This function will update the internal statistics from a stream.
350
351 This function will update the various internal statistics that are a
352 part of the sieve algorithm for streaming submodular optimization. This
353 function does not directly return gains but it updates the values
354 used by a streaming optimizer.
355 """
356
357 super(FeatureBasedSelection, self)._calculate_sieve_gains(X,
358 thresholds, idxs)
359
360 if self.sparse:
361 self.calculate_sieve_gains_(X.data, X.indices, X.indptr,
362 self.n_samples, self.sieve_current_values_,
363 self.sieve_selections_, self.sieve_gains_,
364 self.sieve_total_gains_, thresholds,
365 self.sieve_n_selected_, idxs)
366 else:
367 self.calculate_sieve_gains_(X, self.n_samples,
368 self.sieve_current_values_, self.sieve_selections_,
369 self.sieve_gains_, self.sieve_total_gains_, thresholds,
370 self.sieve_n_selected_, idxs)
371
372 def _select_next(self, X, gain, idx):
373 """This function will add the given item to the selected set."""
374
375 if self.sparse:
376 self.current_values += X.toarray()[0]
377 else:
378 self.current_values += X
379
380 self.current_concave_values = self.concave_func(self.current_values)
381 self.current_concave_values_sum = self.current_concave_values.sum()
382
383 super(FeatureBasedSelection, self)._select_next(
384 X, gain, idx)
385