Debian Codegraph @

apricot/functions/custom.py

raw
1 # custom.py
2 # Author: Jacob Schreiber <[email protected]>
3
4 import numpy
5
6 from .base import BaseSelection
7 from .base import BaseGraphSelection
8
9 class CustomSelection(BaseSelection):
10 """A selector based off a custom, user-defined feature-based function.
11
12 This selector wraps a custom function that is passed in by the user. This
13 function should take in a matrix containing a subset of the ground set and
14 output the standard measure of quality of the subset. Each row in the matrix
15 should be an example and each column should be a feature value for the
16 example (like a standard data matrix for machine learning).
17
18 .. warning::
19 If the function that the user wants to optimize is graph-based,
20 i.e., that it determines the quality of a subset using similarities
21 with other examples instead of the feature values directly,
22 e.g. facility location, CustomGraphSelection should be used instead.
23
24 .. note::
25 Although apricot is built for submodular functions, there is no explicit
26 restriction that the function passed in be submodular. Sometimes,
27 supermodular functions can be reasonably maximized using the same
28 greedy approaches used on submodular functions.
29
30
31 Parameters
32 ----------
33 n_samples : int
34 The number of samples to return.
35
36 func : function
37 The feature-based set function to that this selector should wrap.
38
39 initial_subset : list, numpy.ndarray or None
40 If provided, this should be a list of indices into the data matrix
41 to use as the initial subset, or a group of examples that may not be
42 in the provided data should beused as the initial subset. If indices,
43 the provided array should be one-dimensional. If a group of examples,
44 the data should be 2 dimensional.
45
46 optimizer : string or optimizers.BaseOptimizer, optional
47 The optimization approach to use for the selection. Default is
48 'two-stage', which makes selections using the naive greedy algorithm
49 initially and then switches to the lazy greedy algorithm. Must be
50 one of
51
52 'random' : randomly select elements (dummy optimizer)
53 'modular' : approximate the function using its modular upper bound
54 'naive' : the naive greedy algorithm
55 'lazy' : the lazy (or accelerated) greedy algorithm
56 'approximate-lazy' : the approximate lazy greedy algorithm
57 'two-stage' : starts with naive and switches to lazy
58 'stochastic' : the stochastic greedy algorithm
59 'sample' : randomly take a subset and perform selection on that
60 'greedi' : the GreeDi distributed algorithm
61 'bidirectional' : the bidirectional greedy algorithm
62
63 Default is 'two-stage'.
64
65 optimizer_kwds : dict, optional
66 Arguments to pass into the optimizer object upon initialization.
67 Default is {}.
68
69 function_kwds : dict, optional
70 Arguments to pass into the function object for each call.
71 Default is {}.
72
73 n_jobs : int, optional
74 The number of cores to use for processing. This value is multiplied
75 by 2 when used to set the number of threads. If set to -1, use all
76 cores and threads. Default is -1.
77
78 random_state : int or RandomState or None, optional
79 The random seed to use for the random selection process. Only used
80 for stochastic greedy.
81
82 verbose : bool
83 Whether to print output during the selection process.
84
85 Attributes
86 ----------
87 n_samples : int
88 The number of samples to select.
89
90 ranking : numpy.array int
91 The selected samples in the order of their gain with the first number in
92 the ranking corresponding to the index of the first sample that was
93 selected by the greedy procedure.
94
95 gains : numpy.array float
96 The gain of each sample in the returned set when it was added to the
97 growing subset. The first number corresponds to the gain of the first
98 added sample, the second corresponds to the gain of the second added
99 sample, and so forth.
100 """
101
102 def __init__(self, n_samples, function, initial_subset=None,
103 optimizer='two-stage', optimizer_kwds={}, function_kwds={},
104 n_jobs=1, random_state=None, verbose=False):
105
106 if callable(function) == False:
107 raise ValueError("Passed in function must be callable.")
108
109 self.function = function
110 self.function_kwds = function_kwds
111
112 super(CustomSelection, self).__init__(n_samples=n_samples,
113 initial_subset=initial_subset, optimizer=optimizer,
114 optimizer_kwds=optimizer_kwds, n_jobs=n_jobs,
115 random_state=random_state, verbose=verbose)
116
117 def fit(self, X, y=None, sample_weight=None, sample_cost=None):
118 """Run submodular optimization to select the examples.
119
120 This method is a wrapper for the full submodular optimization process.
121 It takes in some data set (and optionally labels that are ignored
122 during this process) and selects `n_samples` from it in the greedy
123 manner specified by the optimizer.
124
125 This method will return the selector object itself, not the transformed
126 data set. The `transform` method will then transform a data set to the
127 selected points, or alternatively one can use the ranking stored in
128 the `self.ranking` attribute. The `fit_transform` method will perform
129 both optimization and selection and return the selected items.
130
131 Parameters
132 ----------
133 X : list or numpy.ndarray, shape=(n, d)
134 The data set to transform. Must be numeric.
135
136 y : list or numpy.ndarray or None, shape=(n,), optional
137 The labels to transform. If passed in this function will return
138 both the data and th corresponding labels for the rows that have
139 been selected.
140
141 sample_weight : list or numpy.ndarray or None, shape=(n,), optional
142 The weight of each example. Currently ignored in apricot but
143 included to maintain compatibility with sklearn pipelines.
144
145 sample_cost : list or numpy.ndarray or None, shape=(n,), optional
146 The cost of each item. If set, indicates that optimization should
147 be performed with respect to a knapsack constraint.
148
149 Returns
150 -------
151 self : CustomSelection
152 The fit step returns this selector object.
153 """
154
155 return super(CustomSelection, self).fit(X, y=y,
156 sample_weight=sample_weight, sample_cost=sample_cost)
157
158 def _initialize(self, X):
159 super(CustomSelection, self)._initialize(X)
160
161 if self.initial_subset is None:
162 pass
163 elif self.initial_subset.ndim == 2:
164 if self.initial_subset.shape[1] != X.shape[1]:
165 raise ValueError("The number of columns in the initial subset must " \
166 "match the number of columns in X.")
167 elif self.initial_subset.ndim == 1:
168 self.initial_subset = X[self.initial_subset]
169 else:
170 raise ValueError("The initial subset must be either a two dimensional" \
171 " matrix of examples or a one dimensional mask.")
172
173 if self.initial_subset is None:
174 self.total_gain = 0
175 else:
176 self.total_gain = self.function(self.initial_subset)
177
178
179 def _calculate_gains(self, X, idxs=None):
180 """This function will return the gain that each example would give.
181
182 This function will return the gains that each example would give if
183 added to the selected set. When a matrix of examples is given, a
184 vector will be returned showing the gain for each example. When
185 a single element is passed in, it will return a singe value."""
186
187 idxs = idxs if idxs is not None else self.idxs
188 gains = numpy.zeros(idxs.shape[0], dtype='float64')
189
190 x0 = numpy.zeros((1, X.shape[1]))
191
192 if self.initial_subset is not None:
193 X_ = numpy.concatenate([self.initial_subset, self.subset, x0])
194 else:
195 X_ = numpy.concatenate([self.subset, x0])
196
197 for i, idx in enumerate(idxs):
198 X_[-1] = X[idx]
199 gains[i] = self.function(X_, **self.function_kwds) - self.total_gain
200
201 return gains
202
203 def _calculate_sieve_gains(self, X, thresholds, idxs):
204 """This function will update the internal statistics from a stream.
205
206 This function will update the various internal statistics that are a
207 part of the sieve algorithm for streaming submodular optimization. This
208 function does not directly return gains but it updates the values
209 used by a streaming optimizer.
210 """
211
212 super(CustomSelection, self)._calculate_sieve_gains(X,
213 thresholds, idxs)
214
215 raise NotImplementedError
216
217 def _select_next(self, X, gain, idx):
218 """This function will add the given item to the selected set."""
219
220 self.total_gain += gain
221
222 super(CustomSelection, self)._select_next(
223 X, gain, idx)
224
225
226 class CustomGraphSelection(BaseGraphSelection):
227 """A selector based off a custom, user-defined graph-based function.
228
229 This selector wraps a custom graph-based function that is passed in by the user.
230 This function should take in a matrix containing a subset of the ground set and
231 output the standard measure of quality of the subset. Each row in the matrix
232 should be an example and each column should be the similarity to each element
233 in the ground set, with the number of columns being equal to the size of the
234 ground set.
235
236 .. note::
237 Although apricot is built for submodular functions, there is no explicit
238 restriction that the function passed in be submodular. Sometimes,
239 supermodular functions can be reasonably maximized using the same
240 greedy approaches used on submodular functions.
241
242
243 Parameters
244 ----------
245 n_samples : int
246 The number of samples to return.
247
248 func : function
249 The graph-based set function to that this selector should wrap.
250
251 initial_subset : list, numpy.ndarray or None
252 If provided, this should be a list of indices into the data matrix
253 to use as the initial subset, or a group of examples that may not be
254 in the provided data should beused as the initial subset. If indices,
255 the provided array should be one-dimensional. If a group of examples,
256 the data should be 2 dimensional.
257
258 optimizer : string or optimizers.BaseOptimizer, optional
259 The optimization approach to use for the selection. Default is
260 'two-stage', which makes selections using the naive greedy algorithm
261 initially and then switches to the lazy greedy algorithm. Must be
262 one of
263
264 'random' : randomly select elements (dummy optimizer)
265 'modular' : approximate the function using its modular upper bound
266 'naive' : the naive greedy algorithm
267 'lazy' : the lazy (or accelerated) greedy algorithm
268 'approximate-lazy' : the approximate lazy greedy algorithm
269 'two-stage' : starts with naive and switches to lazy
270 'stochastic' : the stochastic greedy algorithm
271 'sample' : randomly take a subset and perform selection on that
272 'greedi' : the GreeDi distributed algorithm
273 'bidirectional' : the bidirectional greedy algorithm
274
275 Default is 'two-stage'.
276
277 optimizer_kwds : dict, optional
278 Arguments to pass into the optimizer object upon initialization.
279 Default is {}.
280
281 function_kwds : dict, optional
282 Arguments to pass into the function object for each call.
283 Default is {}.
284
285 n_jobs : int, optional
286 The number of cores to use for processing. This value is multiplied
287 by 2 when used to set the number of threads. If set to -1, use all
288 cores and threads. Default is -1.
289
290 random_state : int or RandomState or None, optional
291 The random seed to use for the random selection process. Only used
292 for stochastic greedy.
293
294 verbose : bool
295 Whether to print output during the selection process.
296
297 Attributes
298 ----------
299 n_samples : int
300 The number of samples to select.
301
302 ranking : numpy.array int
303 The selected samples in the order of their gain with the first number in
304 the ranking corresponding to the index of the first sample that was
305 selected by the greedy procedure.
306
307 gains : numpy.array float
308 The gain of each sample in the returned set when it was added to the
309 growing subset. The first number corresponds to the gain of the first
310 added sample, the second corresponds to the gain of the second added
311 sample, and so forth.
312 """
313
314 def __init__(self, n_samples, function, metric='euclidean',
315 initial_subset=None, optimizer='two-stage', optimizer_kwds={},
316 function_kwds={}, n_jobs=1, random_state=None, verbose=False):
317
318 if callable(function) == False:
319 raise ValueError("Passed in function must be callable.")
320
321 self.function = function
322 self.function_kwds = function_kwds
323
324 super(CustomGraphSelection, self).__init__(n_samples=n_samples,
325 metric=metric, initial_subset=initial_subset, optimizer=optimizer,
326 optimizer_kwds=optimizer_kwds, n_jobs=n_jobs,
327 random_state=random_state, verbose=verbose)
328
329 def fit(self, X, y=None, sample_weight=None, sample_cost=None):
330 """Run submodular optimization to select the examples.
331
332 This method is a wrapper for the full submodular optimization process.
333 It takes in some data set (and optionally labels that are ignored
334 during this process) and selects `n_samples` from it in the greedy
335 manner specified by the optimizer.
336
337 This method will return the selector object itself, not the transformed
338 data set. The `transform` method will then transform a data set to the
339 selected points, or alternatively one can use the ranking stored in
340 the `self.ranking` attribute. The `fit_transform` method will perform
341 both optimization and selection and return the selected items.
342
343 Parameters
344 ----------
345 X : list or numpy.ndarray, shape=(n, d)
346 The data set to transform. Must be numeric.
347
348 y : list or numpy.ndarray or None, shape=(n,), optional
349 The labels to transform. If passed in this function will return
350 both the data and th corresponding labels for the rows that have
351 been selected.
352
353 sample_weight : list or numpy.ndarray or None, shape=(n,), optional
354 The weight of each example. Currently ignored in apricot but
355 included to maintain compatibility with sklearn pipelines.
356
357 sample_cost : list or numpy.ndarray or None, shape=(n,), optional
358 The cost of each item. If set, indicates that optimization should
359 be performed with respect to a knapsack constraint.
360
361 Returns
362 -------
363 self : CustomSelection
364 The fit step returns this selector object.
365 """
366
367 return super(CustomGraphSelection, self).fit(X, y=y,
368 sample_weight=sample_weight, sample_cost=sample_cost)
369
370 def _initialize(self, X):
371 super(CustomGraphSelection, self)._initialize(X)
372
373 if self.initial_subset is None:
374 pass
375 elif self.initial_subset.ndim == 2:
376 if self.initial_subset.shape[1] != X.shape[1]:
377 raise ValueError("The number of columns in the initial subset must " \
378 "match the number of columns in X.")
379 elif self.initial_subset.ndim == 1:
380 self.initial_subset = X[self.initial_subset]
381 else:
382 raise ValueError("The initial subset must be either a two dimensional" \
383 " matrix of examples or a one dimensional mask.")
384
385 if self.initial_subset is None:
386 self.total_gain = 0
387 else:
388 self.total_gain = self.func(self.initial_subset)
389
390
391 def _calculate_gains(self, X, idxs=None):
392 """This function will return the gain that each example would give.
393
394 This function will return the gains that each example would give if
395 added to the selected set. When a matrix of examples is given, a
396 vector will be returned showing the gain for each example. When
397 a single element is passed in, it will return a singe value."""
398
399 idxs = idxs if idxs is not None else self.idxs
400 gains = numpy.zeros(idxs.shape[0], dtype='float64')
401
402 x0 = numpy.zeros((1, X.shape[1]))
403
404 if self.initial_subset is not None:
405 X_ = numpy.concatenate([self.initial_subset, self.subset, x0])
406 else:
407 X_ = numpy.concatenate([self.subset, x0])
408
409 for i, idx in enumerate(idxs):
410 X_[-1] = X[idx]
411 gains[i] = self.function(X_, **self.function_kwds) - self.total_gain
412
413 return gains
414
415 def _calculate_sieve_gains(self, X, thresholds, idxs):
416 """This function will update the internal statistics from a stream.
417
418 This function will update the various internal statistics that are a
419 part of the sieve algorithm for streaming submodular optimization. This
420 function does not directly return gains but it updates the values
421 used by a streaming optimizer.
422 """
423
424 super(CustomGraphSelection, self)._calculate_sieve_gains(X,
425 thresholds, idxs)
426
427 raise NotImplementedError
428
429 def _select_next(self, X, gain, idx):
430 """This function will add the given item to the selected set."""
431
432 self.total_gain += gain
433
434 super(CustomGraphSelection, self)._select_next(
435 X, gain, idx)