Example #1
0
 def test_rvs(self):
     vals = stats.dlaplace.rvs(1.5, size=(2, 50))
     assert numpy.shape(vals) == (2, 50)
     assert vals.dtype.char in typecodes["AllInteger"]
     val = stats.dlaplace.rvs(1.5)
     assert isinstance(val, int)
     val = stats.dlaplace(1.5).rvs(3)
     assert isinstance(val, numpy.ndarray)
     assert val.dtype.char in typecodes["AllInteger"]
Example #2
0
 def test_rvs(self):
     vals = stats.dlaplace.rvs(1.5 , size=(2, 50))
     assert_(numpy.shape(vals) == (2, 50))
     assert_(vals.dtype.char in typecodes['AllInteger'])
     val = stats.dlaplace.rvs(1.5)
     assert_(isinstance(val, int))
     val = stats.dlaplace(1.5).rvs(3)
     assert_(isinstance(val, numpy.ndarray))
     assert_(val.dtype.char in typecodes['AllInteger'])
    def test_stats(self):
        # compare the explicit formulas w/ direct summation using pmf
        a = 1.
        dl = stats.dlaplace(a)
        m, v, s, k = dl.stats('mvsk')

        N = 37
        xx = np.arange(-N, N+1)
        pp = dl.pmf(xx)
        m2, m4 = np.sum(pp*xx**2), np.sum(pp*xx**4)
        assert_equal((m, s), (0,0))
        assert_allclose((v, k), (m2, m4/m2**2 - 3.), atol=1e-14, rtol=1e-8)
Example #4
0
  def __init__(self,
               parameter: float,
               sensitivity: int = 1) -> None:
    """Initializes the privacy loss of the discrete Laplace mechanism.

    Args:
      parameter: the parameter of the discrete Laplace distribution.
      sensitivity: the sensitivity of function f. (i.e. the maximum absolute
        change in f when an input to a single user changes.)
    """
    if parameter <= 0:
      raise ValueError(f'Parameter is not a positive real number: {parameter}')

    if not isinstance(sensitivity, int):
      raise ValueError(f'Sensitivity is not an integer : {sensitivity}')

    self.sensitivity = sensitivity
    self._parameter = parameter
    self._discrete_laplace_random_variable = stats.dlaplace(parameter)
    super(DiscreteLaplacePrivacyLoss, self).__init__(sensitivity, True)
Example #5
0
    def test_laplace(self):
        from scipy.stats import dlaplace
        import matplotlib.pyplot as plt
        import numpy as np
        fig, ax = plt.subplots(1, 1)

        a = 0.8
        mean, var, skew, kurt = dlaplace.stats(a, moments='mvsk')

        x = np.arange(dlaplace.ppf(0.01, a), dlaplace.ppf(0.99, a))
        ax.plot(x, dlaplace.pmf(x, a), 'bo', ms=8, label='dlaplace pmf')
        ax.vlines(x, 0, dlaplace.pmf(x, a), colors='b', lw=5, alpha=0.5)

        rv = dlaplace(a)
        ax.vlines(x,
                  0,
                  rv.pmf(x),
                  colors='k',
                  linestyles='-',
                  lw=1,
                  label='frozen pmf')
        ax.legend(loc='best', frameon=False)
        self.assertEqual(str(ax), "AxesSubplot(0.125,0.11;0.775x0.77)")
Example #6
0
})


def build_layer_fcr(base_rv, decay_rate):
    return lambda prev, layer_num: (base_rv
                                    if prev is None else MixtureDistribution([
                                        poisson(prev * decay_rate, loc=2),
                                        DeltaDistribution(loc=prev),
                                        poisson(prev / decay_rate, loc=2),
                                    ]))


NUM_GRAPH_LAYERS_RV = geom(0.5)
DENSE_LAYERS_RV = LayerDistribution(
    num_layer_distribution=geom(0.5, loc=-1),
    layer_size_distribution_fn=build_layer_fcr(dlaplace(1e-1, loc=150), 0.5),
)


def constant_int_fcr(choices):
    n = len(choices)
    return lambda _1, _2: CategoricalRV(choices)


def filter_K_fcr(base_rv, delta_rate):
    return lambda prev, _: (base_rv if prev is None else MixtureDistribution([
        poisson(prev * delta_rate, loc=2),
        DeltaDistribution(loc=prev),
        poisson(prev / delta_rate, loc=2),
    ]))
a = 0.8
mean, var, skew, kurt = dlaplace.stats(a, moments='mvsk')

# Display the probability mass function (``pmf``):

x = np.arange(dlaplace.ppf(0.01, a), dlaplace.ppf(0.99, a))
ax.plot(x, dlaplace.pmf(x, a), 'bo', ms=8, label='dlaplace pmf')
ax.vlines(x, 0, dlaplace.pmf(x, a), colors='b', lw=5, alpha=0.5)

# Alternatively, the distribution object can be called (as a function)
# to fix the shape and location. This returns a "frozen" RV object holding
# the given parameters fixed.

# Freeze the distribution and display the frozen ``pmf``:

rv = dlaplace(a)
ax.vlines(x,
          0,
          rv.pmf(x),
          colors='k',
          linestyles='-',
          lw=1,
          label='frozen pmf')
ax.legend(loc='best', frameon=False)
plt.show()

# Check accuracy of ``cdf`` and ``ppf``:

prob = dlaplace.cdf(x, a)
np.allclose(x, dlaplace.ppf(prob, a))
# True
 def test_stats2(self):
     a = np.log(2.)
     dl = stats.dlaplace(a)
     m, v, s, k = dl.stats('mvsk')
     assert_equal((m, s), (0.,0.))
     assert_allclose((v, k), (4., 3.25))