Debian Codegraph @

apricot/functions/mixture.py

raw ◀ ▶
1 Debian patch touch this file
1 # mixture.py
2 # Author: Jacob Schreiber <[email protected]>
3
4 import numpy
5
6 from .base import BaseSelection
7 from .base import BaseGraphSelection
8 from ..utils import _calculate_pairwise_distances
9
10 from tqdm import tqdm
11
12 class MixtureSelection(BaseSelection):
13 """A selection approach based on a mixture of submodular functions.
14
15 A convenient property of submodular functions is that any linear
16 combination of submodular functions is still submodular. More generally,
17 the linear combination of any number of submodular functions (assuming
18 non-negative weights) is still a submodular function. Because of this,
19 a mixture of submodular functions can be optimized using the same
20 algorithms as an individual submodular function. Mixtures can be
21 useful in situations where there are different important aspects
22 of data that are each submodular.
23
24 The general form of a mixture function is
25
26 .. math::
27 f(X) = \\sum\\limits_{i=1}^{M} \\alpha_{i} g_{i}(X)
28
29 where :math:`f` indicates the mixture function, :math:`M` is the number of
30 functions in the mixture, :math:`X` is a subset, :math:`\\alpha_{i}` is the
31 weight of the :math:`i`-th function and :math:`g_{i}` is the :math:`i`-th
32 function.
33
34 .. note::
35 There must be at least two components to the mixture, and all
36 :math:`\\alpha` must be non-negative.
37
38 This class can also be used to add regularizers to the selection procedure.
39 If a submodular function is mixed with another submodular function that
40 acts as a regularizer, such as feature based selection mixed with a
41 custom function measuring some property of the selected subset.
42
43 Parameters
44 ----------
45 n_samples : int
46 The number of samples to return.
47
48 functions : list
49 The list of submodular functions to mix together. The submodular
50 functions should be instantiated.
51
52 weights : list, numpy.ndarray or None, optional
53 The relative weight of each submodular function. This is the value
54 that the gain from each submodular function is multiplied by before
55 being added together. The default is equal weight for each function.
56
57 initial_subset : list, numpy.ndarray or None, optional
58 If provided, this should be a list of indices into the data matrix
59 to use as the initial subset, or a group of examples that may not be
60 in the provided data should beused as the initial subset. If indices,
61 the provided array should be one-dimensional. If a group of examples,
62 the data should be 2 dimensional.
63
64 optimizer : string or optimizers.BaseOptimizer, optional
65 The optimization approach to use for the selection. Default is
66 'two-stage', which makes selections using the naive greedy algorithm
67 initially and then switches to the lazy greedy algorithm. Must be
68 one of
69
70 'random' : randomly select elements (dummy optimizer)
71 'modular' : approximate the function using its modular upper bound
72 'naive' : the naive greedy algorithm
73 'lazy' : the lazy (or accelerated) greedy algorithm
74 'approximate-lazy' : the approximate lazy greedy algorithm
75 'two-stage' : starts with naive and switches to lazy
76 'stochastic' : the stochastic greedy algorithm
77 'sample' : randomly take a subset and perform selection on that
78 'greedi' : the GreeDi distributed algorithm
79 'bidirectional' : the bidirectional greedy algorithm
80
81 Default is 'two-stage'.
82
83 optimizer_kwds : dict or None
84 A dictionary of arguments to pass into the optimizer object. The keys
85 of this dictionary should be the names of the parameters in the optimizer
86 and the values in the dictionary should be the values that these
87 parameters take. Default is None.
88
89 reservoir : numpy.ndarray or None
90 The reservoir to use when calculating gains in the sieve greedy
91 streaming optimization algorithm in the `partial_fit` method.
92 Currently only used for graph-based functions. If a numpy array
93 is passed in, it will be used as the reservoir. If None is passed in,
94 will use reservoir sampling to collect a reservoir. Default is None.
95
96 max_reservoir_size : int
97 The maximum size that the reservoir can take. If a reservoir is passed
98 in, this value is set to the size of that array. Default is 1000.
99
100 n_jobs : int
101 The number of threads to use when performing computation in parallel.
102 Currently, this parameter is exposed but does not actually do anything.
103 This will be fixed soon.
104
105 random_state : int or RandomState or None, optional
106 The random seed to use for the random selection process. Only used
107 for stochastic greedy.
108
109 verbose : bool, optional
110 Whether to print output during the selection process.
111
112 Attributes
113 ----------
114 pq : PriorityQueue
115 The priority queue used to implement the lazy greedy algorithm.
116
117 n_samples : int
118 The number of samples to select.
119
120 submodular_functions : list
121 A concave function for transforming feature values, often referred to as
122 phi in the literature.
123
124 weights : numpy.ndarray
125 The weights of each submodular function.
126
127 ranking : numpy.array int
128 The selected samples in the order of their gain with the first number in
129 the ranking corresponding to the index of the first sample that was
130 selected by the greedy procedure.
131
132 gains : numpy.array float
133 The gain of each sample in the returned set when it was added to the
134 growing subset. The first number corresponds to the gain of the first
135 added sample, the second corresponds to the gain of the second added
136 sample, and so forth.
137 """
138
139 def __init__(self, n_samples, functions, weights=None, metric='ignore',
140 initial_subset=None, optimizer='two-stage', optimizer_kwds={}, n_neighbors=None,
141 reservoir=None, max_reservoir_size=1000, n_jobs=1, random_state=None,
142 verbose=False):
143
144 if len(functions) < 2:
145 raise ValueError("Must mix at least two functions.")
146
147 self.m = len(functions)
148 self.functions = functions
149
150 if weights is None:
151 self.weights = numpy.ones(self.m, dtype='float64')
152 else:
•153 self.weights = numpy.array(weights, dtype='float64')
154
155 super(MixtureSelection, self).__init__(n_samples=n_samples,
156 initial_subset=initial_subset, optimizer=optimizer,
157 optimizer_kwds=optimizer_kwds, reservoir=reservoir,
158 max_reservoir_size=max_reservoir_size, n_jobs=n_jobs,
159 random_state=random_state, verbose=verbose)
160
161 self.metric = metric.replace("corr", "correlation")
162 self.n_neighbors = n_neighbors
163
164 for function in self.functions:
165 function.initial_subset = self.initial_subset
166 function.reservoir = reservoir
167 function.max_reservoir_size = max_reservoir_size
168 function.metric = 'precomputed'
169
170 def fit(self, X, y=None, sample_weight=None, sample_cost=None):
171 """Run submodular optimization to select the examples.
172
173 This method is a wrapper for the full submodular optimization process.
174 It takes in some data set (and optionally labels that are ignored
175 during this process) and selects `n_samples` from it in the greedy
176 manner specified by the optimizer.
177
178 This method will return the selector object itself, not the transformed
179 data set. The `transform` method will then transform a data set to the
180 selected points, or alternatively one can use the ranking stored in
181 the `self.ranking` attribute. The `fit_transform` method will perform
182 both optimization and selection and return the selected items.
183
184 Parameters
185 ----------
186 X : list or numpy.ndarray, shape=(n, d)
187 The data set to transform. Must be numeric.
188
189 y : list or numpy.ndarray or None, shape=(n,), optional
190 The labels to transform. If passed in this function will return
191 both the data and th corresponding labels for the rows that have
192 been selected.
193
194 sample_weight : list or numpy.ndarray or None, shape=(n,), optional
195 The weight of each example. Currently ignored in apricot but
196 included to maintain compatibility with sklearn pipelines.
197
198 sample_cost : list or numpy.ndarray or None, shape=(n,), optional
199 The cost of each item. If set, indicates that optimization should
200 be performed with respect to a knapsack constraint.
201
202 Returns
203 -------
204 self : MixtureSelection
205 The fit step returns this selector object.
206 """
207
208 # If self.metric is ignore, this will return the same matrix.
209 # Otherwise, it will convert it to a pairwise similarity matrix.
210 self._X = X
211 X = _calculate_pairwise_distances(X, metric=self.metric,
212 n_neighbors=self.n_neighbors)
213
214 return super(MixtureSelection, self).fit(X, y=y,
215 sample_weight=sample_weight, sample_cost=sample_cost)
216
217 def _initialize(self, X):
218 super(MixtureSelection, self)._initialize(X)
219
220 for function in self.functions:
221 function._initialize(X)
222
223 def _calculate_gains(self, X, idxs=None):
224 """This function will return the gain that each example would give.
225
226 This function will return the gains that each example would give if
227 added to the selected set. When a matrix of examples is given, a
228 vector will be returned showing the gain for each example. When
229 a single element is passed in, it will return a singe value."""
230
231 idxs = idxs if idxs is not None else self.idxs
232 gains = numpy.zeros(idxs.shape[0], dtype='float64')
233
234 for i, function in enumerate(self.functions):
235 gains += function._calculate_gains(X, idxs) * self.weights[i]
236
237 return gains
238
239 def _calculate_sieve_gains(self, X, thresholds, idxs):
240 super(MixtureSelection, self)._calculate_sieve_gains(X,
241 thresholds, idxs)
242
243 for function in self.functions:
244 super(function.__class__, function)._calculate_sieve_gains(X,
245 thresholds, idxs)
246
247 t = numpy.zeros(thresholds.shape[0], dtype='float64') - 1
248
249 for j in range(X.shape[0]):
250 x = X[j:j+1]
251
252 current_values = []
253 total_gains = []
254
255 gain = numpy.zeros((len(thresholds), self.n_samples), dtype='float64')
256 for i, function in enumerate(self.functions):
257 current_values.append(function.sieve_current_values_.copy())
258 total_gains.append(function.sieve_total_gains_.copy())
259
260 function._calculate_sieve_gains(x, t, idxs)
261 gain += function.sieve_gains_ * self.weights[i]
262
263 for l in range(len(thresholds)):
264 if self.sieve_n_selected_[l] == self.n_samples:
265 continue
266
267 threshold = ((thresholds[l] / 2. - self.sieve_total_gains_[l])
268 / (self.n_samples - self.sieve_n_selected_[l]))
269
270 if gain[l, self.sieve_n_selected_[l]] > threshold:
271 self.sieve_total_gains_[l] += gain[l, self.sieve_n_selected_[l]]
272 self.sieve_selections_[l, self.sieve_n_selected_[l]] = idxs[j]
273 self.sieve_gains_[l, self.sieve_n_selected_[l]] = gain[l, self.sieve_n_selected_[l]]
274 self.sieve_n_selected_[l] += 1
275 else:
276 v = self.sieve_n_selected_[l]
277
278 for i, function in enumerate(self.functions):
279 vi = function.sieve_n_selected_[l]
280 if vi != self.sieve_n_selected_[l]:
281 function.sieve_current_values_[l] = current_values[i][l]
282 function.sieve_total_gains_[l] = total_gains[i][l]
283 function.sieve_n_selected_[l] = vi - 1
284 if vi < self.n_samples:
285 function.sieve_selections_[l, vi] = 0
286 function.sieve_gains_[l, vi] = 0
287 function.sieve_subsets_[l, vi] = 0
288
289 def _select_next(self, X, gain, idx):
290 """This function will add the given item to the selected set."""
291
292 for function in self.functions:
293 function._select_next(X, gain, idx)
294
295 super(MixtureSelection, self)._select_next(X, gain, idx)