/
laplace.py
451 lines (330 loc) · 14.5 KB
/
laplace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# MIT License
#
# Copyright (C) IBM Corporation 2019
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
The classic Laplace mechanism in differential privacy, and its derivatives.
"""
from numbers import Real
import numpy as np
from numpy.random import random
from diffprivlib.mechanisms.base import DPMechanism, TruncationAndFoldingMixin
from diffprivlib.utils import copy_docstring
class Laplace(DPMechanism):
r"""
The classic Laplace mechanism in differential privacy, as first proposed by Dwork, McSherry, Nissim and Smith.
Paper link: https://link.springer.com/content/pdf/10.1007/11681878_14.pdf
Includes extension to (relaxed) :math:`(\epsilon,\delta)`-differential privacy, as proposed by Holohan et al.
Paper link: https://arxiv.org/pdf/1402.6124.pdf
"""
def __init__(self):
super().__init__()
self._sensitivity = None
def __repr__(self):
output = super().__repr__()
output += ".set_sensitivity(" + str(self._sensitivity) + ")" if self._sensitivity is not None else ""
return output
def set_sensitivity(self, sensitivity):
"""Sets the sensitivity of the mechanism.
Parameters
----------
sensitivity : float
The sensitivity of the mechanism. Must satisfy `sensitivity` > 0.
Returns
-------
self : class
"""
if not isinstance(sensitivity, Real):
raise TypeError("Sensitivity must be numeric")
if sensitivity <= 0:
raise ValueError("Sensitivity must be strictly positive")
self._sensitivity = float(sensitivity)
return self
def check_inputs(self, value):
"""Checks that all parameters of the mechanism have been initialised correctly, and that the mechanism is ready
to be used.
Parameters
----------
value : float
The value to be checked
Returns
-------
True if the mechanism is ready to be used.
Raises
------
Exception
If parameters have not been set correctly, or if `value` falls outside the domain of the mechanism.
"""
super().check_inputs(value)
if not isinstance(value, Real):
raise TypeError("Value to be randomised must be a number")
if self._sensitivity is None:
raise ValueError("Sensitivity must be set")
return True
def get_bias(self, value):
"""Returns the bias of the mechanism at a given `value`.
Parameters
----------
value : int or float
The value at which the bias of the mechanism is sought.
Returns
-------
bias : float or None
The bias of the mechanism at `value`.
"""
return 0.0
def get_variance(self, value):
"""Returns the variance of the mechanism at a given `value`.
Parameters
----------
value : float
The value at which the variance of the mechanism is sought.
Returns
-------
bias : float
The variance of the mechanism at `value`.
"""
self.check_inputs(0)
return 2 * (self._sensitivity / self._epsilon) ** 2
def randomise(self, value):
"""Randomise `value` with the mechanism.
Parameters
----------
value : float
The value to be randomised.
Returns
-------
float
The randomised value.
"""
self.check_inputs(value)
scale = self._sensitivity / (self._epsilon - np.log(1 - self._delta))
unif_rv = random() - 0.5
return value - scale * np.sign(unif_rv) * np.log(1 - 2 * np.abs(unif_rv))
class LaplaceTruncated(Laplace, TruncationAndFoldingMixin):
"""
The truncated Laplace mechanism, where values outside a pre-described domain are mapped to the closest point
within the domain.
"""
def __init__(self):
super().__init__()
TruncationAndFoldingMixin.__init__(self)
def __repr__(self):
output = super().__repr__()
output += TruncationAndFoldingMixin.__repr__(self)
return output
@copy_docstring(Laplace.get_bias)
def get_bias(self, value):
self.check_inputs(value)
shape = self._sensitivity / self._epsilon
return shape / 2 * (np.exp((self._lower_bound - value) / shape) - np.exp((value - self._upper_bound) / shape))
@copy_docstring(Laplace.get_variance)
def get_variance(self, value):
self.check_inputs(value)
shape = self._sensitivity / self._epsilon
variance = value ** 2 + shape * (self._lower_bound * np.exp((self._lower_bound - value) / shape)
- self._upper_bound * np.exp((value - self._upper_bound) / shape))
variance += (shape ** 2) * (2 - np.exp((self._lower_bound - value) / shape)
- np.exp((value - self._upper_bound) / shape))
variance -= (self.get_bias(value) + value) ** 2
return variance
@copy_docstring(Laplace.check_inputs)
def check_inputs(self, value):
super().check_inputs(value)
TruncationAndFoldingMixin.check_inputs(self, value)
return True
@copy_docstring(Laplace.randomise)
def randomise(self, value):
TruncationAndFoldingMixin.check_inputs(self, value)
noisy_value = super().randomise(value)
return self._truncate(noisy_value)
class LaplaceFolded(Laplace, TruncationAndFoldingMixin):
"""
The folded Laplace mechanism, where values outside a pre-described domain are folded around the domain until they
fall within.
"""
def __init__(self):
super().__init__()
TruncationAndFoldingMixin.__init__(self)
def __repr__(self):
output = super().__repr__()
output += TruncationAndFoldingMixin.__repr__(self)
return output
@copy_docstring(Laplace.get_bias)
def get_bias(self, value):
self.check_inputs(value)
shape = self._sensitivity / self._epsilon
bias = shape * (np.exp((self._lower_bound + self._upper_bound - 2 * value) / shape) - 1)
bias /= np.exp((self._lower_bound - value) / shape) + np.exp((self._upper_bound - value) / shape)
return bias
@copy_docstring(DPMechanism.get_variance)
def get_variance(self, value):
pass
@copy_docstring(Laplace.check_inputs)
def check_inputs(self, value):
super().check_inputs(value)
TruncationAndFoldingMixin.check_inputs(self, value)
return True
@copy_docstring(Laplace.randomise)
def randomise(self, value):
TruncationAndFoldingMixin.check_inputs(self, value)
noisy_value = super().randomise(value)
return self._fold(noisy_value)
class LaplaceBoundedDomain(LaplaceTruncated):
"""
The bounded Laplace mechanism on a bounded domain. The mechanism draws values directly from the domain, without any
post-processing.
"""
def __init__(self):
super().__init__()
self._scale = None
def _find_scale(self):
if self._epsilon is None or self._delta is None:
raise ValueError("Epsilon and Delta must be set before calling _find_scale().")
eps = self._epsilon
delta = self._delta
diam = self._upper_bound - self._lower_bound
delta_q = self._sensitivity
def _delta_c(shape):
if shape == 0:
return 2.0
return (2 - np.exp(- delta_q / shape) - np.exp(- (diam - delta_q) / shape)) / (1 - np.exp(- diam / shape))
def _f(shape):
return delta_q / (eps - np.log(_delta_c(shape)) - np.log(1 - delta))
left = delta_q / (eps - np.log(1 - delta))
right = _f(left)
old_interval_size = (right - left) * 2
while old_interval_size > right - left:
old_interval_size = right - left
middle = (right + left) / 2
if _f(middle) >= middle:
left = middle
if _f(middle) <= middle:
right = middle
return (right + left) / 2
def _cdf(self, value):
# Allow for infinite epsilon
if self._scale == 0:
return 0 if value < 0 else 1
if value < 0:
return 0.5 * np.exp(value / self._scale)
return 1 - 0.5 * np.exp(-value / self._scale)
def get_effective_epsilon(self):
r"""Gets the effective epsilon of the mechanism, only for strict :math:`\epsilon`-differential privacy. Returns
``None`` if :math:`\delta` is non-zero.
Returns
-------
float
The effective :math:`\epsilon` parameter of the mechanism. Returns ``None`` if `delta` is non-zero.
"""
if self._scale is None:
self._scale = self._find_scale()
if self._delta > 0.0:
return None
return self._sensitivity / self._scale
@copy_docstring(Laplace.get_bias)
def get_bias(self, value):
self.check_inputs(value)
if self._scale is None:
self._scale = self._find_scale()
bias = (self._scale - self._lower_bound + value) / 2 * np.exp((self._lower_bound - value) / self._scale) \
- (self._scale + self._upper_bound - value) / 2 * np.exp((value - self._upper_bound) / self._scale)
bias /= 1 - np.exp((self._lower_bound - value) / self._scale) / 2 \
- np.exp((value - self._upper_bound) / self._scale) / 2
return bias
@copy_docstring(Laplace.get_variance)
def get_variance(self, value):
self.check_inputs(value)
if self._scale is None:
self._scale = self._find_scale()
variance = value**2
variance -= (np.exp((self._lower_bound - value) / self._scale) * (self._lower_bound ** 2)
+ np.exp((value - self._upper_bound) / self._scale) * (self._upper_bound ** 2)) / 2
variance += self._scale * (self._lower_bound * np.exp((self._lower_bound - value) / self._scale)
- self._upper_bound * np.exp((value - self._upper_bound) / self._scale))
variance += (self._scale ** 2) * (2 - np.exp((self._lower_bound - value) / self._scale)
- np.exp((value - self._upper_bound) / self._scale))
variance /= 1 - (np.exp(-(value - self._lower_bound) / self._scale)
+ np.exp(-(self._upper_bound - value) / self._scale)) / 2
variance -= (self.get_bias(value) + value) ** 2
return variance
@copy_docstring(Laplace.randomise)
def randomise(self, value):
self.check_inputs(value)
if self._scale is None:
self._scale = self._find_scale()
value = min(value, self._upper_bound)
value = max(value, self._lower_bound)
unif_rv = random()
unif_rv *= self._cdf(self._upper_bound - value) - self._cdf(self._lower_bound - value)
unif_rv += self._cdf(self._lower_bound - value)
unif_rv -= 0.5
unif_rv = min(unif_rv, 0.5 - 1e-10)
return value - self._scale * np.sign(unif_rv) * np.log(1 - 2 * np.abs(unif_rv))
class LaplaceBoundedNoise(Laplace):
"""
The Laplace mechanism with bounded noise, only applicable for approximate differential privacy (delta > 0).
"""
def __init__(self):
super().__init__()
self._scale = None
self._noise_bound = None
def set_epsilon_delta(self, epsilon, delta):
r"""Set the privacy parameters :math:`\epsilon` and :math:`\delta` for the mechanism.
Epsilon must be strictly positive, `epsilon` > 0. `delta` must be strictly in the interval (0, 0.5).
- For zero `epsilon`, use :class:`.Uniform`.
- For zero `delta`, use :class:`.Laplace`.
Parameters
----------
epsilon : float
The value of epsilon for achieving :math:`(\epsilon,\delta)`-differential privacy with the mechanism. Must
have `epsilon > 0`.
delta : float
The value of delta for achieving :math:`(\epsilon,\delta)`-differential privacy with the mechanism. Must
have `0 < delta < 0.5`.
Returns
-------
self : class
"""
if epsilon == 0:
raise ValueError("Epsilon must be strictly positive. For zero epsilon, use :class:`.Uniform`.")
if isinstance(delta, Real) and not 0 < delta < 0.5:
raise ValueError("Delta must be strictly in (0,0.5). For zero delta, use :class:`.Laplace`.")
return DPMechanism.set_epsilon_delta(self, epsilon, delta)
def _cdf(self, value):
if self._scale == 0:
return 0 if value < 0 else 1
if value < 0:
return 0.5 * np.exp(value / self._scale)
return 1 - 0.5 * np.exp(-value / self._scale)
@copy_docstring(Laplace.get_bias)
def get_bias(self, value):
return 0.0
@copy_docstring(DPMechanism.get_variance)
def get_variance(self, value):
pass
@copy_docstring(Laplace.randomise)
def randomise(self, value):
self.check_inputs(value)
if self._scale is None or self._noise_bound is None:
self._scale = self._sensitivity / self._epsilon
self._noise_bound = -1 if self._scale == 0 else \
self._scale * np.log(1 + (np.exp(self._epsilon) - 1) / 2 / self._delta)
unif_rv = random()
unif_rv *= self._cdf(self._noise_bound) - self._cdf(- self._noise_bound)
unif_rv += self._cdf(- self._noise_bound)
unif_rv -= 0.5
return value - self._scale * (np.sign(unif_rv) * np.log(1 - 2 * np.abs(unif_rv)))