



Diffprivlib: Differential Privacy Library 0.4.1 documentation

 [Diffprivlib: Differential Privacy Library](#) 

 0.4.1

 

Modules

* [`diffprivlib.accountant`](index.html#document-modules/accountant)

	+ [Base class](index.html#base-class)

* [`diffprivlib.mechanisms`](index.html#document-modules/mechanisms)

	+ [Base classes](index.html#base-classes)

	+ [Binary mechanism](index.html#binary-mechanism)

	+ [Bingham mechanism](index.html#bingham-mechanism)

	+ [Exponential mechanisms](index.html#exponential-mechanisms)

	+ [Gaussian mechanisms](index.html#gaussian-mechanisms)

	+ [Geometric mechanisms](index.html#geometric-mechanisms)

	+ [Laplace mechanisms](index.html#laplace-mechanisms)

	+ [Staircase mechanism](index.html#staircase-mechanism)

	+ [Uniform mechanism](index.html#uniform-mechanism)

	+ [Vector mechanism](index.html#vector-mechanism)

	+ [Wishart mechanism](index.html#wishart-mechanism)

* [`diffprivlib.mechanisms.transforms`](index.html#document-modules/transforms)

	+ [Base class](index.html#base-class)

	+ [Type casting transforms](index.html#type-casting-transforms)

	+ [Other transforms](index.html#other-transforms)

* [`diffprivlib.tools`](index.html#document-modules/tools)

	+ [Histogram functions](index.html#histogram-functions)

	+ [General Utilities](index.html#general-utilities)

	+ [Quantile-like functions](index.html#quantile-like-functions)

* [`diffprivlib.models`](index.html#document-modules/models)

	+ [Classification models](index.html#classification-models)

		- [Gaussian Naive Bayes](index.html#gaussian-naive-bayes)

		- [Logistic Regression](index.html#logistic-regression)

	+ [Regression models](index.html#regression-models)

		- [Linear Regression](index.html#linear-regression)

	+ [Clustering models](index.html#clustering-models)

		- [K-Means](index.html#k-means)

	+ [Dimensionality reduction models](index.html#dimensionality-reduction-models)

		- [PCA](index.html#pca)

	+ [Preprocessing](index.html#preprocessing)

		- [Standard Scaler](index.html#standard-scaler)

* [Utilities and general functions](index.html#document-modules/utils)

	+ [Exceptions and warnings](index.html#exceptions-and-warnings)

	+ [General classes](index.html#general-classes)

	+ [General functions](index.html#general-functions)

* [Validation functions](index.html#document-modules/validation)

	+ [General functions](index.html#general-functions)

[Diffprivlib: Differential Privacy Library](#)

* »

* Diffprivlib: Differential Privacy Library 0.4.1 documentation

* [Edit on GitHub](https://github.com/IBM/differential-privacy-library/blob/0.4.1/docs/index.rst)

---

Welcome to the IBM Differential Privacy Library[¶](#welcome-to-the-ibm-differential-privacy-library "Permalink to this headline")

=================================================================================================================================

This is a library dedicated to differential privacy and machine learning.

Its purpose is to allow experimentation, simulation, and implementation of differentially private models using a common codebase and building blocks.

[`diffprivlib.accountant`](#module-diffprivlib.accountant "diffprivlib.accountant")[¶](#module-diffprivlib.accountant "Permalink to this headline")

---------------------------------------------------------------------------------------------------------------------------------------------------

Privacy budget accountant for differential privacy

### Base class[¶](#base-class "Permalink to this headline")

*class* diffprivlib.accountant.BudgetAccountant(*epsilon=inf*, *delta=1.0*, *slack=0.0*, *spent\_budget=None*)[[source]](_modules/diffprivlib/accountant.html#BudgetAccountant)[¶](#diffprivlib.accountant.BudgetAccountant "Permalink to this definition")

Privacy budget accountant for differential privacy.

This class creates a privacy budget accountant to track privacy spend across queries and other data accesses. Once

initialised, the BudgetAccountant stores each privacy spend and iteratively updates the total budget spend, raising

an error when the budget ceiling (if specified) is exceeded. The accountant can be initialised without any maximum

budget, to enable users track the total privacy spend of their actions without hindrance.

Diffprivlib functions can make use of a BudgetAccountant in three different ways (see examples for more details):

> 

> * Passed as an `accountant` parameter to the function (e.g., `mean(..., accountant=acc)`)

> * Set as the default using the `set\_default()` method (all subsequent diffprivlib functions will use the

> accountant by default)

> * As a context manager using a `with` statement (the accountant is used for that block of code)

> 

> 

> 

Implements the accountant rules as given in [[KOV17]](index.html#kov17).

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: infinity*) – Epsilon budget ceiling of the accountant.

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Delta budget ceiling of the accountant.

* **slack** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 0.0*) – Slack allowed in delta spend. Greater slack may reduce the overall epsilon spend.

* **spent\_budget** (*list of tuples of the form* *(**epsilon**,* *delta**)**,* *optional*) – List of tuples of pre-existing budget spends. Allows for a new accountant to be initialised with spends

extracted from a previous instance.

epsilon[¶](#diffprivlib.accountant.BudgetAccountant.epsilon "Permalink to this definition")

Epsilon budget ceiling of the accountant.

Type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

delta[¶](#diffprivlib.accountant.BudgetAccountant.delta "Permalink to this definition")

Delta budget ceiling of the accountant.

Type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

slack[¶](#diffprivlib.accountant.BudgetAccountant.slack "Permalink to this definition")

The accountant’s slack. Can be modified at runtime, subject to the privacy budget not being exceeded.

Type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

spent\_budget[¶](#diffprivlib.accountant.BudgetAccountant.spent_budget "Permalink to this definition")

The list of privacy spends recorded by the accountant. Can be used in the initialisation of a new accountant.

Type

list of tuples of the form (epsilon, delta)

Examples

A `BudgetAccountant` is typically passed to diffprivlib functions as an `accountant` parameter. If `epsilon`

and `delta` are not set, the accountant has an infinite budget by default, allowing you to track privacy spend

without imposing a hard limit. By allowing a `slack` in the budget calculation, the overall epsilon privacy spend

can be reduced (at the cost of extra delta spend).

```

>>> import diffprivlib as dp

>>> from numpy.random import random

>>> X = random(100)

>>> acc = dp.BudgetAccountant(epsilon=1.5, delta=0)

>>> dp.tools.mean(X, bounds=(0, 1), accountant=acc)

0.4547006207923884

>>> acc.total()

(epsilon=1.0, delta=0)

>>> dp.tools.std(X, bounds=(0, 1), epsilon=0.25, accountant=acc)

0.2630216611181259

>>> acc.total()

(epsilon=1.25, delta=0)

```

```

>>> acc2 = dp.BudgetAccountant() # infinite budget

>>> first\_half = dp.tools.mean(X[:50], epsilon=0.25, bounds=(0, 1), accountant=acc2)

>>> last\_half = dp.tools.mean(X[50:], epsilon=0.25, bounds=(0, 1), accountant=acc2)

>>> acc2.total()

(epsilon=0.5, delta=0)

>>> acc2.remaining()

(epsilon=inf, delta=1.0)

```

```

>>> acc3 = dp.BudgetAccountant(slack=1e-3)

>>> for i in range(20):

...     dp.tools.mean(X, epsilon=0.05, bounds=(0, 1), accountant=acc3)

>>> acc3.total() # Slack has reduced the epsilon spend by almost 25%

(epsilon=0.7613352285668463, delta=0.001)

```

Using `set\_default()`, an accountant is used by default in all diffprivlib functions in that script. Accountants

also act as context managers, allowing for use in a `with` statement. Passing an accountant as a parameter

overrides all other methods.

```

>>> acc4 = dp.BudgetAccountant()

>>> acc4.set\_default()

BudgetAccountant()

>>> Y = random((100, 2)) - 0.5

>>> clf = dp.models.PCA(1, centered=True, data\_norm=1.4)

>>> clf.fit(Y)

PCA(accountant=BudgetAccountant(spent\_budget=[(1.0, 0)]), centered=True, copy=True, data\_norm=1.4, epsilon=1.0,

n\_components=1, random\_state=None, bounds=None, whiten=False)

>>> acc4.total()

(epsilon=1.0, delta=0)

```

```

>>> with dp.BudgetAccountant() as acc5:

...     dp.tools.mean(Y, bounds=(0, 1), epsilon=1/3)

>>> acc5.total()

(epsilon=0.3333333333333333, delta=0)

```

References

[KOV17](#id1)

Kairouz, Peter, Sewoong Oh, and Pramod Viswanath. “The composition theorem for differential privacy.”

IEEE Transactions on Information Theory 63.6 (2017): 4037-4049.

check(*epsilon*, *delta*)[[source]](_modules/diffprivlib/accountant.html#BudgetAccountant.check)[¶](#diffprivlib.accountant.BudgetAccountant.check "Permalink to this definition")

Checks if the provided (epsilon,delta) can be spent without exceeding the accountant’s budget ceiling.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Epsilon budget spend to check.

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Delta budget spend to check.

Returns

True if the budget can be spent, otherwise a [`BudgetError`](index.html#diffprivlib.utils.BudgetError "diffprivlib.utils.BudgetError") is raised.

Return type

[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")

Raises

[**BudgetError**](index.html#diffprivlib.utils.BudgetError "diffprivlib.utils.BudgetError") – If the specified budget spend will result in the budget ceiling being exceeded.

*static* load\_default(*accountant*)[[source]](_modules/diffprivlib/accountant.html#BudgetAccountant.load_default)[¶](#diffprivlib.accountant.BudgetAccountant.load_default "Permalink to this definition")

Loads the default privacy budget accountant if none is supplied, otherwise checks that the supplied

accountant is a BudgetAccountant class.

An accountant can be set as the default using the set\_default() method. If no default has been set, a default

is created.

Parameters

**accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant") *or* [*None*](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")) – The supplied budget accountant. If None, the default accountant is returned.

Returns

**default** – Returns a working BudgetAccountant, either the supplied accountant or the existing default.

Return type

[BudgetAccountant](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")

*static* pop\_default()[[source]](_modules/diffprivlib/accountant.html#BudgetAccountant.pop_default)[¶](#diffprivlib.accountant.BudgetAccountant.pop_default "Permalink to this definition")

Pops the default BudgetAccountant from the class and returns it to the user.

Returns

**default** – Returns the existing default BudgetAccountant.

Return type

[BudgetAccountant](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")

remaining(*k=1*)[[source]](_modules/diffprivlib/accountant.html#BudgetAccountant.remaining)[¶](#diffprivlib.accountant.BudgetAccountant.remaining "Permalink to this definition")

Calculates the budget that remains to be spent.

Calculates the privacy budget that can be spent on k queries. Spending this budget on k queries will

match the budget ceiling, assuming no floating point errors.

Parameters

**k** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default: 1*) – The number of queries for which to calculate the remaining budget.

Returns

* **epsilon** (*float*) – Total epsilon spend remaining for k queries.

* **delta** (*float*) – Total delta spend remaining for k queries.

set\_default()[[source]](_modules/diffprivlib/accountant.html#BudgetAccountant.set_default)[¶](#diffprivlib.accountant.BudgetAccountant.set_default "Permalink to this definition")

Sets the current accountant to be the default when running functions and queries with diffprivlib.

Returns

**self**

Return type

[BudgetAccountant](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")

spend(*epsilon*, *delta*)[[source]](_modules/diffprivlib/accountant.html#BudgetAccountant.spend)[¶](#diffprivlib.accountant.BudgetAccountant.spend "Permalink to this definition")

Spend the given privacy budget.

Instructs the accountant to spend the given epsilon and delta privacy budget, while ensuring the target budget

is not exceeded.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Epsilon privacy budget to spend.

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Delta privacy budget to spend.

Returns

**self**

Return type

[BudgetAccountant](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")

total(*spent\_budget=None*, *slack=None*)[[source]](_modules/diffprivlib/accountant.html#BudgetAccountant.total)[¶](#diffprivlib.accountant.BudgetAccountant.total "Permalink to this definition")

Returns the total current privacy spend.

spent\_budget and slack can be specified as parameters, otherwise the class values will be used.

Parameters

* **spent\_budget** (*list of tuples of the form* *(**epsilon**,* *delta**)**,* *optional*) – List of tuples of budget spends. If not provided, the accountant’s spends will be used.

* **slack** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *optional*) – Slack in delta for composition. If not provided, the accountant’s slack will be used.

Returns

* **epsilon** (*float*) – Total epsilon spend.

* **delta** (*float*) – Total delta spend.

[`diffprivlib.mechanisms`](#module-diffprivlib.mechanisms "diffprivlib.mechanisms")[¶](#module-diffprivlib.mechanisms "Permalink to this headline")

---------------------------------------------------------------------------------------------------------------------------------------------------

Basic mechanisms for achieving differential privacy, the basic building blocks of the library.

### Base classes[¶](#base-classes "Permalink to this headline")

*class* diffprivlib.mechanisms.DPMachine[[source]](_modules/diffprivlib/mechanisms/base.html#DPMachine)[¶](#diffprivlib.mechanisms.DPMachine "Permalink to this definition")

Parent class for [`DPMechanism`](#diffprivlib.mechanisms.DPMechanism "diffprivlib.mechanisms.DPMechanism") and [`DPTransformer`](index.html#diffprivlib.mechanisms.transforms.DPTransformer "diffprivlib.mechanisms.transforms.DPTransformer"), providing and specifying basic functionality.

copy()[[source]](_modules/diffprivlib/mechanisms/base.html#DPMachine.copy)[¶](#diffprivlib.mechanisms.DPMachine.copy "Permalink to this definition")

Produces a copy of the class.

Returns

**self** – Returns the copy.

Return type

class

*abstract* randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/base.html#DPMachine.randomise)[¶](#diffprivlib.mechanisms.DPMachine.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") *or* *method*) – The value to be randomised.

Returns

The randomised value, same type as value.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") or [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") or method

*class* diffprivlib.mechanisms.DPMechanism(*\**, *epsilon*, *delta*)[[source]](_modules/diffprivlib/mechanisms/base.html#DPMechanism)[¶](#diffprivlib.mechanisms.DPMechanism "Permalink to this definition")

Abstract base class for all mechanisms. Instantiated from [`DPMachine`](#diffprivlib.mechanisms.DPMachine "diffprivlib.mechanisms.DPMachine").

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in [0, ∞].

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\delta\) for the mechanism. Must be in [0, 1]. Cannot be simultaneously zero with

`epsilon`.

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/base.html#DPMechanism.bias)[¶](#diffprivlib.mechanisms.DPMechanism.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

copy()[¶](#diffprivlib.mechanisms.DPMechanism.copy "Permalink to this definition")

Produces a copy of the class.

Returns

**self** – Returns the copy.

Return type

class

mse(*value*)[[source]](_modules/diffprivlib/mechanisms/base.html#DPMechanism.mse)[¶](#diffprivlib.mechanisms.DPMechanism.mse "Permalink to this definition")

Returns the mean squared error (MSE) of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the MSE of the mechanism is sought.

Returns

**bias** – The MSE of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

*abstract* randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/base.html#DPMechanism.randomise)[¶](#diffprivlib.mechanisms.DPMechanism.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") *or* *method*) – The value to be randomised.

Returns

The randomised value, same type as value.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") or [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") or method

variance(*value*)[[source]](_modules/diffprivlib/mechanisms/base.html#DPMechanism.variance)[¶](#diffprivlib.mechanisms.DPMechanism.variance "Permalink to this definition")

Returns the variance of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the variance of the mechanism is sought.

Returns

**bias** – The variance of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

*class* diffprivlib.mechanisms.TruncationAndFoldingMixin(*\**, *lower*, *upper*)[[source]](_modules/diffprivlib/mechanisms/base.html#TruncationAndFoldingMixin)[¶](#diffprivlib.mechanisms.TruncationAndFoldingMixin "Permalink to this definition")

Mixin for truncating or folding the outputs of a mechanism. Must be instantiated with a [`DPMechanism`](#diffprivlib.mechanisms.DPMechanism "diffprivlib.mechanisms.DPMechanism").

Parameters

* **lower** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The lower bound of the mechanism.

* **upper** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The upper bound of the mechanism.

### Binary mechanism[¶](#binary-mechanism "Permalink to this headline")

*class* diffprivlib.mechanisms.Binary(*\**, *epsilon*, *value0*, *value1*)[[source]](_modules/diffprivlib/mechanisms/binary.html#Binary)[¶](#diffprivlib.mechanisms.Binary "Permalink to this definition")

The classic binary mechanism in differential privacy.

Given a binary input value, the mechanism randomly decides to flip to the other binary value or not, in order to

satisfy differential privacy.

Paper link: <https://arxiv.org/pdf/1612.05568.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in [0, ∞].

* **value0** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – 0th binary label.

* **value1** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – 1st binary label. Cannot be the same as `value0`.

Notes

* The binary attributes, known as labels, must be specified as strings. If non-string labels are required (e.g.

integer-valued labels), a [`DPTransformer`](index.html#diffprivlib.mechanisms.transforms.DPTransformer "diffprivlib.mechanisms.transforms.DPTransformer") can be used (e.g. [`IntToString`](index.html#diffprivlib.mechanisms.transforms.IntToString "diffprivlib.mechanisms.transforms.IntToString")).

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/binary.html#Binary.randomise)[¶](#diffprivlib.mechanisms.Binary.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")

### Bingham mechanism[¶](#bingham-mechanism "Permalink to this headline")

*class* diffprivlib.mechanisms.Bingham(*\**, *epsilon*, *sensitivity=1.0*)[[source]](_modules/diffprivlib/mechanisms/bingham.html#Bingham)[¶](#diffprivlib.mechanisms.Bingham "Permalink to this definition")

The Bingham mechanism in differential privacy.

Used to estimate the first eigenvector (associated with the largest eigenvalue) of a covariance matrix.

Paper link: <http://eprints.whiterose.ac.uk/123206/7/simbingham8.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1*) – The sensitivity of the mechanism. Must be in [0, ∞).

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/bingham.html#Bingham.randomise)[¶](#diffprivlib.mechanisms.Bingham.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** (*numpy array*) – The data to be randomised.

Returns

The randomised eigenvector.

Return type

numpy array

### Exponential mechanisms[¶](#exponential-mechanisms "Permalink to this headline")

*class* diffprivlib.mechanisms.Exponential(*\**, *epsilon*, *sensitivity*, *utility*, *candidates=None*, *measure=None*)[[source]](_modules/diffprivlib/mechanisms/exponential.html#Exponential)[¶](#diffprivlib.mechanisms.Exponential "Permalink to this definition")

The exponential mechanism for achieving differential privacy on candidate selection, as first proposed by McSherry

and Talwar.

The exponential mechanism achieves differential privacy by randomly choosing a candidate subject to candidate

utility scores, with greater probability given to higher-utility candidates.

Paper link: <https://www.cs.drexel.edu/~greenie/privacy/mdviadp.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity in utility values to a change in a datapoint in the underlying dataset.

* **utility** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)")) – A list of non-negative utility values for each candidate.

* **candidates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)")*,* *optional*) – An optional list of candidate labels. If omitted, the zero-indexed list [0, 1, …, n] is used.

* **measure** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)")*,* *optional*) – An optional list of measures for each candidate. If omitted, a uniform measure is used.

randomise(*value=None*)[[source]](_modules/diffprivlib/mechanisms/exponential.html#Exponential.randomise)[¶](#diffprivlib.mechanisms.Exponential.randomise "Permalink to this definition")

Select a candidate with differential privacy.

Parameters

**value** ([*None*](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")) – Ignored.

Returns

The randomised candidate.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") or other

*class* diffprivlib.mechanisms.ExponentialCategorical(*\**, *epsilon*, *utility\_list*)[[source]](_modules/diffprivlib/mechanisms/exponential.html#ExponentialCategorical)[¶](#diffprivlib.mechanisms.ExponentialCategorical "Permalink to this definition")

The exponential mechanism for achieving differential privacy on categorical inputs, as first proposed by McSherry

and Talwar.

The exponential mechanism achieves differential privacy by randomly choosing an output value for a given input

value, with greater probability given to values ‘closer’ to the input, as measured by a given utility function.

Paper link: <https://www.cs.drexel.edu/~greenie/privacy/mdviadp.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **utility\_list** (*list of tuples*) – The utility list of the mechanism. Must be specified as a list of tuples, of the form (“value1”, “value2”,

utility), where each value is a string and utility is a strictly positive float. A utility must be

specified for every pair of values given in the utility\_list.

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/exponential.html#ExponentialCategorical.randomise)[¶](#diffprivlib.mechanisms.ExponentialCategorical.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")

*class* diffprivlib.mechanisms.ExponentialHierarchical(*\**, *epsilon*, *hierarchy*)[[source]](_modules/diffprivlib/mechanisms/exponential.html#ExponentialHierarchical)[¶](#diffprivlib.mechanisms.ExponentialHierarchical "Permalink to this definition")

Adaptation of the exponential mechanism to hierarchical data. Simplifies the process of specifying utility values,

as the values can be inferred from the hierarchy.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **hierarchy** (*nested list of str*) – The hierarchy as specified as a nested list of string. Each string must be a leaf node, and each leaf node

must lie at the same depth in the hierarchy.

Examples

Example hierarchies:

```

>>> flat\_hierarchy = ["A", "B", "C", "D", "E"]

>>> nested\_hierarchy = [["A"], ["B"], ["C"], ["D", "E"]]

```

randomise(*value*)[¶](#diffprivlib.mechanisms.ExponentialHierarchical.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")

*class* diffprivlib.mechanisms.PermuteAndFlip(*\**, *epsilon*, *sensitivity*, *utility*, *candidates=None*)[[source]](_modules/diffprivlib/mechanisms/exponential.html#PermuteAndFlip)[¶](#diffprivlib.mechanisms.PermuteAndFlip "Permalink to this definition")

The permute and flip mechanism for achieving differential privacy on candidate selection, as first proposed by

McKenna and Sheldon.

The permute and flip mechanism is an alternative to the exponential mechanism, and achieves differential privacy by

randomly choosing a candidate subject to candidate utility scores, with greater probability given to higher-utility

candidates.

Paper link: <https://arxiv.org/pdf/2010.12603.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity in utility values to a change in a datapoint in the underlying dataset.

* **utility** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)")) – A list of non-negative utility values for each candidate.

* **candidates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)")*,* *optional*) – An optional list of candidate labels. If omitted, the zero-indexed list [0, 1, …, n] is used.

randomise(*value=None*)[[source]](_modules/diffprivlib/mechanisms/exponential.html#PermuteAndFlip.randomise)[¶](#diffprivlib.mechanisms.PermuteAndFlip.randomise "Permalink to this definition")

Select a candidate with differential privacy.

Parameters

**value** ([*None*](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")) – Ignored.

Returns

The randomised candidate.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") or other

### Gaussian mechanisms[¶](#gaussian-mechanisms "Permalink to this headline")

*class* diffprivlib.mechanisms.Gaussian(*\**, *epsilon*, *delta*, *sensitivity*)[[source]](_modules/diffprivlib/mechanisms/gaussian.html#Gaussian)[¶](#diffprivlib.mechanisms.Gaussian "Permalink to this definition")

The Gaussian mechanism in differential privacy.

As first proposed by Dwork and Roth in “The algorithmic foundations of differential privacy”.

Paper link: <https://www.nowpublishers.com/article/DownloadSummary/TCS-042>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, 1]. For `epsilon > 1`, use

[`GaussianAnalytic`](#diffprivlib.mechanisms.GaussianAnalytic "diffprivlib.mechanisms.GaussianAnalytic").

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\delta\) for the mechanism. Must be in (0, 1].

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity of the mechanism. Must be in [0, ∞).

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/gaussian.html#Gaussian.bias)[¶](#diffprivlib.mechanisms.Gaussian.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

mse(*value*)[¶](#diffprivlib.mechanisms.Gaussian.mse "Permalink to this definition")

Returns the mean squared error (MSE) of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the MSE of the mechanism is sought.

Returns

**bias** – The MSE of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/gaussian.html#Gaussian.randomise)[¶](#diffprivlib.mechanisms.Gaussian.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

variance(*value*)[[source]](_modules/diffprivlib/mechanisms/gaussian.html#Gaussian.variance)[¶](#diffprivlib.mechanisms.Gaussian.variance "Permalink to this definition")

Returns the variance of the mechanism at a given value.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the variance of the mechanism is sought.

Returns

**bias** – The variance of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

*class* diffprivlib.mechanisms.GaussianAnalytic(*\**, *epsilon*, *delta*, *sensitivity*)[[source]](_modules/diffprivlib/mechanisms/gaussian.html#GaussianAnalytic)[¶](#diffprivlib.mechanisms.GaussianAnalytic "Permalink to this definition")

The analytic Gaussian mechanism in differential privacy.

As first proposed by Balle and Wang in “Improving the Gaussian Mechanism for Differential Privacy: Analytical

Calibration and Optimal Denoising”.

Paper link: <https://arxiv.org/pdf/1805.06530.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\delta\) for the mechanism. Must be in (0, 1].

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity of the mechanism. Must be in [0, ∞).

bias(*value*)[¶](#diffprivlib.mechanisms.GaussianAnalytic.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

mse(*value*)[¶](#diffprivlib.mechanisms.GaussianAnalytic.mse "Permalink to this definition")

Returns the mean squared error (MSE) of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the MSE of the mechanism is sought.

Returns

**bias** – The MSE of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[¶](#diffprivlib.mechanisms.GaussianAnalytic.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

variance(*value*)[¶](#diffprivlib.mechanisms.GaussianAnalytic.variance "Permalink to this definition")

Returns the variance of the mechanism at a given value.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the variance of the mechanism is sought.

Returns

**bias** – The variance of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

*class* diffprivlib.mechanisms.GaussianDiscrete(*\**, *epsilon*, *delta*, *sensitivity=1*)[[source]](_modules/diffprivlib/mechanisms/gaussian.html#GaussianDiscrete)[¶](#diffprivlib.mechanisms.GaussianDiscrete "Permalink to this definition")

The Discrete Gaussian mechanism in differential privacy.

As proposed by Canonne, Kamath and Steinke, re-purposed for approximate \((\epsilon,\delta)\)-differential

privacy.

Paper link: <https://arxiv.org/pdf/2004.00010.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\delta\) for the mechanism. Must be in (0, 1].

* **sensitivity** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default: 1*) – The sensitivity of the mechanism. Must be in [0, ∞).

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/gaussian.html#GaussianDiscrete.bias)[¶](#diffprivlib.mechanisms.GaussianDiscrete.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/gaussian.html#GaussianDiscrete.randomise)[¶](#diffprivlib.mechanisms.GaussianDiscrete.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

### Geometric mechanisms[¶](#geometric-mechanisms "Permalink to this headline")

*class* diffprivlib.mechanisms.Geometric(*\**, *epsilon*, *sensitivity=1*)[[source]](_modules/diffprivlib/mechanisms/geometric.html#Geometric)[¶](#diffprivlib.mechanisms.Geometric "Permalink to this definition")

The classic geometric mechanism for differential privacy, as first proposed by Ghosh, Roughgarden and Sundararajan.

Extended to allow for non-unity sensitivity.

Paper link: <https://arxiv.org/pdf/0811.2841.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1*) – The sensitivity of the mechanism. Must be in [0, ∞).

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/geometric.html#Geometric.bias)[¶](#diffprivlib.mechanisms.Geometric.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

mse(*value*)[¶](#diffprivlib.mechanisms.Geometric.mse "Permalink to this definition")

Returns the mean squared error (MSE) of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the MSE of the mechanism is sought.

Returns

**bias** – The MSE of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/geometric.html#Geometric.randomise)[¶](#diffprivlib.mechanisms.Geometric.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

variance(*value*)[[source]](_modules/diffprivlib/mechanisms/geometric.html#Geometric.variance)[¶](#diffprivlib.mechanisms.Geometric.variance "Permalink to this definition")

Returns the variance of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the variance of the mechanism is sought.

Returns

**bias** – The variance of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

*class* diffprivlib.mechanisms.GeometricTruncated(*\**, *epsilon*, *sensitivity=1*, *lower*, *upper*)[[source]](_modules/diffprivlib/mechanisms/geometric.html#GeometricTruncated)[¶](#diffprivlib.mechanisms.GeometricTruncated "Permalink to this definition")

The truncated geometric mechanism, where values that fall outside a pre-described range are mapped back to the

closest point within the range.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1*) – The sensitivity of the mechanism. Must be in [0, ∞).

* **lower** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The lower bound of the mechanism.

* **upper** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The upper bound of the mechanism.

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/geometric.html#GeometricTruncated.randomise)[¶](#diffprivlib.mechanisms.GeometricTruncated.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

*class* diffprivlib.mechanisms.GeometricFolded(*\**, *epsilon*, *sensitivity=1*, *lower*, *upper*)[[source]](_modules/diffprivlib/mechanisms/geometric.html#GeometricFolded)[¶](#diffprivlib.mechanisms.GeometricFolded "Permalink to this definition")

The folded geometric mechanism, where values outside a pre-described range are folded back toward the domain around

the closest point within the domain.

Half-integer bounds are permitted.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1*) – The sensitivity of the mechanism. Must be in [0, ∞).

* **lower** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The lower bound of the mechanism. Must be integer or half-integer -valued.

* **upper** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The upper bound of the mechanism. Must be integer or half-integer -valued.

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/geometric.html#GeometricFolded.randomise)[¶](#diffprivlib.mechanisms.GeometricFolded.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

### Laplace mechanisms[¶](#laplace-mechanisms "Permalink to this headline")

*class* diffprivlib.mechanisms.Laplace(*\**, *epsilon*, *delta=0.0*, *sensitivity*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#Laplace)[¶](#diffprivlib.mechanisms.Laplace "Permalink to this definition")

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) \((\epsilon,\delta)\)-differential privacy, as proposed by Holohan et al.

Paper link: <https://arxiv.org/pdf/1402.6124.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in [0, ∞].

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 0.0*) – Privacy parameter \(\delta\) for the mechanism. Must be in [0, 1]. Cannot be simultaneously zero with

`epsilon`.

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity of the mechanism. Must be in [0, ∞).

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#Laplace.bias)[¶](#diffprivlib.mechanisms.Laplace.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

mse(*value*)[¶](#diffprivlib.mechanisms.Laplace.mse "Permalink to this definition")

Returns the mean squared error (MSE) of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the MSE of the mechanism is sought.

Returns

**bias** – The MSE of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#Laplace.randomise)[¶](#diffprivlib.mechanisms.Laplace.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

variance(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#Laplace.variance)[¶](#diffprivlib.mechanisms.Laplace.variance "Permalink to this definition")

Returns the variance of the mechanism at a given value.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the variance of the mechanism is sought.

Returns

**bias** – The variance of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

*class* diffprivlib.mechanisms.LaplaceTruncated(*\**, *epsilon*, *delta=0.0*, *sensitivity*, *lower*, *upper*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceTruncated)[¶](#diffprivlib.mechanisms.LaplaceTruncated "Permalink to this definition")

The truncated Laplace mechanism, where values outside a pre-described domain are mapped to the closest point

within the domain.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in [0, ∞].

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 0.0*) – Privacy parameter \(\delta\) for the mechanism. Must be in [0, 1]. Cannot be simultaneously zero with

`epsilon`.

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity of the mechanism. Must be in [0, ∞).

* **lower** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The lower bound of the mechanism.

* **upper** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The upper bound of the mechanism.

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceTruncated.bias)[¶](#diffprivlib.mechanisms.LaplaceTruncated.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

mse(*value*)[¶](#diffprivlib.mechanisms.LaplaceTruncated.mse "Permalink to this definition")

Returns the mean squared error (MSE) of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the MSE of the mechanism is sought.

Returns

**bias** – The MSE of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceTruncated.randomise)[¶](#diffprivlib.mechanisms.LaplaceTruncated.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

variance(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceTruncated.variance)[¶](#diffprivlib.mechanisms.LaplaceTruncated.variance "Permalink to this definition")

Returns the variance of the mechanism at a given value.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the variance of the mechanism is sought.

Returns

**bias** – The variance of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

*class* diffprivlib.mechanisms.LaplaceBoundedDomain(*\**, *epsilon*, *delta=0.0*, *sensitivity*, *lower*, *upper*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceBoundedDomain)[¶](#diffprivlib.mechanisms.LaplaceBoundedDomain "Permalink to this definition")

The bounded Laplace mechanism on a bounded domain. The mechanism draws values directly from the domain, without any

post-processing.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in [0, ∞].

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 0.0*) – Privacy parameter \(\delta\) for the mechanism. Must be in [0, 1]. Cannot be simultaneously zero with

`epsilon`.

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity of the mechanism. Must be in [0, ∞).

* **lower** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The lower bound of the mechanism.

* **upper** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The upper bound of the mechanism.

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceBoundedDomain.bias)[¶](#diffprivlib.mechanisms.LaplaceBoundedDomain.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

effective\_epsilon()[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceBoundedDomain.effective_epsilon)[¶](#diffprivlib.mechanisms.LaplaceBoundedDomain.effective_epsilon "Permalink to this definition")

Gets the effective epsilon of the mechanism, only for strict \(\epsilon\)-differential privacy. Returns

`None` if \(\delta\) is non-zero.

Returns

The effective \(\epsilon\) parameter of the mechanism. Returns `None` if delta is non-zero.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

mse(*value*)[¶](#diffprivlib.mechanisms.LaplaceBoundedDomain.mse "Permalink to this definition")

Returns the mean squared error (MSE) of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the MSE of the mechanism is sought.

Returns

**bias** – The MSE of the mechanism at value if defined, None otherwise.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceBoundedDomain.randomise)[¶](#diffprivlib.mechanisms.LaplaceBoundedDomain.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

variance(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceBoundedDomain.variance)[¶](#diffprivlib.mechanisms.LaplaceBoundedDomain.variance "Permalink to this definition")

Returns the variance of the mechanism at a given value.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the variance of the mechanism is sought.

Returns

**bias** – The variance of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

*class* diffprivlib.mechanisms.LaplaceBoundedNoise(*\**, *epsilon*, *delta*, *sensitivity*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceBoundedNoise)[¶](#diffprivlib.mechanisms.LaplaceBoundedNoise "Permalink to this definition")

The Laplace mechanism with bounded noise, only applicable for approximate differential privacy (delta > 0).

Epsilon must be strictly positive, epsilon > 0. delta must be strictly in the interval (0, 0.5).* For zero epsilon, use [`Uniform`](#diffprivlib.mechanisms.Uniform "diffprivlib.mechanisms.Uniform").

* For zero delta, use [`Laplace`](#diffprivlib.mechanisms.Laplace "diffprivlib.mechanisms.Laplace").

Paper link: <https://arxiv.org/pdf/1810.00877v1.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\delta\) for the mechanism. Must be in (0, 0.5).

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity of the mechanism. Must be in [0, ∞).

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceBoundedNoise.bias)[¶](#diffprivlib.mechanisms.LaplaceBoundedNoise.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceBoundedNoise.randomise)[¶](#diffprivlib.mechanisms.LaplaceBoundedNoise.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

*class* diffprivlib.mechanisms.LaplaceFolded(*\**, *epsilon*, *delta=0.0*, *sensitivity*, *lower*, *upper*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceFolded)[¶](#diffprivlib.mechanisms.LaplaceFolded "Permalink to this definition")

The folded Laplace mechanism, where values outside a pre-described domain are folded around the domain until they

fall within.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in [0, ∞].

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 0.0*) – Privacy parameter \(\delta\) for the mechanism. Must be in [0, 1]. Cannot be simultaneously zero with

`epsilon`.

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity of the mechanism. Must be in [0, ∞).

* **lower** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The lower bound of the mechanism.

* **upper** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The upper bound of the mechanism.

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceFolded.bias)[¶](#diffprivlib.mechanisms.LaplaceFolded.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/laplace.html#LaplaceFolded.randomise)[¶](#diffprivlib.mechanisms.LaplaceFolded.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

### Staircase mechanism[¶](#staircase-mechanism "Permalink to this headline")

*class* diffprivlib.mechanisms.Staircase(*\**, *epsilon*, *sensitivity*, *gamma=None*)[[source]](_modules/diffprivlib/mechanisms/staircase.html#Staircase)[¶](#diffprivlib.mechanisms.Staircase "Permalink to this definition")

The staircase mechanism in differential privacy.

The staircase mechanism is an optimisation of the classical Laplace Mechanism ([`Laplace`](#diffprivlib.mechanisms.Laplace "diffprivlib.mechanisms.Laplace")), described as a

“geometric mixture of uniform random variables”.

Paper link: <https://arxiv.org/pdf/1212.1186.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity of the mechanism. Must be in [0, ∞).

* **gamma** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1 /* *(**1 + exp**(**epsilon/2**)**)*) – Value of the tuning parameter gamma for the mechanism. Must be in [0, 1].

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/staircase.html#Staircase.bias)[¶](#diffprivlib.mechanisms.Staircase.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/staircase.html#Staircase.randomise)[¶](#diffprivlib.mechanisms.Staircase.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

### Uniform mechanism[¶](#uniform-mechanism "Permalink to this headline")

*class* diffprivlib.mechanisms.Uniform(*\**, *delta*, *sensitivity*)[[source]](_modules/diffprivlib/mechanisms/uniform.html#Uniform)[¶](#diffprivlib.mechanisms.Uniform "Permalink to this definition")

The Uniform mechanism in differential privacy.

This emerges as a special case of the [`LaplaceBoundedNoise`](#diffprivlib.mechanisms.LaplaceBoundedNoise "diffprivlib.mechanisms.LaplaceBoundedNoise") mechanism when epsilon = 0.

Paper link: <https://arxiv.org/pdf/1810.00877.pdf>

Parameters

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\delta\) for the mechanism. Must be in (0, 0.5].

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The sensitivity of the mechanism. Must be in [0, ∞).

bias(*value*)[[source]](_modules/diffprivlib/mechanisms/uniform.html#Uniform.bias)[¶](#diffprivlib.mechanisms.Uniform.bias "Permalink to this definition")

Returns the bias of the mechanism at a given value.

Parameters

**value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value at which the bias of the mechanism is sought.

Returns

**bias** – The bias of the mechanism at value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/uniform.html#Uniform.randomise)[¶](#diffprivlib.mechanisms.Uniform.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value to be randomised.

Returns

The randomised value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

### Vector mechanism[¶](#vector-mechanism "Permalink to this headline")

*class* diffprivlib.mechanisms.Vector(*\**, *epsilon*, *function\_sensitivity*, *data\_sensitivity=1.0*, *dimension*, *alpha=0.01*)[[source]](_modules/diffprivlib/mechanisms/vector.html#Vector)[¶](#diffprivlib.mechanisms.Vector "Permalink to this definition")

The vector mechanism in differential privacy.

The vector mechanism is used when perturbing convex objective functions.

Full paper: <http://www.jmlr.org/papers/volume12/chaudhuri11a/chaudhuri11a.pdf>

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Privacy parameter \(\epsilon\) for the mechanism. Must be in (0, ∞].

* **function\_sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The function sensitivity of the mechanism. Must be in [0, ∞).

* **data\_sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – The data sensitivityof the mechanism. Must be in [0, ∞).

* **dimension** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – Function input dimension. This dimension relates to the size of the input vector of the function being

considered by the mechanism. This corresponds to the size of the random vector produced by the mechanism. Must

be in [1, ∞).

* **alpha** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 0.01*) – Regularisation parameter. Must be in (0, ∞).

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/vector.html#Vector.randomise)[¶](#diffprivlib.mechanisms.Vector.randomise "Permalink to this definition")

Randomise value with the mechanism.

If value is a method of two outputs, they are taken as f and fprime (i.e., its gradient), and both are

perturbed accordingly.

Parameters

**value** (*method*) – The function to be randomised.

Returns

The randomised method.

Return type

method

### Wishart mechanism[¶](#wishart-mechanism "Permalink to this headline")

*class* diffprivlib.mechanisms.Wishart(*epsilon*, *sensitivity*)[[source]](_modules/diffprivlib/mechanisms/wishart.html#Wishart)[¶](#diffprivlib.mechanisms.Wishart "Permalink to this definition")

The Wishart mechanism in differential privacy.

Used to achieve differential privacy on 2nd moment matrices.

Paper link: <https://ieeexplore.ieee.org/abstract/document/7472095/>

Deprecated since version 0.4: Wishart is deprecated and will be removed in version 0.5. The Wishart mechanism has been shown not to satisfy

differential privacy, and its continued use is not recommended.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The value of epsilon for achieving \((\epsilon,\delta)\)-differential privacy with the mechanism. Must be

> 0.

* **sensitivity** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The maximum l2-norm of the data. Must be >= 0.

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/wishart.html#Wishart.randomise)[¶](#diffprivlib.mechanisms.Wishart.randomise "Permalink to this definition")

Randomise value with the mechanism.

Parameters

**value** (*numpy array*) – The data to be randomised.

Returns

The randomised array.

Return type

numpy array

[`diffprivlib.mechanisms.transforms`](#module-diffprivlib.mechanisms.transforms "diffprivlib.mechanisms.transforms")[¶](#module-diffprivlib.mechanisms.transforms "Permalink to this headline")

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Transform wrappers for differential privacy mechanisms to extend their use to alternative data types.

Notes

The naming convention for new transforms is to describe the pre-transform action, i.e. the action performed on the

data to be ingested by the mechanism. For transforms without a pre-transform, the post-transform action should be

described.

### Base class[¶](#base-class "Permalink to this headline")

*class* diffprivlib.mechanisms.transforms.DPTransformer(*parent*)[[source]](_modules/diffprivlib/mechanisms/transforms/base.html#DPTransformer)[¶](#diffprivlib.mechanisms.transforms.DPTransformer "Permalink to this definition")

Base class for DP transformers. DP Transformers are simple wrappers for DP Mechanisms to allow mechanisms to be

used with data types and structures outside their scope.

A [`DPTransformer`](#diffprivlib.mechanisms.transforms.DPTransformer "diffprivlib.mechanisms.transforms.DPTransformer") must be initiated with a [`DPMachine`](index.html#diffprivlib.mechanisms.DPMachine "diffprivlib.mechanisms.DPMachine") (either another [`DPTransformer`](#diffprivlib.mechanisms.transforms.DPTransformer "diffprivlib.mechanisms.transforms.DPTransformer"), or a

[`DPMechanism`](index.html#diffprivlib.mechanisms.DPMechanism "diffprivlib.mechanisms.DPMechanism")). This allows many instances of [`DPTransformer`](#diffprivlib.mechanisms.transforms.DPTransformer "diffprivlib.mechanisms.transforms.DPTransformer") to be chained together, but the chain

must terminate with a [`DPMechanism`](index.html#diffprivlib.mechanisms.DPMechanism "diffprivlib.mechanisms.DPMechanism").

copy()[¶](#diffprivlib.mechanisms.transforms.DPTransformer.copy "Permalink to this definition")

Produces a copy of the class.

Returns

**self** – Returns the copy.

Return type

class

post\_transform(*value*)[[source]](_modules/diffprivlib/mechanisms/transforms/base.html#DPTransformer.post_transform)[¶](#diffprivlib.mechanisms.transforms.DPTransformer.post_transform "Permalink to this definition")

Performs no transformation on the output of the mechanism, and is returned as-is.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Mechanism output to be transformed.

Returns

Transformed output value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or string

pre\_transform(*value*)[[source]](_modules/diffprivlib/mechanisms/transforms/base.html#DPTransformer.pre_transform)[¶](#diffprivlib.mechanisms.transforms.DPTransformer.pre_transform "Permalink to this definition")

Performs no transformation on the input data, and is ingested by the mechanism as-is.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Input value to be transformed.

Returns

Transformed input value

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or string

randomise(*value*)[[source]](_modules/diffprivlib/mechanisms/transforms/base.html#DPTransformer.randomise)[¶](#diffprivlib.mechanisms.transforms.DPTransformer.randomise "Permalink to this definition")

Randomise the given value using the [`DPMachine`](index.html#diffprivlib.mechanisms.DPMachine "diffprivlib.mechanisms.DPMachine").

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Value to be randomised.

Returns

Randomised value, same type as value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or string

### Type casting transforms[¶](#type-casting-transforms "Permalink to this headline")

*class* diffprivlib.mechanisms.transforms.IntToString(*parent*)[[source]](_modules/diffprivlib/mechanisms/transforms/inttostring.html#IntToString)[¶](#diffprivlib.mechanisms.transforms.IntToString "Permalink to this definition")

IntToString DP transformer, for using integer-valued data with string-valued mechanisms.

Useful when using integer-valued data with [`Binary`](index.html#diffprivlib.mechanisms.Binary "diffprivlib.mechanisms.Binary") or [`Exponential`](index.html#diffprivlib.mechanisms.Exponential "diffprivlib.mechanisms.Exponential").

post\_transform(*value*)[[source]](_modules/diffprivlib/mechanisms/transforms/inttostring.html#IntToString.post_transform)[¶](#diffprivlib.mechanisms.transforms.IntToString.post_transform "Permalink to this definition")

Transforms the output of the mechanism to be integer-valued.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Mechanism output to be transformed.

Returns

Transformed output value.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

pre\_transform(*value*)[[source]](_modules/diffprivlib/mechanisms/transforms/inttostring.html#IntToString.pre_transform)[¶](#diffprivlib.mechanisms.transforms.IntToString.pre_transform "Permalink to this definition")

Transforms the input to be string-valued for ingestion by the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Input value to be transformed.

Returns

Transformed input value

Return type

string

randomise(*value*)[¶](#diffprivlib.mechanisms.transforms.IntToString.randomise "Permalink to this definition")

Randomise the given value using the [`DPMachine`](index.html#diffprivlib.mechanisms.DPMachine "diffprivlib.mechanisms.DPMachine").

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Value to be randomised.

Returns

Randomised value, same type as value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or string

*class* diffprivlib.mechanisms.transforms.StringToInt(*parent*)[[source]](_modules/diffprivlib/mechanisms/transforms/stringtoint.html#StringToInt)[¶](#diffprivlib.mechanisms.transforms.StringToInt "Permalink to this definition")

StringToInt DP transformer, for using string-valued data with integer-valued mechanisms.

Useful when using ordered, string-valued data with [`Geometric`](index.html#diffprivlib.mechanisms.Geometric "diffprivlib.mechanisms.Geometric").

post\_transform(*value*)[[source]](_modules/diffprivlib/mechanisms/transforms/stringtoint.html#StringToInt.post_transform)[¶](#diffprivlib.mechanisms.transforms.StringToInt.post_transform "Permalink to this definition")

Transforms the output of the mechanism to be string-valued.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Mechanism output to be transformed.

Returns

Transformed output value.

Return type

string

pre\_transform(*value*)[[source]](_modules/diffprivlib/mechanisms/transforms/stringtoint.html#StringToInt.pre_transform)[¶](#diffprivlib.mechanisms.transforms.StringToInt.pre_transform "Permalink to this definition")

Transforms the input to be integer-valued for ingestion by the mechanism.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Input value to be transformed.

Returns

Transformed input value

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

randomise(*value*)[¶](#diffprivlib.mechanisms.transforms.StringToInt.randomise "Permalink to this definition")

Randomise the given value using the [`DPMachine`](index.html#diffprivlib.mechanisms.DPMachine "diffprivlib.mechanisms.DPMachine").

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Value to be randomised.

Returns

Randomised value, same type as value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or string

### Other transforms[¶](#other-transforms "Permalink to this headline")

*class* diffprivlib.mechanisms.transforms.RoundedInteger(*parent*)[[source]](_modules/diffprivlib/mechanisms/transforms/roundedinteger.html#RoundedInteger)[¶](#diffprivlib.mechanisms.transforms.RoundedInteger "Permalink to this definition")

Rounded integer transform. Rounds the (float) output of the given mechanism to the nearest integer.

post\_transform(*value*)[[source]](_modules/diffprivlib/mechanisms/transforms/roundedinteger.html#RoundedInteger.post_transform)[¶](#diffprivlib.mechanisms.transforms.RoundedInteger.post_transform "Permalink to this definition")

Transforms the (float) output of the mechanism to be a rounded integer.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Mechanism output to be transformed.

Returns

Transformed output value.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

pre\_transform(*value*)[¶](#diffprivlib.mechanisms.transforms.RoundedInteger.pre_transform "Permalink to this definition")

Performs no transformation on the input data, and is ingested by the mechanism as-is.

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Input value to be transformed.

Returns

Transformed input value

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or string

randomise(*value*)[¶](#diffprivlib.mechanisms.transforms.RoundedInteger.randomise "Permalink to this definition")

Randomise the given value using the [`DPMachine`](index.html#diffprivlib.mechanisms.DPMachine "diffprivlib.mechanisms.DPMachine").

Parameters

**value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *string*) – Value to be randomised.

Returns

Randomised value, same type as value.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or string

[`diffprivlib.tools`](#module-diffprivlib.tools "diffprivlib.tools")[¶](#module-diffprivlib.tools "Permalink to this headline")

-------------------------------------------------------------------------------------------------------------------------------

Tools for data analysis with differential privacy.

### Histogram functions[¶](#histogram-functions "Permalink to this headline")

diffprivlib.tools.histogram(*sample*, *epsilon=1.0*, *bins=10*, *range=None*, *weights=None*, *density=None*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/histograms.html#histogram)[¶](#diffprivlib.tools.histogram "Permalink to this definition")

Compute the differentially private histogram of a set of data.

The histogram is computed using [`numpy.histogram`](https://numpy.org/doc/stable/reference/generated/numpy.histogram.html#numpy.histogram "(in NumPy v1.21)"), and noise added using [`GeometricTruncated`](index.html#diffprivlib.mechanisms.GeometricTruncated "diffprivlib.mechanisms.GeometricTruncated") to

satisfy differential privacy. If the range parameter is not specified correctly, a [`PrivacyLeakWarning`](index.html#diffprivlib.utils.PrivacyLeakWarning "diffprivlib.utils.PrivacyLeakWarning")

is thrown. Users are referred to [`numpy.histogram`](https://numpy.org/doc/stable/reference/generated/numpy.histogram.html#numpy.histogram "(in NumPy v1.21)") for more usage notes.

Parameters

* **sample** (*array\_like*) – Input data. The histogram is computed over the flattened array.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\) to be applied.

* **bins** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *sequence of scalars* *or* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default: 10*) – If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins

is a sequence, it defines a monotonically increasing array of bin edges, including the rightmost edge, allowing

for non-uniform bin widths.

If bins is a string, it defines the method used to calculate the optimal bin width, as defined by

histogram\_bin\_edges.

* **range** (*(*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*)**,* *optional*) – The lower and upper range of the bins. If not provided, range is simply `(a.min(), a.max())`. Values outside

the range are ignored. The first element of the range must be less than or equal to the second. range affects

the automatic bin computation as well. While bin width is computed to be optimal based on the actual data

within range, the bin count will fill the entire range including portions containing no data.

* **weights** (*array\_like**,* *optional*) – An array of weights, of the same shape as a. Each value in a only contributes its associated weight

towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral

of the density over the range remains 1.

* **density** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *optional*) – If `False`, the result will contain the number of samples in each bin. If `True`, the result is the value

of the probability *density* function at the bin, normalized such that the *integral* over the range is 1.

Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is

not a probability *mass* function.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

* **hist** (*array*) – The values of the histogram. See density and weights for a

description of the possible semantics.

* **bin\_edges** (*array of dtype float*) – Return the bin edges `(length(hist)+1)`.

See also

[`histogramdd`](#diffprivlib.tools.histogramdd "diffprivlib.tools.histogramdd"), [`histogram2d`](#diffprivlib.tools.histogram2d "diffprivlib.tools.histogram2d")

Notes

All but the last (righthand-most) bin is half-open. In other words, if bins is:

```

[1, 2, 3, 4]

```

then the first bin is `[1, 2)` (including 1, but excluding 2) and the second `[2, 3)`. The last bin, however,

is `[3, 4]`, which *includes* 4.

diffprivlib.tools.histogramdd(*sample*, *epsilon=1.0*, *bins=10*, *range=None*, *weights=None*, *density=None*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/histograms.html#histogramdd)[¶](#diffprivlib.tools.histogramdd "Permalink to this definition")

Compute the differentially private multidimensional histogram of some data.

The histogram is computed using [`numpy.histogramdd`](https://numpy.org/doc/stable/reference/generated/numpy.histogramdd.html#numpy.histogramdd "(in NumPy v1.21)"), and noise added using [`GeometricTruncated`](index.html#diffprivlib.mechanisms.GeometricTruncated "diffprivlib.mechanisms.GeometricTruncated") to

satisfy differential privacy. If the range parameter is not specified correctly, a [`PrivacyLeakWarning`](index.html#diffprivlib.utils.PrivacyLeakWarning "diffprivlib.utils.PrivacyLeakWarning")

is thrown. Users are referred to [`numpy.histogramdd`](https://numpy.org/doc/stable/reference/generated/numpy.histogramdd.html#numpy.histogramdd "(in NumPy v1.21)") for more usage notes.

Parameters

* **sample** (*(**N**,* *D**)* *array**, or* *(**D**,* *N**)* *array\_like*) – The data to be histogrammed.

Note the unusual interpretation of sample when an array\_like:

	+ When an array, each row is a coordinate in a D-dimensional space - such as

	`histogramgramdd(np.array([p1, p2, p3]))`.

	+ When an array\_like, each element is the list of values for single coordinate - such as

	`histogramgramdd((X, Y, Z))`.

The first form should be preferred.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\) to be applied.

* **bins** (*sequence* *or* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default: 10*) – The bin specification:

	+ A sequence of arrays describing the monotonically increasing bin edges along each dimension.

	+ The number of bins for each dimension (nx, ny, … =bins)

	+ The number of bins for all dimensions (nx=ny=…=bins).

* **range** (*sequence**,* *optional*) – A sequence of length D, each an optional (lower, upper) tuple giving the outer bin edges to be used if the edges

are not given explicitly in bins.

An entry of None in the sequence results in the minimum and maximum values being used for the corresponding

dimension.

The default, None, is equivalent to passing a tuple of D None values.

* **density** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *optional*) – If False, the default, returns the number of samples in each bin. If True, returns the probability *density*

function at the bin, `bin\_count / sample\_count / bin\_volume`.

* **weights** (*(**N**,**)* *array\_like**,* *optional*) – An array of values w\_i weighing each sample (x\_i, y\_i, z\_i, …). Weights are normalized to 1 if normed is

True. If normed is False, the values of the returned histogram are equal to the sum of the weights belonging to

the samples falling into each bin.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

* **H** (*ndarray*) – The multidimensional histogram of sample x. See normed and weights for the different possible semantics.

* **edges** (*list*) – A list of D arrays describing the bin edges for each dimension.

See also

[`histogram`](#diffprivlib.tools.histogram "diffprivlib.tools.histogram")1-D differentially private histogram

[`histogram2d`](#diffprivlib.tools.histogram2d "diffprivlib.tools.histogram2d")2-D differentially private histogram

diffprivlib.tools.histogram2d(*array\_x*, *array\_y*, *epsilon=1.0*, *bins=10*, *range=None*, *weights=None*, *density=None*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/histograms.html#histogram2d)[¶](#diffprivlib.tools.histogram2d "Permalink to this definition")

Compute the differentially private bi-dimensional histogram of two data samples.

Parameters

* **array\_x** (*array\_like**,* *shape* *(**N**,**)*) – An array containing the x coordinates of the points to be histogrammed.

* **array\_y** (*array\_like**,* *shape* *(**N**,**)*) – An array containing the y coordinates of the points to be histogrammed.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\) to be applied.

* **bins** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *array\_like* *or* *[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*] or* *[**array**,* *array**]**,* *default: 10*) – The bin specification:

> 

> 

> 	+ If int, the number of bins for the two dimensions (nx=ny=bins).

> 	+ If array\_like, the bin edges for the two dimensions (x\_edges=y\_edges=bins).

> 	+ If [int, int], the number of bins in each dimension (nx, ny = bins).

> 	+ If [array, array], the bin edges in each dimension (x\_edges, y\_edges = bins).

> 	+ A combination [int, array] or [array, int], where int is the number of bins and array is the bin edges.

>

* **range** (*array\_like**,* *shape**(**2**,**2**)**,* *optional*) – The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins

parameters): `[[xmin, xmax], [ymin, ymax]]`. All values outside of this range will be considered outliers and

not tallied in the histogram.

* **density** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *optional*) – If False, the default, returns the number of samples in each bin. If True, returns the probability *density*

function at the bin, `bin\_count / sample\_count / bin\_area`.

* **weights** (*array\_like**,* *shape**(**N**,**)**,* *optional*) – An array of values `w\_i` weighing each sample `(x\_i, y\_i)`. Weights are normalized to 1 if normed is

True. If normed is False, the values of the returned histogram are equal to the sum of the weights belonging

to the samples falling into each bin.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

* **H** (*ndarray, shape(nx, ny)*) – The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension

and values in y are histogrammed along the second dimension.

* **xedges** (*ndarray, shape(nx+1,)*) – The bin edges along the first dimension.

* **yedges** (*ndarray, shape(ny+1,)*) – The bin edges along the second dimension.

See also

[`histogram`](#diffprivlib.tools.histogram "diffprivlib.tools.histogram")1D differentially private histogram

[`histogramdd`](#diffprivlib.tools.histogramdd "diffprivlib.tools.histogramdd")Differentially private Multidimensional histogram

Notes

When normed is True, then the returned histogram is the sample density, defined such that the sum over bins of the

product `bin\_value \* bin\_area` is 1.

Please note that the histogram does not follow the Cartesian convention where x values are on the abscissa and y

values on the ordinate axis. Rather, x is histogrammed along the first dimension of the array (vertical), and y

along the second dimension of the array (horizontal). This ensures compatibility with histogramdd.

### General Utilities[¶](#general-utilities "Permalink to this headline")

diffprivlib.tools.count\_nonzero(*array*, *epsilon=1.0*, *accountant=None*, *axis=None*, *keepdims=False*)[[source]](_modules/diffprivlib/tools/utils.html#count_nonzero)[¶](#diffprivlib.tools.count_nonzero "Permalink to this definition")

Counts the number of non-zero values in the array `array` with differential privacy.

The word “non-zero” is in reference to the Python 2.x built-in method `\_\_nonzero\_\_()` (renamed `\_\_bool\_\_()` in

Python 3.x) of Python objects that tests an object’s “truthfulness”. For example, any number is considered truthful

if it is nonzero, whereas any string is considered truthful if it is not the empty string. Thus, this function

(recursively) counts how many elements in `array` (and in sub-arrays thereof) have their `\_\_nonzero\_\_()` or

`\_\_bool\_\_()` method evaluated to `True`.

Parameters

* **array** (*array\_like*) – The array for which to count non-zeros.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

* **axis** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted

along a flattened version of `array`.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes that are counted are left in the result as dimensions with size one. With this

option, the result will broadcast correctly against the input array.

Returns

**count** – Differentially private number of non-zero values in the array along a given axis. Otherwise, the total number

of non-zero values in the array is returned.

Return type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") or array of int

diffprivlib.tools.mean(*array*, *epsilon=1.0*, *bounds=None*, *axis=None*, *dtype=None*, *keepdims=False*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/utils.html#mean)[¶](#diffprivlib.tools.mean "Permalink to this definition")

Compute the differentially private arithmetic mean along the specified axis.

Returns the average of the array elements with differential privacy. The average is taken over the flattened array

by default, otherwise over the specified axis. Noise is added using [`Laplace`](index.html#diffprivlib.mechanisms.Laplace "diffprivlib.mechanisms.Laplace") to satisfy differential

privacy, where sensitivity is calculated using bounds. Users are advised to consult the documentation of

[`numpy.mean`](https://numpy.org/doc/stable/reference/generated/numpy.mean.html#numpy.mean "(in NumPy v1.21)") for further details, as the behaviour of mean closely follows its Numpy variant.

Parameters

* **array** (*array\_like*) – Array containing numbers whose mean is desired. If array is not an array, a conversion is attempted.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **axis** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

If this is a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as

before.

* **dtype** (*data-type**,* *optional*) – Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it

is the same as the input dtype.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

**m** – Returns a new array containing the mean values.

Return type

ndarray, see dtype parameter above

See also

[`std`](#diffprivlib.tools.std "diffprivlib.tools.std"), [`var`](#diffprivlib.tools.var "diffprivlib.tools.var"), [`nanmean`](#diffprivlib.tools.nanmean "diffprivlib.tools.nanmean")

diffprivlib.tools.nanmean(*array*, *epsilon=1.0*, *bounds=None*, *axis=None*, *dtype=None*, *keepdims=False*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/utils.html#nanmean)[¶](#diffprivlib.tools.nanmean "Permalink to this definition")

Compute the differentially private arithmetic mean along the specified axis, ignoring NaNs.

Returns the average of the array elements with differential privacy. The average is taken over the flattened array

by default, otherwise over the specified axis. Noise is added using [`Laplace`](index.html#diffprivlib.mechanisms.Laplace "diffprivlib.mechanisms.Laplace") to satisfy differential

privacy, where sensitivity is calculated using bounds. Users are advised to consult the documentation of

[`numpy.mean`](https://numpy.org/doc/stable/reference/generated/numpy.mean.html#numpy.mean "(in NumPy v1.21)") for further details, as the behaviour of mean closely follows its Numpy variant.

For all-NaN slices, NaN is returned and a RuntimeWarning is raised.

Parameters

* **array** (*array\_like*) – Array containing numbers whose mean is desired. If array is not an array, a conversion is attempted.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **axis** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

If this is a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as

before.

* **dtype** (*data-type**,* *optional*) – Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it

is the same as the input dtype.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

**m** – Returns a new array containing the mean values.

Return type

ndarray, see dtype parameter above

See also

[`std`](#diffprivlib.tools.std "diffprivlib.tools.std"), [`var`](#diffprivlib.tools.var "diffprivlib.tools.var"), [`mean`](#diffprivlib.tools.mean "diffprivlib.tools.mean")

diffprivlib.tools.std(*array*, *epsilon=1.0*, *bounds=None*, *axis=None*, *dtype=None*, *keepdims=False*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/utils.html#std)[¶](#diffprivlib.tools.std "Permalink to this definition")

Compute the standard deviation along the specified axis.

Returns the standard deviation of the array elements, a measure of the spread of a distribution, with differential

privacy. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

Noise is added using [`LaplaceBoundedDomain`](index.html#diffprivlib.mechanisms.LaplaceBoundedDomain "diffprivlib.mechanisms.LaplaceBoundedDomain") to satisfy differential privacy, where sensitivity is

calculated using bounds. Users are advised to consult the documentation of [`numpy.std`](https://numpy.org/doc/stable/reference/generated/numpy.std.html#numpy.std "(in NumPy v1.21)") for further details,

as the behaviour of std closely follows its Numpy variant.

Parameters

* **array** (*array\_like*) – Calculate the standard deviation of these values.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **axis** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation

of the flattened array.

If this is a tuple of ints, a standard deviation is performed over multiple axes, instead of a single axis or

all the axes as before.

* **dtype** (*dtype**,* *optional*) – Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays

of float types it is the same as the array type.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

**standard\_deviation** – Return a new array containing the standard deviation.

Return type

ndarray, see dtype parameter above.

See also

[`var`](#diffprivlib.tools.var "diffprivlib.tools.var"), [`mean`](#diffprivlib.tools.mean "diffprivlib.tools.mean"), [`nanstd`](#diffprivlib.tools.nanstd "diffprivlib.tools.nanstd")

diffprivlib.tools.nanstd(*array*, *epsilon=1.0*, *bounds=None*, *axis=None*, *dtype=None*, *keepdims=False*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/utils.html#nanstd)[¶](#diffprivlib.tools.nanstd "Permalink to this definition")

Compute the standard deviation along the specified axis, ignoring NaNs.

Returns the standard deviation of the array elements, a measure of the spread of a distribution, with differential

privacy. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

Noise is added using [`LaplaceBoundedDomain`](index.html#diffprivlib.mechanisms.LaplaceBoundedDomain "diffprivlib.mechanisms.LaplaceBoundedDomain") to satisfy differential privacy, where sensitivity is

calculated using bounds. Users are advised to consult the documentation of [`numpy.std`](https://numpy.org/doc/stable/reference/generated/numpy.std.html#numpy.std "(in NumPy v1.21)") for further details,

as the behaviour of std closely follows its Numpy variant.

For all-NaN slices, NaN is returned and a RuntimeWarning is raised.

Parameters

* **array** (*array\_like*) – Calculate the standard deviation of these values.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **axis** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation

of the flattened array.

If this is a tuple of ints, a standard deviation is performed over multiple axes, instead of a single axis or

all the axes as before.

* **dtype** (*dtype**,* *optional*) – Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays

of float types it is the same as the array type.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

**standard\_deviation** – Return a new array containing the standard deviation.

Return type

ndarray, see dtype parameter above.

See also

[`var`](#diffprivlib.tools.var "diffprivlib.tools.var"), [`mean`](#diffprivlib.tools.mean "diffprivlib.tools.mean"), [`std`](#diffprivlib.tools.std "diffprivlib.tools.std")

diffprivlib.tools.sum(*array*, *epsilon=1.0*, *bounds=None*, *accountant=None*, *axis=None*, *dtype=None*, *keepdims=False*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/utils.html#sum)[¶](#diffprivlib.tools.sum "Permalink to this definition")

Sum of array elements over a given axis with differential privacy.

Parameters

* **array** (*array\_like*) – Elements to sum.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

* **axis** ([*None*](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)") *or* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input

array. If axis is negative it counts from the last to the first axis.

If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single

axis or all the axes as before.

* **dtype** (*dtype**,* *optional*) – The type of the returned array and of the accumulator in which the elements are summed. The dtype of array is

used by default unless array has an integer dtype of less precision than the default platform integer. In

that case, if array is signed then the platform integer is used while if array is unsigned then an unsigned

integer of the same precision as the platform integer is used.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

Returns

**sum\_along\_axis** – An array with the same shape as array, with the specified axis removed. If array is a 0-d array, or if

axis is None, a scalar is returned.

Return type

ndarray

See also

`ndarray.sum`Equivalent non-private method.

[`mean`](#diffprivlib.tools.mean "diffprivlib.tools.mean"), [`nansum`](#diffprivlib.tools.nansum "diffprivlib.tools.nansum")

diffprivlib.tools.nansum(*array*, *epsilon=1.0*, *bounds=None*, *accountant=None*, *axis=None*, *dtype=None*, *keepdims=False*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/utils.html#nansum)[¶](#diffprivlib.tools.nansum "Permalink to this definition")

Sum of array elements over a given axis with differential privacy, ignoring NaNs.

Parameters

* **array** (*array\_like*) – Elements to sum.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

* **axis** ([*None*](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)") *or* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input

array. If axis is negative it counts from the last to the first axis.

If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single

axis or all the axes as before.

* **dtype** (*dtype**,* *optional*) – The type of the returned array and of the accumulator in which the elements are summed. The dtype of array is

used by default unless array has an integer dtype of less precision than the default platform integer. In

that case, if array is signed then the platform integer is used while if array is unsigned then an unsigned

integer of the same precision as the platform integer is used.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

Returns

**sum\_along\_axis** – An array with the same shape as array, with the specified axis removed. If array is a 0-d array, or if

axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

Return type

ndarray

See also

`ndarray.sum`Equivalent non-private method.

[`mean`](#diffprivlib.tools.mean "diffprivlib.tools.mean"), [`sum`](#diffprivlib.tools.sum "diffprivlib.tools.sum")

diffprivlib.tools.var(*array*, *epsilon=1.0*, *bounds=None*, *axis=None*, *dtype=None*, *keepdims=False*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/utils.html#var)[¶](#diffprivlib.tools.var "Permalink to this definition")

Compute the differentially private variance along the specified axis.

Returns the variance of the array elements, a measure of the spread of a distribution, with differential privacy.

The variance is computer for the flattened array by default, otherwise over the specified axis. Noise is added

using [`LaplaceBoundedDomain`](index.html#diffprivlib.mechanisms.LaplaceBoundedDomain "diffprivlib.mechanisms.LaplaceBoundedDomain") to satisfy differential privacy, where sensitivity is calculated using

bounds. Users are advised to consult the documentation of [`numpy.var`](https://numpy.org/doc/stable/reference/generated/numpy.var.html#numpy.var "(in NumPy v1.21)") for further details, as the behaviour

of var closely follows its Numpy variant.

Parameters

* **array** (*array\_like*) – Array containing numbers whose variance is desired. If array is not an array, a conversion is attempted.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **axis** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which the variance is computed. The default is to compute the variance of the flattened

array.

If this is a tuple of ints, a variance is performed over multiple axes, instead of a single axis or all the axes

as before.

* **dtype** (*data-type**,* *optional*) – Type to use in computing the variance. For arrays of integer type the default is float32; for arrays of float

types it is the same as the array type.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

**variance** – Returns a new array containing the variance.

Return type

ndarray, see dtype parameter above

See also

[`std`](#diffprivlib.tools.std "diffprivlib.tools.std"), [`mean`](#diffprivlib.tools.mean "diffprivlib.tools.mean"), [`nanvar`](#diffprivlib.tools.nanvar "diffprivlib.tools.nanvar")

diffprivlib.tools.nanvar(*array*, *epsilon=1.0*, *bounds=None*, *axis=None*, *dtype=None*, *keepdims=False*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/utils.html#nanvar)[¶](#diffprivlib.tools.nanvar "Permalink to this definition")

Compute the differentially private variance along the specified axis, ignoring NaNs.

Returns the variance of the array elements, a measure of the spread of a distribution, with differential privacy.

The variance is computer for the flattened array by default, otherwise over the specified axis. Noise is added

using [`LaplaceBoundedDomain`](index.html#diffprivlib.mechanisms.LaplaceBoundedDomain "diffprivlib.mechanisms.LaplaceBoundedDomain") to satisfy differential privacy, where sensitivity is calculated using

bounds. Users are advised to consult the documentation of [`numpy.var`](https://numpy.org/doc/stable/reference/generated/numpy.var.html#numpy.var "(in NumPy v1.21)") for further details, as the behaviour

of var closely follows its Numpy variant.

For all-NaN slices, NaN is returned and a RuntimeWarning is raised.

Parameters

* **array** (*array\_like*) – Array containing numbers whose variance is desired. If array is not an array, a conversion is attempted.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **axis** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which the variance is computed. The default is to compute the variance of the flattened

array.

If this is a tuple of ints, a variance is performed over multiple axes, instead of a single axis or all the axes

as before.

* **dtype** (*data-type**,* *optional*) – Type to use in computing the variance. For arrays of integer type the default is float32; for arrays of float

types it is the same as the array type.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

**variance** – If `out=None`, returns a new array containing the variance; otherwise, a reference to the output array is

returned.

Return type

ndarray, see dtype parameter above

See also

[`std`](#diffprivlib.tools.std "diffprivlib.tools.std"), [`mean`](#diffprivlib.tools.mean "diffprivlib.tools.mean"), [`var`](#diffprivlib.tools.var "diffprivlib.tools.var")

### Quantile-like functions[¶](#quantile-like-functions "Permalink to this headline")

diffprivlib.tools.quantile(*array*, *quant*, *epsilon=1.0*, *bounds=None*, *axis=None*, *keepdims=False*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/quantiles.html#quantile)[¶](#diffprivlib.tools.quantile "Permalink to this definition")

Compute the differentially private quantile of the array.

Returns the specified quantile with differential privacy. The quantile is calculated over the flattened array.

Differential privacy is achieved with the [`Exponential`](index.html#diffprivlib.mechanisms.Exponential "diffprivlib.mechanisms.Exponential") mechanism, using the method first proposed by

Smith, 2011.

Paper link: <https://dl.acm.org/doi/pdf/10.1145/1993636.1993743>

Parameters

* **array** (*array\_like*) – Array containing numbers whose quantile is sought. If array is not an array, a conversion is attempted.

* **quant** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *array-like*) – Quantile or array of quantiles. Each quantile must be in the unit interval [0, 1]. If quant is array-like,

quantiles are returned over the flattened array.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\). Differential privacy is achieved over the entire output, with epsilon split

evenly between each output value.

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **axis** ([*None*](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)") *or* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input

array. If axis is negative it counts from the last to the first axis.

If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single

axis or all the axes as before.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes

of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any

exceptions will be raised.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

**m** – Returns a new array containing the quantile values.

Return type

ndarray

See also

[`numpy.quantile`](https://numpy.org/doc/stable/reference/generated/numpy.quantile.html#numpy.quantile "(in NumPy v1.21)")Equivalent non-private method.

[`percentile`](#diffprivlib.tools.percentile "diffprivlib.tools.percentile"), [`median`](#diffprivlib.tools.median "diffprivlib.tools.median")

diffprivlib.tools.percentile(*array*, *percent*, *epsilon=1.0*, *bounds=None*, *axis=None*, *keepdims=False*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/quantiles.html#percentile)[¶](#diffprivlib.tools.percentile "Permalink to this definition")

Compute the differentially private percentile of the array.

This method calls [`quantile`](#diffprivlib.tools.quantile "diffprivlib.tools.quantile"), where quantile = percentile / 100.

Parameters

* **array** (*array\_like*) – Array containing numbers whose percentile is sought. If array is not an array, a conversion is attempted.

* **percent** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") *or* *array-like*) – Percentile or list of percentiles sought. Each percentile must be in [0, 100]. If percent is array-like,

percentiles are returned over the flattened array.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\). Differential privacy is achieved over the entire output, with epsilon split

evenly between each output value.

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **axis** ([*None*](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)") *or* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input

array. If axis is negative it counts from the last to the first axis.

If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single

axis or all the axes as before.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes

of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any

exceptions will be raised.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

**m** – Returns a new array containing the percentile values.

Return type

ndarray

See also

[`numpy.percentile`](https://numpy.org/doc/stable/reference/generated/numpy.percentile.html#numpy.percentile "(in NumPy v1.21)")Equivalent non-private method.

[`quantile`](#diffprivlib.tools.quantile "diffprivlib.tools.quantile"), [`median`](#diffprivlib.tools.median "diffprivlib.tools.median")

diffprivlib.tools.median(*array*, *epsilon=1.0*, *bounds=None*, *axis=None*, *keepdims=False*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/tools/quantiles.html#median)[¶](#diffprivlib.tools.median "Permalink to this definition")

Compute the differentially private median of the array.

Returns the median with differential privacy. The median is calculated over each axis, or the flattened array

if an axis is not provided. This method calls the [`quantile`](#diffprivlib.tools.quantile "diffprivlib.tools.quantile") method, for the 0.5 quantile.

Parameters

* **array** (*array\_like*) – Array containing numbers whose median is sought. If array is not an array, a conversion is attempted.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\). Differential privacy is achieved over the entire output, with epsilon split

evenly between each output value.

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the values of the array, of the form (min, max).

* **axis** ([*None*](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)") *or* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *tuple of ints**,* *optional*) – Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input

array. If axis is negative it counts from the last to the first axis.

If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single

axis or all the axes as before.

* **keepdims** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With

this option, the result will broadcast correctly against the input array.

If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes

of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any

exceptions will be raised.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

Returns

**m** – Returns a new array containing the median values.

Return type

ndarray

See also

[`numpy.median`](https://numpy.org/doc/stable/reference/generated/numpy.median.html#numpy.median "(in NumPy v1.21)")Equivalent non-private method.

[`quantile`](#diffprivlib.tools.quantile "diffprivlib.tools.quantile"), [`percentile`](#diffprivlib.tools.percentile "diffprivlib.tools.percentile")

[`diffprivlib.models`](#module-diffprivlib.models "diffprivlib.models")[¶](#module-diffprivlib.models "Permalink to this headline")

-----------------------------------------------------------------------------------------------------------------------------------

Machine learning models with differential privacy

### Classification models[¶](#classification-models "Permalink to this headline")

#### Gaussian Naive Bayes[¶](#gaussian-naive-bayes "Permalink to this headline")

*class* diffprivlib.models.GaussianNB(*epsilon=1.0*, *bounds=None*, *priors=None*, *var\_smoothing=1e-09*, *accountant=None*)[[source]](_modules/diffprivlib/models/naive_bayes.html#GaussianNB)[¶](#diffprivlib.models.GaussianNB "Permalink to this definition")

Gaussian Naive Bayes (GaussianNB) with differential privacy

Inherits the [`sklearn.naive\_bayes.GaussianNB`](https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html#sklearn.naive_bayes.GaussianNB "(in scikit-learn v0.24)") class from Scikit Learn and adds noise to satisfy differential

privacy to the learned means and variances. Adapted from the work presented in [[VSB13]](index.html#vsb13).

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\) for the model.

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the data, provided as a tuple of the form (min, max). min and max can either be scalars, covering

the min/max of the entire data, or vectors with one entry per feature. If not provided, the bounds are computed

on the data when `.fit()` is first called, resulting in a [`PrivacyLeakWarning`](index.html#diffprivlib.utils.PrivacyLeakWarning "diffprivlib.utils.PrivacyLeakWarning").

* **priors** (*array-like**,* *shape* *(**n\_classes**,**)*) – Prior probabilities of the classes. If specified the priors are not adjusted according to the data.

* **var\_smoothing** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1e-9*) – Portion of the largest variance of all features that is added to variances for calculation stability.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

class\_prior\_[¶](#diffprivlib.models.GaussianNB.class_prior_ "Permalink to this definition")

probability of each class.

Type

array, shape (n\_classes,)

class\_count\_[¶](#diffprivlib.models.GaussianNB.class_count_ "Permalink to this definition")

number of training samples observed in each class.

Type

array, shape (n\_classes,)

theta\_[¶](#diffprivlib.models.GaussianNB.theta_ "Permalink to this definition")

mean of each feature per class

Type

array, shape (n\_classes, n\_features)

sigma\_[¶](#diffprivlib.models.GaussianNB.sigma_ "Permalink to this definition")

variance of each feature per class

Type

array, shape (n\_classes, n\_features)

epsilon\_[¶](#diffprivlib.models.GaussianNB.epsilon_ "Permalink to this definition")

absolute additive value to variances (unrelated to `epsilon` parameter for differential privacy)

Type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

References

[VSB13](#id1)

Vaidya, Jaideep, Basit Shafiq, Anirban Basu, and Yuan Hong. “Differentially private naive bayes

classification.” In 2013 IEEE/WIC/ACM International Joint Conferences on Web Intelligence (WI) and Intelligent

Agent Technologies (IAT), vol. 1, pp. 571-576. IEEE, 2013.

fit(*X*, *y*, *sample\_weight=None*)[[source]](_modules/sklearn/naive_bayes.html#GaussianNB.fit)[¶](#diffprivlib.models.GaussianNB.fit "Permalink to this definition")

Fit Gaussian Naive Bayes according to X, y

Parameters

* **X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – Training vectors, where n\_samples is the number of samples

and n\_features is the number of features.

* **y** (*array-like of shape* *(**n\_samples**,**)*) – Target values.

* **sample\_weight** (*array-like of shape* *(**n\_samples**,**)**,* *default=None*) – Weights applied to individual samples (1. for unweighted).

New in version 0.17: Gaussian Naive Bayes supports fitting with *sample\_weight*.

Returns

**self**

Return type

[object](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

get\_params(*deep=True*)[¶](#diffprivlib.models.GaussianNB.get_params "Permalink to this definition")

Get parameters for this estimator.

Parameters

**deep** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default=True*) – If True, will return the parameters for this estimator and

contained subobjects that are estimators.

Returns

**params** – Parameter names mapped to their values.

Return type

[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")

partial\_fit(*X*, *y*, *classes=None*, *sample\_weight=None*)[[source]](_modules/sklearn/naive_bayes.html#GaussianNB.partial_fit)[¶](#diffprivlib.models.GaussianNB.partial_fit "Permalink to this definition")

Incremental fit on a batch of samples.

This method is expected to be called several times consecutively

on different chunks of a dataset so as to implement out-of-core

or online learning.

This is especially useful when the whole dataset is too big to fit in

memory at once.

This method has some performance and numerical stability overhead,

hence it is better to call partial\_fit on chunks of data that are

as large as possible (as long as fitting in the memory budget) to

hide the overhead.

Parameters

* **X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – Training vectors, where n\_samples is the number of samples and

n\_features is the number of features.

* **y** (*array-like of shape* *(**n\_samples**,**)*) – Target values.

* **classes** (*array-like of shape* *(**n\_classes**,**)**,* *default=None*) – List of all the classes that can possibly appear in the y vector.

Must be provided at the first call to partial\_fit, can be omitted

in subsequent calls.

* **sample\_weight** (*array-like of shape* *(**n\_samples**,**)**,* *default=None*) – Weights applied to individual samples (1. for unweighted).

New in version 0.17.

Returns

**self**

Return type

[object](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

predict(*X*)[¶](#diffprivlib.models.GaussianNB.predict "Permalink to this definition")

Perform classification on an array of test vectors X.

Parameters

**X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – 

Returns

**C** – Predicted target values for X

Return type

ndarray of shape (n\_samples,)

predict\_log\_proba(*X*)[¶](#diffprivlib.models.GaussianNB.predict_log_proba "Permalink to this definition")

Return log-probability estimates for the test vector X.

Parameters

**X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – 

Returns

**C** – Returns the log-probability of the samples for each class in

the model. The columns correspond to the classes in sorted

order, as they appear in the attribute [classes\_](https://scikit-learn.org/stable/glossary.html#term-classes_ "(in scikit-learn v0.24)").

Return type

array-like of shape (n\_samples, n\_classes)

predict\_proba(*X*)[¶](#diffprivlib.models.GaussianNB.predict_proba "Permalink to this definition")

Return probability estimates for the test vector X.

Parameters

**X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – 

Returns

**C** – Returns the probability of the samples for each class in

the model. The columns correspond to the classes in sorted

order, as they appear in the attribute [classes\_](https://scikit-learn.org/stable/glossary.html#term-classes_ "(in scikit-learn v0.24)").

Return type

array-like of shape (n\_samples, n\_classes)

score(*X*, *y*, *sample\_weight=None*)[¶](#diffprivlib.models.GaussianNB.score "Permalink to this definition")

Return the mean accuracy on the given test data and labels.

In multi-label classification, this is the subset accuracy

which is a harsh metric since you require for each sample that

each label set be correctly predicted.

Parameters

* **X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – Test samples.

* **y** (*array-like of shape* *(**n\_samples**,**) or* *(**n\_samples**,* *n\_outputs**)*) – True labels for X.

* **sample\_weight** (*array-like of shape* *(**n\_samples**,**)**,* *default=None*) – Sample weights.

Returns

**score** – Mean accuracy of `self.predict(X)` wrt. y.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

set\_params(*\*\*params*)[¶](#diffprivlib.models.GaussianNB.set_params "Permalink to this definition")

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects

(such as [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline "(in scikit-learn v0.24)")). The latter have

parameters of the form `<component>\_\_<parameter>` so that it’s

possible to update each component of a nested object.

Parameters

**\*\*params** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – Estimator parameters.

Returns

**self** – Estimator instance.

Return type

estimator instance

#### Logistic Regression[¶](#logistic-regression "Permalink to this headline")

*class* diffprivlib.models.LogisticRegression(*epsilon=1.0*, *data\_norm=None*, *tol=0.0001*, *C=1.0*, *fit\_intercept=True*, *max\_iter=100*, *verbose=0*, *warm\_start=False*, *n\_jobs=None*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/models/logistic_regression.html#LogisticRegression)[¶](#diffprivlib.models.LogisticRegression "Permalink to this definition")

Logistic Regression (aka logit, MaxEnt) classifier with differential privacy.

This class implements regularised logistic regression using [Scipy’s L-BFGS-B algorithm](https://docs.scipy.org/doc/scipy/reference/reference/optimize.minimize-lbfgsb.html#optimize-minimize-lbfgsb "(in SciPy v1.7.0)"). \(\epsilon\)-Differential privacy is achieved relative to the maximum norm

of the data, as determined by data\_norm, by the [`Vector`](index.html#diffprivlib.mechanisms.Vector "diffprivlib.mechanisms.Vector") mechanism, which adds a Laplace-distributed

random vector to the objective. Adapted from the work presented in [[CMS11]](index.html#cms11).

This class is a child of [`sklearn.linear\_model.LogisticRegression`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression "(in scikit-learn v0.24)"), with amendments to allow for the

implementation of differential privacy. Some parameters of Scikit Learn’s model have therefore had to be fixed,

including:

> 

> * The only permitted solver is ‘lbfgs’. Specifying the `solver` option will result in a warning.

> * Consequently, the only permitted penalty is ‘l2’. Specifying the `penalty` option will result in a warning.

> * In the multiclass case, only the one-vs-rest (OvR) scheme is permitted. Specifying the `multi\_class` option

> will result in a warning.

> 

> 

> 

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **data\_norm** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *optional*) – The max l2 norm of any row of the data. This defines the spread of data that will be protected by

differential privacy.

If not specified, the max norm is taken from the data when `.fit()` is first called, but will result in a

[`PrivacyLeakWarning`](index.html#diffprivlib.utils.PrivacyLeakWarning "diffprivlib.utils.PrivacyLeakWarning"), as it reveals information about the data. To preserve differential privacy fully,

data\_norm should be selected independently of the data, i.e. with domain knowledge.

* **tol** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1e-4*) – Tolerance for stopping criteria.

* **C** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Inverse of regularization strength; must be a positive float. Like in support vector machines, smaller values

specify stronger regularization.

* **fit\_intercept** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: True*) – Specifies if a constant (a.k.a. bias or intercept) should be added to the decision function.

* **max\_iter** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default: 100*) – Maximum number of iterations taken for the solver to converge. For smaller epsilon (more noise), max\_iter

may need to be increased.

* **verbose** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default: 0*) – Set to any positive number for verbosity.

* **warm\_start** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – When set to `True`, reuse the solution of the previous call to fit as initialization, otherwise, just erase

the previous solution.

* **n\_jobs** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *optional*) – Number of CPU cores used when parallelising over classes. `None` means 1 unless in a context. `-1` means

using all processors.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

classes\_[¶](#diffprivlib.models.LogisticRegression.classes_ "Permalink to this definition")

A list of class labels known to the classifier.

Type

array, shape (n\_classes, )

coef\_[¶](#diffprivlib.models.LogisticRegression.coef_ "Permalink to this definition")

Coefficient of the features in the decision function.

coef\_ is of shape (1, n\_features) when the given problem is binary.

Type

array, shape (1, n\_features) or (n\_classes, n\_features)

intercept\_[¶](#diffprivlib.models.LogisticRegression.intercept_ "Permalink to this definition")

Intercept (a.k.a. bias) added to the decision function.

If fit\_intercept is set to False, the intercept is set to zero. intercept\_ is of shape (1,) when the

given problem is binary.

Type

array, shape (1,) or (n\_classes,)

n\_iter\_[¶](#diffprivlib.models.LogisticRegression.n_iter_ "Permalink to this definition")

Actual number of iterations for all classes. If binary, it returns only 1 element.

Type

array, shape (n\_classes,) or (1, )

Examples

```

>>> from sklearn.datasets import load\_iris

>>> from diffprivlib.models import LogisticRegression

>>> X, y = load\_iris(return\_X\_y=True)

>>> clf = LogisticRegression(data\_norm=12, epsilon=2).fit(X, y)

>>> clf.predict(X[:2, :])

array([0, 0])

>>> clf.predict\_proba(X[:2, :])

array([[7.35362932e-01, 2.16667422e-14, 2.64637068e-01],

 [9.08384378e-01, 3.47767052e-13, 9.16156215e-02]])

>>> clf.score(X, y)

0.5266666666666666

```

See also

[`sklearn.linear\_model.LogisticRegression`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression "(in scikit-learn v0.24)")The implementation of logistic regression in scikit-learn, upon which this implementation is built.

[`Vector`](index.html#diffprivlib.mechanisms.Vector "diffprivlib.mechanisms.Vector")The mechanism used by the model to achieve differential privacy.

References

[CMS11](#id2)

Chaudhuri, Kamalika, Claire Monteleoni, and Anand D. Sarwate. “Differentially private empirical risk

minimization.” Journal of Machine Learning Research 12, no. Mar (2011): 1069-1109.

decision\_function(*X*)[¶](#diffprivlib.models.LogisticRegression.decision_function "Permalink to this definition")

Predict confidence scores for samples.

The confidence score for a sample is proportional to the signed

distance of that sample to the hyperplane.

Parameters

**X** (*array-like* *or* *sparse matrix**,* *shape* *(**n\_samples**,* *n\_features**)*) – Samples.

Returns

Confidence scores per (sample, class) combination. In the binary

case, confidence score for self.classes\_[1] where >0 means this

class would be predicted.

Return type

array, shape=(n\_samples,) if n\_classes == 2 else (n\_samples, n\_classes)

densify()[¶](#diffprivlib.models.LogisticRegression.densify "Permalink to this definition")

Convert coefficient matrix to dense array format.

Converts the `coef\_` member (back) to a numpy.ndarray. This is the

default format of `coef\_` and is required for fitting, so calling

this method is only required on models that have previously been

sparsified; otherwise, it is a no-op.

Returns

Fitted estimator.

Return type

self

fit(*X*, *y*, *sample\_weight=None*)[[source]](_modules/diffprivlib/models/logistic_regression.html#LogisticRegression.fit)[¶](#diffprivlib.models.LogisticRegression.fit "Permalink to this definition")

Fit the model according to the given training data.

Parameters

* **X** (*{array-like**,* *sparse matrix}**,* *shape* *(**n\_samples**,* *n\_features**)*) – Training vector, where n\_samples is the number of samples and n\_features is the number of features.

* **y** (*array-like**,* *shape* *(**n\_samples**,**)*) – Target vector relative to X.

* **sample\_weight** (*ignored*) – Ignored by diffprivlib. Present for consistency with sklearn API.

Returns

**self**

Return type

class

get\_params(*deep=True*)[¶](#diffprivlib.models.LogisticRegression.get_params "Permalink to this definition")

Get parameters for this estimator.

Parameters

**deep** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default=True*) – If True, will return the parameters for this estimator and

contained subobjects that are estimators.

Returns

**params** – Parameter names mapped to their values.

Return type

[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")

predict(*X*)[¶](#diffprivlib.models.LogisticRegression.predict "Permalink to this definition")

Predict class labels for samples in X.

Parameters

**X** (*array-like* *or* *sparse matrix**,* *shape* *(**n\_samples**,* *n\_features**)*) – Samples.

Returns

**C** – Predicted class label per sample.

Return type

array, shape [n\_samples]

predict\_log\_proba(*X*)[[source]](_modules/sklearn/linear_model/_logistic.html#LogisticRegression.predict_log_proba)[¶](#diffprivlib.models.LogisticRegression.predict_log_proba "Permalink to this definition")

Predict logarithm of probability estimates.

The returned estimates for all classes are ordered by the

label of classes.

Parameters

**X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – Vector to be scored, where n\_samples is the number of samples and

n\_features is the number of features.

Returns

**T** – Returns the log-probability of the sample for each class in the

model, where classes are ordered as they are in `self.classes\_`.

Return type

array-like of shape (n\_samples, n\_classes)

predict\_proba(*X*)[[source]](_modules/sklearn/linear_model/_logistic.html#LogisticRegression.predict_proba)[¶](#diffprivlib.models.LogisticRegression.predict_proba "Permalink to this definition")

Probability estimates.

The returned estimates for all classes are ordered by the

label of classes.

For a multi\_class problem, if multi\_class is set to be “multinomial”

the softmax function is used to find the predicted probability of

each class.

Else use a one-vs-rest approach, i.e calculate the probability

of each class assuming it to be positive using the logistic function.

and normalize these values across all the classes.

Parameters

**X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – Vector to be scored, where n\_samples is the number of samples and

n\_features is the number of features.

Returns

**T** – Returns the probability of the sample for each class in the model,

where classes are ordered as they are in `self.classes\_`.

Return type

array-like of shape (n\_samples, n\_classes)

score(*X*, *y*, *sample\_weight=None*)[¶](#diffprivlib.models.LogisticRegression.score "Permalink to this definition")

Return the mean accuracy on the given test data and labels.

In multi-label classification, this is the subset accuracy

which is a harsh metric since you require for each sample that

each label set be correctly predicted.

Parameters

* **X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – Test samples.

* **y** (*array-like of shape* *(**n\_samples**,**) or* *(**n\_samples**,* *n\_outputs**)*) – True labels for X.

* **sample\_weight** (*array-like of shape* *(**n\_samples**,**)**,* *default=None*) – Sample weights.

Returns

**score** – Mean accuracy of `self.predict(X)` wrt. y.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

set\_params(*\*\*params*)[¶](#diffprivlib.models.LogisticRegression.set_params "Permalink to this definition")

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects

(such as [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline "(in scikit-learn v0.24)")). The latter have

parameters of the form `<component>\_\_<parameter>` so that it’s

possible to update each component of a nested object.

Parameters

**\*\*params** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – Estimator parameters.

Returns

**self** – Estimator instance.

Return type

estimator instance

sparsify()[¶](#diffprivlib.models.LogisticRegression.sparsify "Permalink to this definition")

Convert coefficient matrix to sparse format.

Converts the `coef\_` member to a scipy.sparse matrix, which for

L1-regularized models can be much more memory- and storage-efficient

than the usual numpy.ndarray representation.

The `intercept\_` member is not converted.

Returns

Fitted estimator.

Return type

self

Notes

For non-sparse models, i.e. when there are not many zeros in `coef\_`,

this may actually *increase* memory usage, so use this method with

care. A rule of thumb is that the number of zero elements, which can

be computed with `(coef\_ == 0).sum()`, must be more than 50% for this

to provide significant benefits.

After calling this method, further fitting with the partial\_fit

method (if any) will not work until you call densify.

### Regression models[¶](#regression-models "Permalink to this headline")

#### Linear Regression[¶](#linear-regression "Permalink to this headline")

*class* diffprivlib.models.LinearRegression(*epsilon=1.0*, *bounds\_X=None*, *bounds\_y=None*, *fit\_intercept=True*, *copy\_X=True*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/models/linear_regression.html#LinearRegression)[¶](#diffprivlib.models.LinearRegression "Permalink to this definition")

Ordinary least squares Linear Regression with differential privacy.

LinearRegression fits a linear model with coefficients w = (w1, …, wp) to minimize the residual sum of squares

between the observed targets in the dataset, and the targets predicted by the linear approximation. Differential

privacy is guaranteed with respect to the training sample.

Differential privacy is achieved by adding noise to the coefficients of the objective function, taking inspiration

from [[ZZX12]](index.html#zzx12).

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **bounds\_X** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")) – Bounds of the data, provided as a tuple of the form (min, max). min and max can either be scalars, covering

the min/max of the entire data, or vectors with one entry per feature. If not provided, the bounds are computed

on the data when `.fit()` is first called, resulting in a [`PrivacyLeakWarning`](index.html#diffprivlib.utils.PrivacyLeakWarning "diffprivlib.utils.PrivacyLeakWarning").

* **bounds\_y** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")) – Same as bounds\_X, but for the training label set y.

* **fit\_intercept** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: True*) – Whether to calculate the intercept for this model. If set to False, no intercept will be used in calculations

(i.e. data is expected to be centered).

* **copy\_X** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: True*) – If True, X will be copied; else, it may be overwritten.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

coef\_[¶](#diffprivlib.models.LinearRegression.coef_ "Permalink to this definition")

Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D),

this is a 2D array of shape (n\_targets, n\_features), while if only one target is passed, this is a 1D array of

length n\_features.

Type

array of shape (n\_features, ) or (n\_targets, n\_features)

intercept\_[¶](#diffprivlib.models.LinearRegression.intercept_ "Permalink to this definition")

Independent term in the linear model. Set to 0.0 if fit\_intercept = False.

Type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") or array of shape of (n\_targets,)

References

[ZZX12](#id3)

Zhang, Jun, Zhenjie Zhang, Xiaokui Xiao, Yin Yang, and Marianne Winslett. “Functional mechanism:

regression analysis under differential privacy.” arXiv preprint arXiv:1208.0219 (2012).

fit(*X*, *y*, *sample\_weight=None*)[[source]](_modules/diffprivlib/models/linear_regression.html#LinearRegression.fit)[¶](#diffprivlib.models.LinearRegression.fit "Permalink to this definition")

Fit linear model.

Parameters

* **X** (*array-like* *or* *sparse matrix**,* *shape* *(**n\_samples**,* *n\_features**)*) – Training data

* **y** (*array\_like**,* *shape* *(**n\_samples**,* *n\_targets**)*) – Target values. Will be cast to X’s dtype if necessary

* **sample\_weight** (*ignored*) – Ignored by diffprivlib. Present for consistency with sklearn API.

Returns

**self**

Return type

returns an instance of self.

get\_params(*deep=True*)[¶](#diffprivlib.models.LinearRegression.get_params "Permalink to this definition")

Get parameters for this estimator.

Parameters

**deep** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default=True*) – If True, will return the parameters for this estimator and

contained subobjects that are estimators.

Returns

**params** – Parameter names mapped to their values.

Return type

[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")

predict(*X*)[¶](#diffprivlib.models.LinearRegression.predict "Permalink to this definition")

Predict using the linear model.

Parameters

**X** (*array-like* *or* *sparse matrix**,* *shape* *(**n\_samples**,* *n\_features**)*) – Samples.

Returns

**C** – Returns predicted values.

Return type

array, shape (n\_samples,)

score(*X*, *y*, *sample\_weight=None*)[¶](#diffprivlib.models.LinearRegression.score "Permalink to this definition")

Return the coefficient of determination \(R^2\) of the

prediction.

The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\),

where \(u\) is the residual sum of squares `((y\_true - y\_pred)

\*\* 2).sum()` and \(v\) is the total sum of squares `((y\_true -

y\_true.mean()) \*\* 2).sum()`. The best possible score is 1.0 and it

can be negative (because the model can be arbitrarily worse). A

constant model that always predicts the expected value of y,

disregarding the input features, would get a \(R^2\) score of

0.0.

Parameters

* **X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – Test samples. For some estimators this may be a precomputed

kernel matrix or a list of generic objects instead with shape

`(n\_samples, n\_samples\_fitted)`, where `n\_samples\_fitted`

is the number of samples used in the fitting for the estimator.

* **y** (*array-like of shape* *(**n\_samples**,**) or* *(**n\_samples**,* *n\_outputs**)*) – True values for X.

* **sample\_weight** (*array-like of shape* *(**n\_samples**,**)**,* *default=None*) – Sample weights.

Returns

**score** – \(R^2\) of `self.predict(X)` wrt. y.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

Notes

The \(R^2\) score used when calling `score` on a regressor uses

`multioutput='uniform\_average'` from version 0.23 to keep consistent

with default value of [`r2\_score()`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.html#sklearn.metrics.r2_score "(in scikit-learn v0.24)").

This influences the `score` method of all the multioutput

regressors (except for

[`MultiOutputRegressor`](https://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputRegressor.html#sklearn.multioutput.MultiOutputRegressor "(in scikit-learn v0.24)")).

set\_params(*\*\*params*)[¶](#diffprivlib.models.LinearRegression.set_params "Permalink to this definition")

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects

(such as [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline "(in scikit-learn v0.24)")). The latter have

parameters of the form `<component>\_\_<parameter>` so that it’s

possible to update each component of a nested object.

Parameters

**\*\*params** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – Estimator parameters.

Returns

**self** – Estimator instance.

Return type

estimator instance

### Clustering models[¶](#clustering-models "Permalink to this headline")

#### K-Means[¶](#k-means "Permalink to this headline")

*class* diffprivlib.models.KMeans(*epsilon=1.0*, *bounds=None*, *n\_clusters=8*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/models/k_means.html#KMeans)[¶](#diffprivlib.models.KMeans "Permalink to this definition")

K-Means clustering with differential privacy.

Implements the DPLloyd approach presented in [[SCL16]](index.html#scl16), leveraging the [`sklearn.cluster.KMeans`](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans "(in scikit-learn v0.24)") class for full

integration with Scikit Learn.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\).

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the data, provided as a tuple of the form (min, max). min and max can either be scalars, covering

the min/max of the entire data, or vectors with one entry per feature. If not provided, the bounds are computed

on the data when `.fit()` is first called, resulting in a [`PrivacyLeakWarning`](index.html#diffprivlib.utils.PrivacyLeakWarning "diffprivlib.utils.PrivacyLeakWarning").

* **n\_clusters** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default: 8*) – The number of clusters to form as well as the number of centroids to generate.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

cluster\_centers\_[¶](#diffprivlib.models.KMeans.cluster_centers_ "Permalink to this definition")

Coordinates of cluster centers. If the algorithm stops before fully converging, these will not be consistent

with `labels\_`.

Type

array, [n\_clusters, n\_features]

labels\_[¶](#diffprivlib.models.KMeans.labels_ "Permalink to this definition")

Labels of each point

inertia\_[¶](#diffprivlib.models.KMeans.inertia_ "Permalink to this definition")

Sum of squared distances of samples to their closest cluster center.

Type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

n\_iter\_[¶](#diffprivlib.models.KMeans.n_iter_ "Permalink to this definition")

Number of iterations run.

Type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

References

[SCL16](#id4)

Su, Dong, Jianneng Cao, Ninghui Li, Elisa Bertino, and Hongxia Jin. “Differentially private k-means

clustering.” In Proceedings of the sixth ACM conference on data and application security and privacy, pp. 26-37.

ACM, 2016.

fit(*X*, *y=None*, *sample\_weight=None*)[[source]](_modules/diffprivlib/models/k_means.html#KMeans.fit)[¶](#diffprivlib.models.KMeans.fit "Permalink to this definition")

Computes k-means clustering with differential privacy.

Parameters

* **X** (*array-like**,* *shape=**(**n\_samples**,* *n\_features**)*) – Training instances to cluster.

* **y** (*Ignored*) – not used, present here for API consistency by convention.

* **sample\_weight** (*ignored*) – Ignored by diffprivlib. Present for consistency with sklearn API.

Returns

**self**

Return type

class

fit\_predict(*X*, *y=None*, *sample\_weight=None*)[[source]](_modules/sklearn/cluster/_kmeans.html#KMeans.fit_predict)[¶](#diffprivlib.models.KMeans.fit_predict "Permalink to this definition")

Compute cluster centers and predict cluster index for each sample.

Convenience method; equivalent to calling fit(X) followed by

predict(X).

Parameters

* **X** (*{array-like**,* *sparse matrix} of shape* *(**n\_samples**,* *n\_features**)*) – New data to transform.

* **y** (*Ignored*) – Not used, present here for API consistency by convention.

* **sample\_weight** (*array-like of shape* *(**n\_samples**,**)**,* *default=None*) – The weights for each observation in X. If None, all observations

are assigned equal weight.

Returns

**labels** – Index of the cluster each sample belongs to.

Return type

ndarray of shape (n\_samples,)

fit\_transform(*X*, *y=None*, *sample\_weight=None*)[[source]](_modules/sklearn/cluster/_kmeans.html#KMeans.fit_transform)[¶](#diffprivlib.models.KMeans.fit_transform "Permalink to this definition")

Compute clustering and transform X to cluster-distance space.

Equivalent to fit(X).transform(X), but more efficiently implemented.

Parameters

* **X** (*{array-like**,* *sparse matrix} of shape* *(**n\_samples**,* *n\_features**)*) – New data to transform.

* **y** (*Ignored*) – Not used, present here for API consistency by convention.

* **sample\_weight** (*array-like of shape* *(**n\_samples**,**)**,* *default=None*) – The weights for each observation in X. If None, all observations

are assigned equal weight.

Returns

**X\_new** – X transformed in the new space.

Return type

ndarray of shape (n\_samples, n\_clusters)

get\_params(*deep=True*)[¶](#diffprivlib.models.KMeans.get_params "Permalink to this definition")

Get parameters for this estimator.

Parameters

**deep** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default=True*) – If True, will return the parameters for this estimator and

contained subobjects that are estimators.

Returns

**params** – Parameter names mapped to their values.

Return type

[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")

predict(*X*, *sample\_weight=None*)[[source]](_modules/sklearn/cluster/_kmeans.html#KMeans.predict)[¶](#diffprivlib.models.KMeans.predict "Permalink to this definition")

Predict the closest cluster each sample in X belongs to.

In the vector quantization literature, cluster\_centers\_ is called

the code book and each value returned by predict is the index of

the closest code in the code book.

Parameters

* **X** (*{array-like**,* *sparse matrix} of shape* *(**n\_samples**,* *n\_features**)*) – New data to predict.

* **sample\_weight** (*array-like of shape* *(**n\_samples**,**)**,* *default=None*) – The weights for each observation in X. If None, all observations

are assigned equal weight.

Returns

**labels** – Index of the cluster each sample belongs to.

Return type

ndarray of shape (n\_samples,)

score(*X*, *y=None*, *sample\_weight=None*)[[source]](_modules/sklearn/cluster/_kmeans.html#KMeans.score)[¶](#diffprivlib.models.KMeans.score "Permalink to this definition")

Opposite of the value of X on the K-means objective.

Parameters

* **X** (*{array-like**,* *sparse matrix} of shape* *(**n\_samples**,* *n\_features**)*) – New data.

* **y** (*Ignored*) – Not used, present here for API consistency by convention.

* **sample\_weight** (*array-like of shape* *(**n\_samples**,**)**,* *default=None*) – The weights for each observation in X. If None, all observations

are assigned equal weight.

Returns

**score** – Opposite of the value of X on the K-means objective.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

set\_params(*\*\*params*)[¶](#diffprivlib.models.KMeans.set_params "Permalink to this definition")

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects

(such as [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline "(in scikit-learn v0.24)")). The latter have

parameters of the form `<component>\_\_<parameter>` so that it’s

possible to update each component of a nested object.

Parameters

**\*\*params** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – Estimator parameters.

Returns

**self** – Estimator instance.

Return type

estimator instance

transform(*X*)[[source]](_modules/sklearn/cluster/_kmeans.html#KMeans.transform)[¶](#diffprivlib.models.KMeans.transform "Permalink to this definition")

Transform X to a cluster-distance space.

In the new space, each dimension is the distance to the cluster

centers. Note that even if X is sparse, the array returned by

transform will typically be dense.

Parameters

**X** (*{array-like**,* *sparse matrix} of shape* *(**n\_samples**,* *n\_features**)*) – New data to transform.

Returns

**X\_new** – X transformed in the new space.

Return type

ndarray of shape (n\_samples, n\_clusters)

### Dimensionality reduction models[¶](#dimensionality-reduction-models "Permalink to this headline")

#### PCA[¶](#pca "Permalink to this headline")

*class* diffprivlib.models.PCA(*n\_components=None*, *centered=False*, *epsilon=1.0*, *data\_norm=None*, *bounds=None*, *copy=True*, *whiten=False*, *random\_state=None*, *accountant=None*, *\*\*unused\_args*)[[source]](_modules/diffprivlib/models/pca.html#PCA)[¶](#diffprivlib.models.PCA "Permalink to this definition")

Principal component analysis (PCA) with differential privacy.

This class is a child of [`sklearn.decomposition.PCA`](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA "(in scikit-learn v0.24)"), with amendments to allow for the implementation of

differential privacy as given in [[IS16b]](index.html#is16b). Some parameters of Scikit Learn’s model have therefore had to be

fixed, including:

> 

> * The only permitted svd\_solver is ‘full’. Specifying the `svd\_solver` option will result in a warning;

> * The parameters `tol` and `iterated\_power` are not applicable (as a consequence of fixing `svd\_solver =

> 'full'`).

> 

> 

> 

Parameters

* **n\_components** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* [*None*](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)") *or* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – Number of components to keep.

If n\_components is not set all components are kept:

```

n\_components == min(n\_samples, n\_features)

```

If `n\_components == 'mle'`, Minka’s MLE is used to guess the dimension.

If `0 < n\_components < 1`, select the number of components such that the amount of variance that needs to be

explained is greater than the percentage specified by n\_components.

Hence, the None case results in:

```

n\_components == min(n\_samples, n\_features) - 1

```

* **centered** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – If False, the data will be centered before calculating the principal components. This will be calculated with

differential privacy, consuming privacy budget from epsilon.

If True, the data is assumed to have been centered previously (e.g. using [`StandardScaler`](#diffprivlib.models.StandardScaler "diffprivlib.models.StandardScaler")), and

therefore will not require the consumption of privacy budget to calculate the mean.

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – Privacy parameter \(\epsilon\). If `centered=False`, half of epsilon is used to calculate the

differentially private mean to center the data prior to the calculation of principal components.

* **data\_norm** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *optional*) – The max l2 norm of any row of the data. This defines the spread of data that will be protected by

differential privacy.

If not specified, the max norm is taken from the data when `.fit()` is first called, but will result in a

[`PrivacyLeakWarning`](index.html#diffprivlib.utils.PrivacyLeakWarning "diffprivlib.utils.PrivacyLeakWarning"), as it reveals information about the data. To preserve differential privacy fully,

data\_norm should be selected independently of the data, i.e. with domain knowledge.

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the data, provided as a tuple of the form (min, max). min and max can either be scalars, covering

the min/max of the entire data, or vectors with one entry per feature. If not provided, the bounds are computed

on the data when `.fit()` is first called, resulting in a [`PrivacyLeakWarning`](index.html#diffprivlib.utils.PrivacyLeakWarning "diffprivlib.utils.PrivacyLeakWarning").

* **copy** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: True*) – If False, data passed to fit are overwritten and running fit(X).transform(X) will not yield the expected

results, use fit\_transform(X) instead.

* **whiten** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – When True (False by default) the components\_ vectors are multiplied by the square root of n\_samples and

then divided by the singular values to ensure uncorrelated outputs with unit component-wise variances.

Whitening will remove some information from the transformed signal (the relative variance scales of the

components) but can sometime improve the predictive accuracy of the downstream estimators by making their

data respect some hard-wired assumptions.

* **random\_state** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") *or* *RandomState instance**,* *optional*) – If int, random\_state is the seed used by the random number generator; If RandomState instance, random\_state

is the random number generator.

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

components\_[¶](#diffprivlib.models.PCA.components_ "Permalink to this definition")

Principal axes in feature space, representing the directions of maximum variance in the data. The components

are sorted by `explained\_variance\_`.

Type

array, shape (n\_components, n\_features)

explained\_variance\_[¶](#diffprivlib.models.PCA.explained_variance_ "Permalink to this definition")

The amount of variance explained by each of the selected components.

Equal to n\_components largest eigenvalues of the covariance matrix of X.

Type

array, shape (n\_components,)

explained\_variance\_ratio\_[¶](#diffprivlib.models.PCA.explained_variance_ratio_ "Permalink to this definition")

Percentage of variance explained by each of the selected components.

If `n\_components` is not set then all components are stored and the sum of the ratios is equal to 1.0.

Type

array, shape (n\_components,)

singular\_values\_[¶](#diffprivlib.models.PCA.singular_values_ "Permalink to this definition")

The singular values corresponding to each of the selected components. The singular values are equal to the

2-norms of the `n\_components` variables in the lower-dimensional space.

Type

array, shape (n\_components,)

mean\_[¶](#diffprivlib.models.PCA.mean_ "Permalink to this definition")

Per-feature empirical mean, estimated from the training set.

Equal to X.mean(axis=0).

Type

array, shape (n\_features,)

n\_components\_[¶](#diffprivlib.models.PCA.n_components_ "Permalink to this definition")

The estimated number of components. When n\_components is set to ‘mle’ or a number between 0 and 1 (with

svd\_solver == ‘full’) this number is estimated from input data. Otherwise it equals the parameter

n\_components, or the lesser value of n\_features and n\_samples if n\_components is None.

Type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

n\_features\_[¶](#diffprivlib.models.PCA.n_features_ "Permalink to this definition")

Number of features in the training data.

Type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

n\_samples\_[¶](#diffprivlib.models.PCA.n_samples_ "Permalink to this definition")

Number of samples in the training data.

Type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")

noise\_variance\_[¶](#diffprivlib.models.PCA.noise_variance_ "Permalink to this definition")

The estimated noise covariance following the Probabilistic PCA model from Tipping and Bishop 1999. See

“Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or

<http://www.miketipping.com/papers/met-mppca.pdf>. It is required to compute the estimated data covariance and

score samples.

Equal to the average of (min(n\_features, n\_samples) - n\_components) smallest eigenvalues of the covariance

matrix of X.

Type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

See also

[`sklearn.decomposition.PCA`](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA "(in scikit-learn v0.24)")Scikit-learn implementation Principal Component Analysis.

References

[IS16b](#id5)

Imtiaz, Hafiz, and Anand D. Sarwate. “Symmetric matrix perturbation for differentially-private principal

component analysis.” In 2016 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP),

pp. 2339-2343. IEEE, 2016.

fit(*X*, *y=None*)[[source]](_modules/sklearn/decomposition/_pca.html#PCA.fit)[¶](#diffprivlib.models.PCA.fit "Permalink to this definition")

Fit the model with X.

Parameters

* **X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – Training data, where n\_samples is the number of samples

and n\_features is the number of features.

* **y** (*Ignored*) –

Returns

**self** – Returns the instance itself.

Return type

[object](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

fit\_transform(*X*, *y=None*)[[source]](_modules/diffprivlib/models/pca.html#PCA.fit_transform)[¶](#diffprivlib.models.PCA.fit_transform "Permalink to this definition")

Fit the model with X and apply the dimensionality reduction on X.

Parameters

* **X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – Training data, where n\_samples is the number of samples

and n\_features is the number of features.

* **y** (*Ignored*) –

Returns

**X\_new** – Transformed values.

Return type

ndarray of shape (n\_samples, n\_components)

Notes

This method returns a Fortran-ordered array. To convert it to a

C-ordered array, use ‘np.ascontiguousarray’.

get\_covariance()[¶](#diffprivlib.models.PCA.get_covariance "Permalink to this definition")

Compute data covariance with the generative model.

`cov = components\_.T \* S\*\*2 \* components\_ + sigma2 \* eye(n\_features)`

where S\*\*2 contains the explained variances, and sigma2 contains the

noise variances.

Returns

**cov** – Estimated covariance of data.

Return type

array, shape=(n\_features, n\_features)

get\_params(*deep=True*)[¶](#diffprivlib.models.PCA.get_params "Permalink to this definition")

Get parameters for this estimator.

Parameters

**deep** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default=True*) – If True, will return the parameters for this estimator and

contained subobjects that are estimators.

Returns

**params** – Parameter names mapped to their values.

Return type

[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")

get\_precision()[¶](#diffprivlib.models.PCA.get_precision "Permalink to this definition")

Compute data precision matrix with the generative model.

Equals the inverse of the covariance but computed with

the matrix inversion lemma for efficiency.

Returns

**precision** – Estimated precision of data.

Return type

array, shape=(n\_features, n\_features)

inverse\_transform(*X*)[¶](#diffprivlib.models.PCA.inverse_transform "Permalink to this definition")

Transform data back to its original space.

In other words, return an input X\_original whose transform would be X.

Parameters

**X** (*array-like**,* *shape* *(**n\_samples**,* *n\_components**)*) – New data, where n\_samples is the number of samples

and n\_components is the number of components.

Returns

Return type

X\_original array-like, shape (n\_samples, n\_features)

Notes

If whitening is enabled, inverse\_transform will compute the

exact inverse operation, which includes reversing whitening.

score(*X*, *y=None*)[[source]](_modules/sklearn/decomposition/_pca.html#PCA.score)[¶](#diffprivlib.models.PCA.score "Permalink to this definition")

Return the average log-likelihood of all samples.

See. “Pattern Recognition and Machine Learning”

by C. Bishop, 12.2.1 p. 574

or <http://www.miketipping.com/papers/met-mppca.pdf>

Parameters

* **X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – The data.

* **y** (*Ignored*) –

Returns

**ll** – Average log-likelihood of the samples under the current model.

Return type

[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")

score\_samples(*X*)[[source]](_modules/sklearn/decomposition/_pca.html#PCA.score_samples)[¶](#diffprivlib.models.PCA.score_samples "Permalink to this definition")

Return the log-likelihood of each sample.

See. “Pattern Recognition and Machine Learning”

by C. Bishop, 12.2.1 p. 574

or <http://www.miketipping.com/papers/met-mppca.pdf>

Parameters

**X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – The data.

Returns

**ll** – Log-likelihood of each sample under the current model.

Return type

ndarray of shape (n\_samples,)

set\_params(*\*\*params*)[¶](#diffprivlib.models.PCA.set_params "Permalink to this definition")

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects

(such as [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline "(in scikit-learn v0.24)")). The latter have

parameters of the form `<component>\_\_<parameter>` so that it’s

possible to update each component of a nested object.

Parameters

**\*\*params** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – Estimator parameters.

Returns

**self** – Estimator instance.

Return type

estimator instance

transform(*X*)[¶](#diffprivlib.models.PCA.transform "Permalink to this definition")

Apply dimensionality reduction to X.

X is projected on the first principal components previously extracted

from a training set.

Parameters

**X** (*array-like**,* *shape* *(**n\_samples**,* *n\_features**)*) – New data, where n\_samples is the number of samples

and n\_features is the number of features.

Returns

**X\_new**

Return type

array-like, shape (n\_samples, n\_components)

### Preprocessing[¶](#preprocessing "Permalink to this headline")

#### Standard Scaler[¶](#standard-scaler "Permalink to this headline")

*class* diffprivlib.models.StandardScaler(*epsilon=1.0*, *bounds=None*, *copy=True*, *with\_mean=True*, *with\_std=True*, *accountant=None*)[[source]](_modules/diffprivlib/models/standard_scaler.html#StandardScaler)[¶](#diffprivlib.models.StandardScaler "Permalink to this definition")

Standardize features by removing the mean and scaling to unit variance, calculated with differential privacy

guarantees. Differential privacy is guaranteed on the learned scaler with respect to the training sample; the

transformed output will certainly not satisfy differential privacy.

The standard score of a sample x is calculated as:

> 

> z = (x - u) / s

> 

> 

> 

where u is the (differentially private) mean of the training samples or zero if with\_mean=False, and s is the

(differentially private) standard deviation of the training samples or one if with\_std=False.

Centering and scaling happen independently on each feature by computing the relevant statistics on the samples in

the training set. Mean and standard deviation are then stored to be used on later data using the transform

method.

For further information, users are referred to [`sklearn.preprocessing.StandardScaler`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler "(in scikit-learn v0.24)").

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 1.0*) – The privacy budget to be allocated to learning the mean and variance of the training sample. If

with\_std=True, the privacy budget is split evenly between mean and variance (the mean must be calculated even

when with\_mean=False, as it is used in the calculation of the variance.

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")*,* *optional*) – Bounds of the data, provided as a tuple of the form (min, max). min and max can either be scalars, covering

the min/max of the entire data, or vectors with one entry per feature. If not provided, the bounds are computed

on the data when `.fit()` is first called, resulting in a [`PrivacyLeakWarning`](index.html#diffprivlib.utils.PrivacyLeakWarning "diffprivlib.utils.PrivacyLeakWarning").

* **copy** (*boolean**,* *default: True*) – If False, try to avoid a copy and do inplace scaling instead. This is not guaranteed to always work inplace;

e.g. if the data is not a NumPy array, a copy may still be returned.

* **with\_mean** (*boolean**,* *True by default*) – If True, center the data before scaling.

* **with\_std** (*boolean**,* *True by default*) – If True, scale the data to unit variance (or equivalently, unit standard deviation).

* **accountant** ([*BudgetAccountant*](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant")*,* *optional*) – Accountant to keep track of privacy budget.

scale\_[¶](#diffprivlib.models.StandardScaler.scale_ "Permalink to this definition")

Per feature relative scaling of the data. This is calculated using np.sqrt(var\_). Equal to `None` when

`with\_std=False`.

Type

ndarray or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)"), shape (n\_features,)

mean\_[¶](#diffprivlib.models.StandardScaler.mean_ "Permalink to this definition")

The mean value for each feature in the training set. Equal to `None` when `with\_mean=False`.

Type

ndarray or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)"), shape (n\_features,)

var\_[¶](#diffprivlib.models.StandardScaler.var_ "Permalink to this definition")

The variance for each feature in the training set. Used to compute scale\_. Equal to `None` when

`with\_std=False`.

Type

ndarray or [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)"), shape (n\_features,)

n\_samples\_seen\_[¶](#diffprivlib.models.StandardScaler.n_samples_seen_ "Permalink to this definition")

The number of samples processed by the estimator for each feature. If there are not missing samples, the

`n\_samples\_seen` will be an integer, otherwise it will be an array.

Will be reset on new calls to fit, but increments across `partial\_fit` calls.

Type

[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") or array, shape (n\_features,)

See also

[`sklearn.preprocessing.StandardScaler`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler "(in scikit-learn v0.24)")Vanilla scikit-learn version, without differential privacy.

[`PCA`](#diffprivlib.models.PCA "diffprivlib.models.PCA")Further removes the linear correlation across features with ‘whiten=True’.

Notes

NaNs are treated as missing values: disregarded in fit, and maintained in transform.

fit(*X*, *y=None*, *sample\_weight=None*)[[source]](_modules/sklearn/preprocessing/_data.html#StandardScaler.fit)[¶](#diffprivlib.models.StandardScaler.fit "Permalink to this definition")

Compute the mean and std to be used for later scaling.

Parameters

* **X** (*{array-like**,* *sparse matrix} of shape* *(**n\_samples**,* *n\_features**)*) – The data used to compute the mean and standard deviation

used for later scaling along the features axis.

* **y** ([*None*](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")) – Ignored.

* **sample\_weight** (*array-like of shape* *(**n\_samples**,**)**,* *default=None*) – Individual weights for each sample.

New in version 0.24: parameter *sample\_weight* support to StandardScaler.

Returns

**self** – Fitted scaler.

Return type

[object](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

fit\_transform(*X*, *y=None*, *\*\*fit\_params*)[¶](#diffprivlib.models.StandardScaler.fit_transform "Permalink to this definition")

Fit to data, then transform it.

Fits transformer to X and y with optional parameters fit\_params

and returns a transformed version of X.

Parameters

* **X** (*array-like of shape* *(**n\_samples**,* *n\_features**)*) – Input samples.

* **y** (*array-like of shape* *(**n\_samples**,**) or* *(**n\_samples**,* *n\_outputs**)**,* *default=None*) – Target values (None for unsupervised transformations).

* **\*\*fit\_params** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – Additional fit parameters.

Returns

**X\_new** – Transformed array.

Return type

ndarray array of shape (n\_samples, n\_features\_new)

get\_params(*deep=True*)[¶](#diffprivlib.models.StandardScaler.get_params "Permalink to this definition")

Get parameters for this estimator.

Parameters

**deep** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default=True*) – If True, will return the parameters for this estimator and

contained subobjects that are estimators.

Returns

**params** – Parameter names mapped to their values.

Return type

[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")

inverse\_transform(*X*, *copy=None*)[[source]](_modules/sklearn/preprocessing/_data.html#StandardScaler.inverse_transform)[¶](#diffprivlib.models.StandardScaler.inverse_transform "Permalink to this definition")

Scale back the data to the original representation

Parameters

* **X** (*{array-like**,* *sparse matrix} of shape* *(**n\_samples**,* *n\_features**)*) – The data used to scale along the features axis.

* **copy** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default=None*) – Copy the input X or not.

Returns

**X\_tr** – Transformed array.

Return type

{ndarray, sparse matrix} of shape (n\_samples, n\_features)

partial\_fit(*X*, *y=None*, *sample\_weight=None*)[[source]](_modules/diffprivlib/models/standard_scaler.html#StandardScaler.partial_fit)[¶](#diffprivlib.models.StandardScaler.partial_fit "Permalink to this definition")

Online computation of mean and std with differential privacy on X for later scaling. All of X is processed

as a single batch. This is intended for cases when fit is not feasible due to very large number of

n\_samples or because X is read from a continuous stream.

The algorithm for incremental mean and std is given in Equation 1.5a,b in Chan, Tony F., Gene H. Golub, and

Randall J. LeVeque. “Algorithms for computing the sample variance: Analysis and recommendations.” The American

Statistician 37.3 (1983): 242-247:

Parameters

* **X** (*{array-like}**,* *shape* *[**n\_samples**,* *n\_features**]*) – The data used to compute the mean and standard deviation used for later scaling along the features axis.

* **y** – Ignored

* **sample\_weight** – Ignored by diffprivlib. Present for consistency with sklearn API.

set\_params(*\*\*params*)[¶](#diffprivlib.models.StandardScaler.set_params "Permalink to this definition")

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects

(such as [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline "(in scikit-learn v0.24)")). The latter have

parameters of the form `<component>\_\_<parameter>` so that it’s

possible to update each component of a nested object.

Parameters

**\*\*params** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – Estimator parameters.

Returns

**self** – Estimator instance.

Return type

estimator instance

transform(*X*, *copy=None*)[[source]](_modules/sklearn/preprocessing/_data.html#StandardScaler.transform)[¶](#diffprivlib.models.StandardScaler.transform "Permalink to this definition")

Perform standardization by centering and scaling

Parameters

* **X** (*{array-like**,* *sparse matrix of shape* *(**n\_samples**,* *n\_features**)*) – The data used to scale along the features axis.

* **copy** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default=None*) – Copy the input X or not.

Returns

**X\_tr** – Transformed array.

Return type

{ndarray, sparse matrix} of shape (n\_samples, n\_features)

Utilities and general functions[¶](#module-diffprivlib.utils "Permalink to this headline")

------------------------------------------------------------------------------------------

Basic functions and other utilities for the differential privacy library

### Exceptions and warnings[¶](#exceptions-and-warnings "Permalink to this headline")

*exception* diffprivlib.utils.PrivacyLeakWarning[[source]](_modules/diffprivlib/utils.html#PrivacyLeakWarning)[¶](#diffprivlib.utils.PrivacyLeakWarning "Permalink to this definition")

Custom warning to capture privacy leaks resulting from incorrect parameter setting.

For example, this warning may occur when the user:

> 

> * fails to specify the bounds or range of data to a model where required (e.g., bounds=None to

> [`GaussianNB`](index.html#diffprivlib.models.GaussianNB "diffprivlib.models.GaussianNB")).

> * inputs data to a model that falls outside the bounds or range originally specified.

> 

> 

> 

*exception* diffprivlib.utils.DiffprivlibCompatibilityWarning[[source]](_modules/diffprivlib/utils.html#DiffprivlibCompatibilityWarning)[¶](#diffprivlib.utils.DiffprivlibCompatibilityWarning "Permalink to this definition")

Custom warning to capture inherited class arguments that are not compatible with diffprivlib.

The purpose of the warning is to alert the user of the incompatibility, but to continue execution having fixed the

incompatibility at runtime.

For example, this warning may occur when the user:

> 

> * passes a parameter value that is not compatible with diffprivlib (e.g., solver=’liblinear’ to

> [`LogisticRegression`](index.html#diffprivlib.models.LogisticRegression "diffprivlib.models.LogisticRegression"))

> * specifies a non-default value for a parameter that is ignored by diffprivlib (e.g., intercept\_scaling=0.5

> to [`LogisticRegression`](index.html#diffprivlib.models.LogisticRegression "diffprivlib.models.LogisticRegression").

> 

> 

> 

*exception* diffprivlib.utils.BudgetError[[source]](_modules/diffprivlib/utils.html#BudgetError)[¶](#diffprivlib.utils.BudgetError "Permalink to this definition")

Custom exception to capture the privacy budget being exceeded, typically controlled by a

[`BudgetAccountant`](index.html#diffprivlib.accountant.BudgetAccountant "diffprivlib.accountant.BudgetAccountant").

For example, this exception may be raised when the user:

> 

> * Attempts to execute a query which would exceed the privacy budget of the accountant.

> * Attempts to change the slack of the accountant in such a way that the existing budget spends would exceed the

> accountant’s budget.

> 

> 

> 

### General classes[¶](#general-classes "Permalink to this headline")

*class* diffprivlib.utils.Budget(*epsilon*, *delta*)[[source]](_modules/diffprivlib/utils.html#Budget)[¶](#diffprivlib.utils.Budget "Permalink to this definition")

Custom tuple subclass for privacy budgets of the form (epsilon, delta).

The `Budget` class allows for correct comparison/ordering of privacy budget, ensuring that both epsilon and delta

satisfy the comparison (tuples are compared lexicographically). Additionally, tuples are represented with added

verbosity, labelling epsilon and delta appropriately.

Examples

```

>>> from diffprivlib.utils import Budget

>>> Budget(1, 0.5)

(epsilon=1, delta=0.5)

>>> Budget(2, 0) >= Budget(1, 0.5)

False

>>> (2, 0) >= (1, 0.5) # Tuples are compared with lexicographic ordering

True

```

### General functions[¶](#general-functions "Permalink to this headline")

diffprivlib.utils.copy\_docstring(*source*)[[source]](_modules/diffprivlib/utils.html#copy_docstring)[¶](#diffprivlib.utils.copy_docstring "Permalink to this definition")

Decorator function to copy a docstring from a source function to a target function.

The docstring is only copied if a docstring is present in source, and if none is present in target. Takes

inspiration from similar in matplotlib.

Parameters

**source** (*method*) – Source function from which to copy the docstring. If `source.\_\_doc\_\_` is empty, do nothing.

Returns

**target** – Target function with new docstring.

Return type

method

diffprivlib.utils.global\_seed(*seed*)[[source]](_modules/diffprivlib/utils.html#global_seed)[¶](#diffprivlib.utils.global_seed "Permalink to this definition")

Sets the seed for all random number generators, to guarantee reproducibility in experiments.

Parameters

**seed** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The seed value for the random number generators.

Returns

Return type

[None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

diffprivlib.utils.warn\_unused\_args(*args*)[[source]](_modules/diffprivlib/utils.html#warn_unused_args)[¶](#diffprivlib.utils.warn_unused_args "Permalink to this definition")

Warn the user about supplying unused args to a diffprivlib model.

Arguments can be supplied as a string, a list of strings, or a dictionary as supplied to kwargs.

Parameters

**args** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") *or* [*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") *or* [*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – Arguments for which warnings should be thrown.

Returns

Return type

[None](https://docs.python.org/3/library/constants.html#None "(in Python v3.9)")

Validation functions[¶](#module-diffprivlib.validation "Permalink to this headline")

------------------------------------------------------------------------------------

Validation functions for the differential privacy library

### General functions[¶](#general-functions "Permalink to this headline")

diffprivlib.validation.check\_epsilon\_delta(*epsilon*, *delta*, *allow\_zero=False*)[[source]](_modules/diffprivlib/validation.html#check_epsilon_delta)[¶](#diffprivlib.validation.check_epsilon_delta "Permalink to this definition")

Checks that epsilon and delta are valid values for differential privacy. Throws an error if checks fail,

otherwise returns nothing.

As well as the requirements of epsilon and delta separately, both cannot be simultaneously zero, unless

`allow\_zero` is set to `True`.

Parameters

* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Epsilon parameter for differential privacy. Must be non-negative.

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Delta parameter for differential privacy. Must be on the unit interval, [0, 1].

* **allow\_zero** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default: False*) – Allow epsilon and delta both be zero.

diffprivlib.validation.check\_bounds(*bounds*, *shape=0*, *min\_separation=0.0*, *dtype=<class 'float'>*)[[source]](_modules/diffprivlib/validation.html#check_bounds)[¶](#diffprivlib.validation.check_bounds "Permalink to this definition")

Input validation for the `bounds` parameter.

Checks that `bounds` is composed of a list of tuples of the form (lower, upper), where lower <= upper and both

are numeric. Also checks that `bounds` contains the appropriate number of dimensions, and that there is a

`min\_separation` between the bounds.

Parameters

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")) – Tuple of bounds of the form (min, max). min and max can either be scalars or 1-dimensional arrays.

* **shape** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default: 0*) – Number of dimensions to be expected in `bounds`.

* **min\_separation** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default: 0.0*) – The minimum separation between lower and upper of each dimension. This separation is enforced if not

already satisfied.

* **dtype** (*data-type**,* *default: float*) – Data type of the returned bounds.

Returns

**bounds**

Return type

[tuple](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")

diffprivlib.validation.clip\_to\_norm(*array*, *clip*)[[source]](_modules/diffprivlib/validation.html#clip_to_norm)[¶](#diffprivlib.validation.clip_to_norm "Permalink to this definition")

Clips the examples of a 2-dimensional array to a given maximum norm.

Parameters

* **array** (*np.ndarray*) – Array to be clipped. After clipping, all examples have a 2-norm of at most clip.

* **clip** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – Norm at which to clip each example

Returns

**array** – The clipped array.

Return type

np.ndarray

diffprivlib.validation.clip\_to\_bounds(*array*, *bounds*)[[source]](_modules/diffprivlib/validation.html#clip_to_bounds)[¶](#diffprivlib.validation.clip_to_bounds "Permalink to this definition")

Clips the examples of a 2-dimensional array to given bounds.

Parameters

* **array** (*np.ndarray*) – Array to be clipped. After clipping, all examples have a 2-norm of at most clip.

* **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")) – Tuple of bounds of the form (min, max) which the array is to be clipped to. min and max must be scalar,

unless array is 2-dimensional.

Returns

**array** – The clipped array.

Return type

np.ndarray

Indices and tables[¶](#indices-and-tables "Permalink to this headline")

=======================================================================

* [Index](genindex.html)

* [Module Index](py-modindex.html)

* [Search Page](search.html)

