Debian Codegraph @

apricot/functions/sumRedundancy.py

raw ◀ ▶
1 Debian patch touch this file
1 # sumRedundancy.py
2 # Author: Jacob Schreiber <[email protected]>
3
4 import numpy
5
6 from .base import BaseGraphSelection
7
8 from tqdm import tqdm
9
10 class SumRedundancySelection(BaseGraphSelection):
•11 r"""A selector based off a sum redundancy submodular function.
12
13 The sum redundancy function is a graph-based function that penalizes
14 redundancy among the selected set. This approach is straightforward,
15 in that it simply involved a sum. It is also fast in comparison to a
16 facility location function because it involves only performing calculation
17 over the selected set as opposed to the entire ground set. Because the sum
18 of the similarities is not submodular, it is subtracted from the sum of
19 the entire similarity matrix, such that examples that are highly similar
20 to each other result in a lower value than examples that are not very
21 similar.
22
23 .. note::
24 All ~pairwise~ values in your data must be positive for this
25 selection to work.
26
27 The general form of a sum redundancy function is
28
29 .. math::
30 f(X, V) = \sum_{x, y \in V} \phi(x, y) - \sum_{x, y\in X} \phi(x,y)
31
32 where :math:`f` indicates the function, :math:`X` is the selected subset,
33 :math:`V` is the ground set, and :math:`\phi` is the similarity measure
34 between two examples. While sum redundancy functions involves calculating
35 the sum of the entire similarity matrix in principle, in practice if one
36 is only calculating the gains this step can be ignored.
37
38 This implementation allows users to pass in either their own symmetric
39 square matrix of similarity values, or a data matrix as normal and a function
40 that calculates these pairwise values.
41
42 Parameters
43 ----------
44 n_samples : int
45 The number of samples to return.
46
47 metric : str, optional
48 The method for converting a data matrix into a square symmetric matrix
49 of pairwise similarities. If a string, can be any of the metrics
50 implemented in sklearn (see
51 https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise_distances.html),
52 including "precomputed" if one has already generated a similarity
53 matrix. Note that sklearn calculates distance matrices whereas apricot
54 operates on similarity matrices, and so a distances.max() - distances
55 transformation is performed on the resulting distances. For
56 backcompatibility, 'corr' will be read as 'correlation'. Default is
57 'euclidean'.
58
59 initial_subset : list, numpy.ndarray or None, optional
60 If provided, this should be a list of indices into the data matrix
61 to use as the initial subset, or a group of examples that may not be
62 in the provided data should beused as the initial subset. If indices,
63 the provided array should be one-dimensional. If a group of examples,
64 the data should be 2 dimensional. Default is None.
65
66 optimizer : string or optimizers.BaseOptimizer, optional
67 The optimization approach to use for the selection. Default is
68 'two-stage', which makes selections using the naive greedy algorithm
69 initially and then switches to the lazy greedy algorithm. Must be
70 one of
71
72 'random' : randomly select elements (dummy optimizer)
73 'modular' : approximate the function using its modular upper bound
74 'naive' : the naive greedy algorithm
75 'lazy' : the lazy (or accelerated) greedy algorithm
76 'approximate-lazy' : the approximate lazy greedy algorithm
77 'two-stage' : starts with naive and switches to lazy
78 'stochastic' : the stochastic greedy algorithm
79 'sample' : randomly take a subset and perform selection on that
80 'greedi' : the GreeDi distributed algorithm
81 'bidirectional' : the bidirectional greedy algorithm
82
83 Default is 'two-stage'.
84
85 optimizer_kwds : dict or None
86 A dictionary of arguments to pass into the optimizer object. The keys
87 of this dictionary should be the names of the parameters in the optimizer
88 and the values in the dictionary should be the values that these
89 parameters take. Default is None.
90
91 n_neighbors : int or None
92 When constructing a similarity matrix, the number of nearest neighbors
93 whose similarity values will be kept. The result is a sparse similarity
94 matrix which can significantly speed up computation at the cost of
95 accuracy. Default is None.
96
97 reservoir : numpy.ndarray or None
98 The reservoir to use when calculating gains in the sieve greedy
99 streaming optimization algorithm in the `partial_fit` method.
100 Currently only used for graph-based functions. If a numpy array
101 is passed in, it will be used as the reservoir. If None is passed in,
102 will use reservoir sampling to collect a reservoir. Default is None.
103
104 max_reservoir_size : int
105 The maximum size that the reservoir can take. If a reservoir is passed
106 in, this value is set to the size of that array. Default is 1000.
107
108 n_jobs : int
109 The number of threads to use when performing computation in parallel.
110 Currently, this parameter is exposed but does not actually do anything.
111 This will be fixed soon.
112
113 random_state : int or RandomState or None, optional
114 The random seed to use for the random selection process. Only used
115 for stochastic greedy.
116
117 verbose : bool
118 Whether to print output during the selection process.
119
120 Attributes
121 ----------
122 n_samples : int
123 The number of samples to select.
124
125 pairwise_func : callable
126 A function that takes in a data matrix and converts it to a square
127 symmetric matrix.
128
129 ranking : numpy.array int
130 The selected samples in the order of their gain.
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=10, metric='euclidean',
140 initial_subset=None, optimizer='two-stage', n_neighbors=None,
141 reservoir=None, max_reservoir_size=1000, n_jobs=1,
142 random_state=None, optimizer_kwds={}, verbose=False):
143
144 super(SumRedundancySelection, self).__init__(n_samples=n_samples,
145 metric=metric, initial_subset=initial_subset, optimizer=optimizer,
146 n_neighbors=n_neighbors, reservoir=reservoir,
147 max_reservoir_size=max_reservoir_size, n_jobs=n_jobs,
148 random_state=random_state, optimizer_kwds=optimizer_kwds,
149 verbose=verbose)
150
151 def fit(self, X, y=None, sample_weight=None, sample_cost=None):
152 """Run submodular optimization to select the examples.
153
154 This method is a wrapper for the full submodular optimization process.
155 It takes in some data set (and optionally labels that are ignored
156 during this process) and selects `n_samples` from it in the greedy
157 manner specified by the optimizer.
158
159 This method will return the selector object itself, not the transformed
160 data set. The `transform` method will then transform a data set to the
161 selected points, or alternatively one can use the ranking stored in
162 the `self.ranking` attribute. The `fit_transform` method will perform
163 both optimization and selection and return the selected items.
164
165 Parameters
166 ----------
167 X : list or numpy.ndarray, shape=(n, d)
168 The data set to transform. Must be numeric.
169
170 y : list or numpy.ndarray or None, shape=(n,), optional
171 The labels to transform. If passed in this function will return
172 both the data and th corresponding labels for the rows that have
173 been selected.
174
175 sample_weight : list or numpy.ndarray or None, shape=(n,), optional
176 The weight of each example. Currently ignored in apricot but
177 included to maintain compatibility with sklearn pipelines.
178
179 sample_cost : list or numpy.ndarray or None, shape=(n,), optional
180 The cost of each item. If set, indicates that optimization should
181 be performed with respect to a knapsack constraint.
182
183 Returns
184 -------
185 self : SumRedundancySelection
186 The fit step returns this selector object.
187 """
188
189 return super(SumRedundancySelection, self).fit(X, y=y,
190 sample_weight=sample_weight, sample_cost=sample_cost)
191
192 def _initialize(self, X_pairwise, idxs=None):
193 super(SumRedundancySelection, self)._initialize(X_pairwise, idxs=idxs)
194 idxs = idxs if idxs is not None else numpy.arange(X_pairwise.shape[0])
195
196 for i, idx in enumerate(idxs):
197 self.current_values[i] = X_pairwise[idx, idx]
198
199 if self.initial_subset is None:
200 return
201 elif self.initial_subset.ndim == 2:
202 raise ValueError("When using saturated coverage, the initial subset"\
203 " must be a one dimensional array of indices.")
204 elif self.initial_subset.ndim == 1:
205 if not self.sparse:
206 for i in self.initial_subset:
207 self.current_values += X_pairwise[i] * 2
208 else:
209 for i in self.initial_subset:
210 self.current_values += X_pairwise[i].toarray()[0] * 2
211 else:
212 raise ValueError("The initial subset must be either a two dimensional" \
213 " matrix of examples or a one dimensional mask.")
214
215 def _calculate_gains(self, X_pairwise, idxs=None):
216 idxs = idxs if idxs is not None else self.idxs
217 return -self.current_values[idxs]
218
219 def _select_next(self, X_pairwise, gain, idx):
220 """This function will add the given item to the selected set."""
221
222 if self.sparse:
223 self.current_values += X_pairwise.toarray()[0] * 2
224 else:
225 self.current_values += X_pairwise * 2
226
227 super(SumRedundancySelection, self)._select_next(
228 X_pairwise, gain, idx)