Debian Codegraph @

apricot/functions/graphCut.py

raw
1 # graphCut.py
2 # Author: Jacob Schreiber <[email protected]>
3
4 import numpy
5
6 from .base import BaseGraphSelection
7
8 from ..utils import _calculate_pairwise_distances
9
10 from tqdm import tqdm
11
12 from numba import njit
13 from numba import prange
14
15 from scipy.sparse import csr_matrix
16
17 sieve_dtypes = 'void(float64[:,:], int64, float64[:,:], int64[:,:],' \
18 'float64[:,:], float64[:], float64[:], int64[:], float64[:], int64[:])'
19
20 def calculate_gains_sieve(dtypes, parallel, fastmath, cache):
21 @njit(dtypes, parallel=parallel, fastmath=fastmath, cache=cache)
22 def calculate_gains_sieve_(X, k, current_values, selections, gains,
23 total_gains, max_values, n_selected, row_sums, idxs):
24 n, d = X.shape
25 t = max_values.shape[0]
26
27 for j in prange(t):
28 for i in range(n):
29 if n_selected[j] == k:
30 break
31
32 idx = idxs[i]
33 threshold = (max_values[j] / 2. - total_gains[j]) / (k - n_selected[j])
34 gain = row_sums[i] - current_values[j, i]
35
36 if gain > threshold:
37 total_gains[j] += gain
38
39 selections[j, n_selected[j]] = idx
40 gains[j, n_selected[j]] = gain
41 n_selected[j] += 1
42
43 return calculate_gains_sieve_
44
45
46 class GraphCutSelection(BaseGraphSelection):
47 """A selector based on using a graph-cut function.
48
49 Graph cuts are canonical class of functions that involves selecting
50 examples that split the similarity matrix into subgraphs well.
51
52 .. note::
53 All ~pairwise~ values in your data must be non-negative for this
54 selection to work.
55
56 The general form of a graph cut function is
57
58 .. math::
59 f(X, V) = \\lambda\\sum_{v \\in V} \\sum_{x \\in X} \\phi(x, v) - \\sum_{x, y \\in X} \\phi(x, y)
60
61 where :math:`f` indicates the function, :math:`X` is a subset, :math:`V`
62 is the ground set, and :math:`\\phi` is the similarity measure between
63 two examples. Like most graph-based functons, the graph-cut function
64 requires access to the full similarity matrix.
65
66 This implementation allows users to pass in either their own symmetric
67 square matrix of similarity values, or a data matrix as normal and a function
68 that calculates these pairwise values.
69
70 Parameters
71 ----------
72 n_samples : int
73 The number of samples to return.
74
75 metric : str, optional
76 The method for converting a data matrix into a square symmetric matrix
77 of pairwise similarities. If a string, can be any of the metrics
78 implemented in sklearn (see
79 https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise_distances.html),
80 including "precomputed" if one has already generated a similarity
81 matrix. Note that sklearn calculates distance matrices whereas apricot
82 operates on similarity matrices, and so a distances.max() - distances
83 transformation is performed on the resulting distances. For
84 backcompatibility, 'corr' will be read as 'correlation'. Default is
85 'euclidean'.
86
87 alpha : float
88 The weight of the first term in the graph-cut objective, which
89 measures the how representative the selected examples are of the
90 ground set. The larger this is, the more likely examples are chosen
91 that are near points in the ground set, even if there are other
92 already-selected examples that are similar. Default is 1.
93
94 initial_subset : list, numpy.ndarray or None, optional
95 If provided, this should be a list of indices into the data matrix
96 to use as the initial subset, or a group of examples that may not be
97 in the provided data should beused as the initial subset. If indices,
98 the provided array should be one-dimensional. If a group of examples,
99 the data should be 2 dimensional. Default is None.
100
101 optimizer : string or optimizers.BaseOptimizer, optional
102 The optimization approach to use for the selection. Default is
103 'two-stage', which makes selections using the naive greedy algorithm
104 initially and then switches to the lazy greedy algorithm. Must be
105 one of
106
107 'random' : randomly select elements (dummy optimizer)
108 'modular' : approximate the function using its modular upper bound
109 'naive' : the naive greedy algorithm
110 'lazy' : the lazy (or accelerated) greedy algorithm
111 'approximate-lazy' : the approximate lazy greedy algorithm
112 'two-stage' : starts with naive and switches to lazy
113 'stochastic' : the stochastic greedy algorithm
114 'sample' : randomly take a subset and perform selection on that
115 'greedi' : the GreeDi distributed algorithm
116 'bidirectional' : the bidirectional greedy algorithm
117
118 Default is 'two-stage'.
119
120 optimizer_kwds : dict or None
121 A dictionary of arguments to pass into the optimizer object. The keys
122 of this dictionary should be the names of the parameters in the optimizer
123 and the values in the dictionary should be the values that these
124 parameters take. Default is None.
125
126 n_neighbors : int or None
127 When constructing a similarity matrix, the number of nearest neighbors
128 whose similarity values will be kept. The result is a sparse similarity
129 matrix which can significantly speed up computation at the cost of
130 accuracy. Default is None.
131
132 reservoir : numpy.ndarray or None
133 The reservoir to use when calculating gains in the sieve greedy
134 streaming optimization algorithm in the `partial_fit` method.
135 Currently only used for graph-based functions. If a numpy array
136 is passed in, it will be used as the reservoir. If None is passed in,
137 will use reservoir sampling to collect a reservoir. Default is None.
138
139 max_reservoir_size : int
140 The maximum size that the reservoir can take. If a reservoir is passed
141 in, this value is set to the size of that array. Default is 1000.
142
143 n_jobs : int
144 The number of threads to use when performing computation in parallel.
145 Currently, this parameter is exposed but does not actually do anything.
146 This will be fixed soon.
147
148 random_state : int or RandomState or None, optional
149 The random seed to use for the random selection process. Only used
150 for stochastic greedy.
151
152 verbose : bool
153 Whether to print output during the selection process.
154
155 Attributes
156 ----------
157 n_samples : int
158 The number of samples to select.
159
160 pairwise_func : callable
161 A function that takes in a data matrix and converts it to a square
162 symmetric matrix.
163
164 ranking : numpy.array int
165 The selected samples in the order of their gain.
166
167 gains : numpy.array float
168 The gain of each sample in the returned set when it was added to the
169 growing subset. The first number corresponds to the gain of the first
170 added sample, the second corresponds to the gain of the second added
171 sample, and so forth.
172 """
173
174 def __init__(self, n_samples=10, metric='euclidean', alpha=1,
175 initial_subset=None, optimizer='naive', optimizer_kwds={},
176 n_neighbors=None, reservoir=None, max_reservoir_size=1000,
177 n_jobs=1, random_state=None, verbose=False):
178 self.alpha = alpha
179
180 super(GraphCutSelection, self).__init__(n_samples=n_samples,
181 metric=metric, initial_subset=initial_subset, optimizer=optimizer,
182 n_neighbors=n_neighbors, reservoir=reservoir,
183 max_reservoir_size=max_reservoir_size, n_jobs=n_jobs,
184 random_state=random_state, optimizer_kwds={}, verbose=verbose)
185
186 def fit(self, X, y=None, sample_weight=None, sample_cost=None):
187 """Run submodular optimization to select the examples.
188
189 This method is a wrapper for the full submodular optimization process.
190 It takes in some data set (and optionally labels that are ignored
191 during this process) and selects `n_samples` from it in the greedy
192 manner specified by the optimizer.
193
194 This method will return the selector object itself, not the transformed
195 data set. The `transform` method will then transform a data set to the
196 selected points, or alternatively one can use the ranking stored in
197 the `self.ranking` attribute. The `fit_transform` method will perform
198 both optimization and selection and return the selected items.
199
200 Parameters
201 ----------
202 X : list or numpy.ndarray, shape=(n, d)
203 The data set to transform. Must be numeric.
204
205 y : list or numpy.ndarray or None, shape=(n,), optional
206 The labels to transform. If passed in this function will return
207 both the data and th corresponding labels for the rows that have
208 been selected.
209
210 sample_weight : list or numpy.ndarray or None, shape=(n,), optional
211 The weight of each example. Currently ignored in apricot but
212 included to maintain compatibility with sklearn pipelines.
213
214 sample_cost : list or numpy.ndarray or None, shape=(n,), optional
215 The cost of each item. If set, indicates that optimization should
216 be performed with respect to a knapsack constraint.
217
218 Returns
219 -------
220 self : GraphCutSelection
221 The fit step returns this selector object.
222 """
223
224 return super(GraphCutSelection, self).fit(X, y=y,
225 sample_weight=sample_weight, sample_cost=sample_cost)
226
227 def _initialize(self, X_pairwise):
228 super(GraphCutSelection, self)._initialize(X_pairwise)
229
230 if self.reservoir is not None:
231 X_pairwise = _calculate_pairwise_distances(self._X,
232 metric=self.metric)
233
234 if self.sparse:
235 self.row_sums = self.alpha * numpy.array(X_pairwise.sum(axis=1))[:,0]
236 self.current_values = X_pairwise.diagonal().astype('float64')
237 else:
238 self.row_sums = self.alpha * X_pairwise.sum(axis=1)
239 self.current_values = numpy.diag(X_pairwise).astype('float64')
240
241 if self.initial_subset is None:
242 pass
243 elif self.initial_subset.ndim == 2:
244 raise ValueError("When using graph-cut, the initial subset"\
245 " must be a one dimensional array of indices.")
246 elif self.initial_subset.ndim == 1:
247 if self.sparse:
248 for i in self.initial_subset:
249 self.current_values += X_pairwise[i].toarray()[0] * 2
250 else:
251 for i in self.initial_subset:
252 self.current_values += X_pairwise[i] * 2
253 else:
254 raise ValueError("The initial subset must be either a two dimensional" \
255 " matrix of examples or a one dimensional mask.")
256
257 self.calculate_sieve_gains_ = calculate_gains_sieve(sieve_dtypes,
258 True, True, False)
259
260 def _calculate_gains(self, X_pairwise, idxs=None):
261 idxs = idxs if idxs is not None else self.idxs
262 gains = self.row_sums[idxs] - self.current_values[idxs]
263 return gains
264
265 def _calculate_sieve_gains(self, X_pairwise, thresholds, idxs):
266 """This function will update the internal statistics from a stream.
267
268 This function will update the various internal statistics that are a
269 part of the sieve algorithm for streaming submodular optimization. This
270 function does not directly return gains but it updates the values
271 used by a streaming optimizer.
272 """
273
274 super(GraphCutSelection, self)._calculate_sieve_gains(X_pairwise,
275 thresholds, idxs)
276
277 n, m = X_pairwise.shape[0], len(thresholds)
278 row_sums = self.alpha * X_pairwise.mean(axis=1)
279 sieve_current_values_ = numpy.tile(numpy.diag(
280 _calculate_pairwise_distances(self._X, metric=self.metric)), (m, 1))
281
282 for i in range(m):
283 l = self.sieve_n_selected_[i]
284 if l == self.n_samples or l == 0:
285 continue
286
287 sieve_current_values_[i] = _calculate_pairwise_distances(
288 self._X, Y=self.sieve_subsets_[i, :l],
289 metric=self.metric).mean(axis=1)
290
291 if self.sparse:
292 self.calculate_sieve_gains_(X_pairwise.data,
293 X_pairwise.indices, X_pairwise.indptr,
294 self.n_samples, sieve_current_values_,
295 self.sieve_selections_, self.sieve_gains_,
296 self.sieve_total_gains_, thresholds,
297 self.sieve_n_selected_, idxs)
298 else:
299 self.calculate_sieve_gains_(X_pairwise, self.n_samples,
300 sieve_current_values_, self.sieve_selections_,
301 self.sieve_gains_, self.sieve_total_gains_, thresholds,
302 self.sieve_n_selected_, row_sums, idxs)
303
304 def _select_next(self, X_pairwise, gain, idx):
305 """This function will add the given item to the selected set."""
306
307 if self.sparse:
308 self.current_values += X_pairwise.toarray()[0] * 2
309 else:
310 self.current_values += X_pairwise * 2
311
312 super(GraphCutSelection, self)._select_next(
313 X_pairwise, gain, idx)