Debian Codegraph @

apricot/functions/featureBased.py

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