Python scipy.stats.poisson() Examples

The following are 30 code examples of scipy.stats.poisson(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy.stats , or try the search function .
Example #1
Source File: unguided_network.py    From nconv with GNU General Public License v3.0 6 votes vote down vote up
def navg_layer(self, kernel_size, init_stdev=0.5, in_channels=1, out_channels=1, initalizer='x', pos=False, groups=1):
        
        navg = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1, 
                         padding=(kernel_size[0]//2, kernel_size[1]//2), bias=False, groups=groups)
        
        weights = navg.weight            
        
        if initalizer == 'x': # Xavier            
            torch.nn.init.xavier_uniform(weights)
        elif initalizer == 'k':    
            torch.nn.init.kaiming_uniform(weights)
        elif initalizer == 'p':    
            mu=kernel_size[0]/2 
            dist = poisson(mu)
            x = np.arange(0, kernel_size[0])
            y = np.expand_dims(dist.pmf(x),1)
            w = signal.convolve2d(y, y.transpose(), 'full')
            w = torch.FloatTensor(w).cuda()
            w = torch.unsqueeze(w,0)
            w = torch.unsqueeze(w,1)
            w = w.repeat(out_channels, 1, 1, 1)
            w = w.repeat(1, in_channels, 1, 1)
            weights.data = w + torch.rand(w.shape).cuda()
         
        return navg 
Example #2
Source File: draw_pmf.py    From machine-learning-note with MIT License 6 votes vote down vote up
def poisson_pmf(mu=3):
    """
    泊松分布
    https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.poisson.html#scipy.stats.poisson
    :param mu: 单位时间(或单位面积)内随机事件的平均发生率
    :return:
    """
    poisson_dis = stats.poisson(mu)
    x = np.arange(poisson_dis.ppf(0.001), poisson_dis.ppf(0.999))
    print(x)
    fig, ax = plt.subplots(1, 1)
    ax.plot(x, poisson_dis.pmf(x), 'bo', ms=8, label='poisson pmf')
    ax.vlines(x, 0, poisson_dis.pmf(x), colors='b', lw=5, alpha=0.5)
    ax.legend(loc='best', frameon=False)
    plt.ylabel('Probability')
    plt.title('PMF of poisson distribution(mu={})'.format(mu))
    plt.show()

# poisson_pmf(mu=8) 
Example #3
Source File: bootstrap.py    From resample with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _resample_parametric(
    sample: np.ndarray, size: int, dist, rng: np.random.Generator,
) -> Generator[np.ndarray, None, None]:
    n = len(sample)

    # fit parameters by maximum likelihood and sample from that
    if dist == stats.poisson:
        # - poisson has no fit method and there is no scale parameter
        # - random number generation for poisson distribution in scipy seems to be buggy
        mu = np.mean(sample)
        for _ in range(size):
            yield rng.poisson(mu, size=n)
    else:
        args = _fit_parametric_family(dist, sample)
        dist = dist(*args)
        for _ in range(size):
            yield dist.rvs(size=n, random_state=rng) 
Example #4
Source File: test_bootstrap.py    From resample with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_resample_1d_statistical_test_poisson(rng):
    # poisson is behaving super weird in scipy
    x = rng.poisson(1.5, size=1000)
    mu = np.mean(x)

    xe = (0, 1, 2, 3, 10)
    # somehow location 1 is needed here...
    wref = np.diff(stats.poisson(mu, 1).cdf(xe)) * len(x)

    # compute P values for replicas compared to original
    prob = []
    for bx in resample(x, 100, method="poisson", random_state=rng):
        w = np.histogram(bx, bins=xe)[0]
        c = stats.chisquare(w, wref)
        prob.append(c.pvalue)

    # check whether P value distribution is flat
    # - test has chance probability of 1 % to fail randomly
    # - if it fails due to programming error, value is typically < 1e-20
    wp = np.histogram(prob, range=(0, 1))[0]
    c = stats.chisquare(wp)
    assert c.pvalue > 0.01 
Example #5
Source File: test_mixedvine.py    From mixedvines with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        '''
        Saves the current random state for later recovery, sets the random seed
        to get reproducible results and manually constructs a mixed vine.
        '''
        # Save random state for later recovery
        self.random_state = np.random.get_state()
        # Set fixed random seed
        np.random.seed(0)
        # Manually construct mixed vine
        self.dim = 3  # Dimension
        self.vine = MixedVine(self.dim)
        # Specify marginals
        self.vine.set_marginal(0, norm(0, 1))
        self.vine.set_marginal(1, poisson(5))
        self.vine.set_marginal(2, gamma(2, 0, 4))
        # Specify pair copulas
        self.vine.set_copula(1, 0, GaussianCopula(0.5))
        self.vine.set_copula(1, 1, FrankCopula(4))
        self.vine.set_copula(2, 0, ClaytonCopula(5)) 
Example #6
Source File: discretemodels.py    From abcpy with BSD 3-Clause Clear License 6 votes vote down vote up
def pmf(self, input_values, x):
        """Calculates the probability mass function of the distribution at point x.

        Parameters
        ----------
        input_values: list
            List of input parameters, in the same order as specified in the InputConnector passed to the init function
        x: integer
            The point at which the pmf should be evaluated.

        Returns
        -------
        Float
            The evaluated pmf at point x.
        """

        pmf = poisson(int(input_values[0])).pmf(x)
        self.calculated_pmf = pmf
        return pmf 
Example #7
Source File: discretemodels.py    From abcpy with BSD 3-Clause Clear License 6 votes vote down vote up
def forward_simulate(self, input_values, k, rng=np.random.RandomState(), mpi_comm=None):
        """
        Samples k values from the defined possion distribution.

        Parameters
        ----------
        input_values: list
            List of input parameters, in the same order as specified in the InputConnector passed to the init function
        k: integer
            The number of samples.
        rng: random number generator
            The random number generator to be used.

        Returns
        -------
        list: [np.ndarray]
            A list containing the sampled values as np-array.


        """

        result = rng.poisson(int(input_values[0]), k)
        return [np.array([x]) for x in result] 
Example #8
Source File: discretemodels.py    From abcpy with BSD 3-Clause Clear License 6 votes vote down vote up
def __init__(self, parameters, name='Poisson'):
        """This class implements a probabilistic model following a poisson distribution.

        Parameters
        ----------
        parameters: list
            A list containing one entry, the mean of the distribution.

        name: string
            The name that should be given to the probabilistic model in the journal file.
        """

        if not isinstance(parameters, list):
            raise TypeError('Input for Poisson has to be of type list.')
        if len(parameters)!=1:
            raise ValueError('Input for Poisson has to be of length 1.')

        self._dimension = 1
        input_parameters = InputConnector.from_list(parameters)
        super(Poisson, self).__init__(input_parameters, name)
        self.visited = False 
Example #9
Source File: allocation_agents.py    From ml-fairness-gym with Apache License 2.0 6 votes vote down vote up
def _LL(self, data, rate):
    """Return likelihood of the given data with the given rate as the poisson parameter."""
    observed_count = np.array(data[:, 0])
    allocated_count = np.array(data[:, 1])
    output_array = np.zeros(len(observed_count))

    assert len(observed_count) == len(allocated_count)

    output_array += (observed_count < allocated_count) * stats.poisson.pmf(
        observed_count, rate)
    # The probability of observing a count equal to the allocated count is
    # the tail of the poisson pmf from the observed_count value.
    # Summing the tail is equivalent to 1-the sum of the head up to
    # observed_count which is the value of the cdf at the observed_count-1.
    output_array += (observed_count == allocated_count) * (
        1.0 - stats.poisson.cdf(observed_count - 1, rate))

    return output_array 
Example #10
Source File: test_distributions.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_pickling(self):
        # test that a frozen instance pickles and unpickles
        # (this method is a clone of common_tests.check_pickling)
        beta = stats.beta(2.3098496451481823, 0.62687954300963677)
        poiss = stats.poisson(3.)
        sample = stats.rv_discrete(values=([0, 1, 2, 3],
                                           [0.1, 0.2, 0.3, 0.4]))

        for distfn in [beta, poiss, sample]:
            distfn.random_state = 1234
            distfn.rvs(size=8)
            s = pickle.dumps(distfn)
            r0 = distfn.rvs(size=8)

            unpickled = pickle.loads(s)
            r1 = unpickled.rvs(size=8)
            assert_equal(r0, r1)

            # also smoke test some methods
            medians = [distfn.ppf(0.5), unpickled.ppf(0.5)]
            assert_equal(medians[0], medians[1])
            assert_equal(distfn.cdf(medians[0]),
                         unpickled.cdf(medians[1])) 
Example #11
Source File: nconv.py    From nconv with GNU General Public License v3.0 6 votes vote down vote up
def init_parameters(self):
        # Init weights
        if self.init_method == 'x': # Xavier            
            torch.nn.init.xavier_uniform_(self.weight)
        elif self.init_method == 'k': # Kaiming
            torch.nn.init.kaiming_uniform_(self.weight)
        elif self.init_method == 'p': # Poisson
            mu=self.kernel_size[0]/2 
            dist = poisson(mu)
            x = np.arange(0, self.kernel_size[0])
            y = np.expand_dims(dist.pmf(x),1)
            w = signal.convolve2d(y, y.transpose(), 'full')
            w = torch.Tensor(w).type_as(self.weight)
            w = torch.unsqueeze(w,0)
            w = torch.unsqueeze(w,1)
            w = w.repeat(self.out_channels, 1, 1, 1)
            w = w.repeat(1, self.in_channels, 1, 1)
            self.weight.data = w + torch.rand(w.shape)
            
        # Init bias
        self.bias = torch.nn.Parameter(torch.zeros(self.out_channels)+0.01)
        
        
# Non-negativity enforcement class 
Example #12
Source File: unguided_network.py    From nconv with GNU General Public License v3.0 6 votes vote down vote up
def navg_layer(self, kernel_size, init_stdev=0.5, in_channels=1, out_channels=1, initalizer='x', pos=False, groups=1):
        
        navg = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1, 
                         padding=(kernel_size[0]//2, kernel_size[1]//2), bias=False, groups=groups)
        
        weights = navg.weight            
        
        if initalizer == 'x': # Xavier            
            torch.nn.init.xavier_uniform(weights)
        elif initalizer == 'k':    
            torch.nn.init.kaiming_uniform(weights)
        elif initalizer == 'p':    
            mu=kernel_size[0]/2 
            dist = poisson(mu)
            x = np.arange(0, kernel_size[0])
            y = np.expand_dims(dist.pmf(x),1)
            w = signal.convolve2d(y, y.transpose(), 'full')
            w = torch.FloatTensor(w).cuda()
            w = torch.unsqueeze(w,0)
            w = torch.unsqueeze(w,1)
            w = w.repeat(out_channels, 1, 1, 1)
            w = w.repeat(1, in_channels, 1, 1)
            weights.data = w + torch.rand(w.shape).cuda()
         
        return navg 
Example #13
Source File: unguided_network.py    From nconv with GNU General Public License v3.0 6 votes vote down vote up
def navg_layer(self, kernel_size, init_stdev=0.5, in_channels=1, out_channels=1, initalizer='x', pos=False, groups=1):
        
        navg = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1, 
                         padding=(kernel_size[0]//2, kernel_size[1]//2), bias=False, groups=groups)
        
        weights = navg.weight            
        
        if initalizer == 'x': # Xavier            
            torch.nn.init.xavier_uniform(weights)
        elif initalizer == 'k':    
            torch.nn.init.kaiming_uniform(weights)
        elif initalizer == 'p':    
            mu=kernel_size[0]/2 
            dist = poisson(mu)
            x = np.arange(0, kernel_size[0])
            y = np.expand_dims(dist.pmf(x),1)
            w = signal.convolve2d(y, y.transpose(), 'full')
            w = torch.FloatTensor(w).cuda()
            w = torch.unsqueeze(w,0)
            w = torch.unsqueeze(w,1)
            w = w.repeat(out_channels, 1, 1, 1)
            w = w.repeat(1, in_channels, 1, 1)
            weights.data = w + torch.rand(w.shape).cuda()
         
        return navg 
Example #14
Source File: poisson_threshold.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def prob_noise_above_th(rate, T, m):
    """Returns the probability that noise is above the burst search threshold.

    Basically is the probability that a poisson process with rate "rate" had
    "m" or more events in a time window "T".
    """
    return poisson(rate*T).sf(m-1) 
Example #15
Source File: allocation_agents.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def _calculate_tail_probability(self, x, rate):
    """Calculates the probability c>=x for all c for a poisson(rate)."""
    return 1 - stats.poisson.cdf(x - 1, rate) 
Example #16
Source File: allocation_agents.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def _construct_approx_fi_table(self, n_bins, rates, n_resource):
    """Constructs a n_bins by n_resource+1 matrix of f_i values.

    Args:
      n_bins: int number of bins.
      rates: rate for each bin.
      n_resource: int number of resources available to allocate.

    Returns:
      np.ndarray of f_i(v_i) for every allocation, bin pair.
    """
    c_values = np.array(
        range(1, self.params.poisson_truncation_val), dtype=float).reshape(
            (self.params.poisson_truncation_val - 1, 1))
    c_values_with0 = np.array(
        range(self.params.poisson_truncation_val), dtype=float).reshape(
            (self.params.poisson_truncation_val, 1))
    alloc_vals = np.array(
        range(1, n_resource), dtype=float).reshape((n_resource - 1, 1))
    poissons = stats.poisson(mu=np.array(rates))
    pmf_values = poissons.pmf(c_values_with0)

    minimums = np.minimum(alloc_vals.T, c_values)
    mins_over_c = np.divide(minimums, c_values)
    # defining 0/0 to be 1, can change to np.zeros if 0/0 should be zero.
    mins_over_c = np.concatenate((np.ones((1, n_resource - 1)), mins_over_c),
                                 axis=0)
    # can also switch the order of these concatenates depending on if min(v,c)/c
    # where v=0, c=0 should be 0 or one.
    mins_over_c = np.concatenate((np.zeros(
        (self.params.poisson_truncation_val, 1)), mins_over_c),
                                 axis=1)
    fi = np.matmul(pmf_values.T, mins_over_c)
    return fi 
Example #17
Source File: test_toy.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_intensity():
    from ctapipe.image.toymodel import Gaussian

    np.random.seed(0)
    geom = CameraGeometry.from_name("LSTCam")

    x, y = u.Quantity([0.2, 0.3], u.m)
    width = 0.05 * u.m
    length = 0.15 * u.m
    intensity = 50
    psi = "30d"

    # make a toymodel shower model
    model = Gaussian(x=x, y=y, width=width, length=length, psi=psi)

    _, signal, _ = model.generate_image(geom, intensity=intensity, nsb_level_pe=5,)

    # test if signal reproduces given cog values
    assert np.average(geom.pix_x.to_value(u.m), weights=signal) == approx(0.2, rel=0.15)
    assert np.average(geom.pix_y.to_value(u.m), weights=signal) == approx(0.3, rel=0.15)

    # test if signal reproduces given width/length values
    cov = np.cov(geom.pix_x.value, geom.pix_y.value, aweights=signal)
    eigvals, _ = np.linalg.eigh(cov)

    assert np.sqrt(eigvals[0]) == approx(width.to_value(u.m), rel=0.15)
    assert np.sqrt(eigvals[1]) == approx(length.to_value(u.m), rel=0.15)

    # test if total intensity is inside in 99 percent confidence interval
    assert poisson(intensity).ppf(0.05) <= signal.sum() <= poisson(intensity).ppf(0.95) 
Example #18
Source File: numpy_backend.py    From pyhf with Apache License 2.0 5 votes vote down vote up
def sample(self, sample_shape):
        return poisson(self.rate).rvs(size=sample_shape + self.rate.shape) 
Example #19
Source File: numpy_backend.py    From pyhf with Apache License 2.0 5 votes vote down vote up
def poisson(self, n, lam):
        r"""
        The continous approximation, using :math:`n! = \Gamma\left(n+1\right)`,
        to the probability mass function of the Poisson distribution evaluated
        at :code:`n` given the parameter :code:`lam`.

        Example:

            >>> import pyhf
            >>> pyhf.set_backend("numpy")
            >>> pyhf.tensorlib.poisson(5., 6.)
            0.16062314104797995
            >>> values = pyhf.tensorlib.astensor([5., 9.])
            >>> rates = pyhf.tensorlib.astensor([6., 8.])
            >>> pyhf.tensorlib.poisson(values, rates)
            array([0.16062314, 0.12407692])

        Args:
            n (`tensor` or `float`): The value at which to evaluate the approximation to the Poisson distribution p.m.f.
                                  (the observed number of events)
            lam (`tensor` or `float`): The mean of the Poisson distribution p.m.f.
                                    (the expected number of events)

        Returns:
            NumPy float: Value of the continous approximation to Poisson(n|lam)
        """
        n = np.asarray(n)
        lam = np.asarray(lam)
        return np.exp(n * np.log(lam) - lam - gammaln(n + 1.0)) 
Example #20
Source File: test_distributions.py    From Computable with MIT License 5 votes vote down vote up
def test_poisson(self):
        # poisson, use lower bound only
        prob_bounds = stats.poisson.expect(lambda x: 1, args=(2,), lb=3,
                                      conditional=False)
        prob_b_true = 1-stats.poisson.cdf(2,2)
        assert_almost_equal(prob_bounds, prob_b_true, decimal=14)

        prob_lb = stats.poisson.expect(lambda x: 1, args=(2,), lb=2,
                                       conditional=True)
        assert_almost_equal(prob_lb, 1, decimal=14) 
Example #21
Source File: test_distributions.py    From Computable with MIT License 5 votes vote down vote up
def test_stats(self):
        mu = 16.0
        result = stats.poisson.stats(mu, moments='mvsk')
        assert_allclose(result, [mu, mu, np.sqrt(1.0/mu), 1.0/mu]) 
Example #22
Source File: test_distributions.py    From Computable with MIT License 5 votes vote down vote up
def test_rvs(self):
        vals = stats.poisson.rvs(0.5, size=(2, 50))
        assert_(numpy.all(vals >= 0))
        assert_(numpy.shape(vals) == (2, 50))
        assert_(vals.dtype.char in typecodes['AllInteger'])
        val = stats.poisson.rvs(0.5)
        assert_(isinstance(val, int))
        val = stats.poisson(0.5).rvs(3)
        assert_(isinstance(val, numpy.ndarray))
        assert_(val.dtype.char in typecodes['AllInteger']) 
Example #23
Source File: count.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def predict_distribution(self, exog):
        '''return frozen scipy.stats distribution with mu at estimated prediction
        '''
        if not hasattr(self, result):
            raise ValueError
        else:
            mu = np.exp(np.dot(exog, params))
            return stats.poisson(mu, loc=0) 
Example #24
Source File: test_distributions.py    From numpyro with Apache License 2.0 5 votes vote down vote up
def gen_values_within_bounds(constraint, size, key=random.PRNGKey(11)):
    eps = 1e-6

    if isinstance(constraint, constraints._Boolean):
        return random.bernoulli(key, shape=size)
    elif isinstance(constraint, constraints._GreaterThan):
        return jnp.exp(random.normal(key, size)) + constraint.lower_bound + eps
    elif isinstance(constraint, constraints._IntegerInterval):
        lower_bound = jnp.broadcast_to(constraint.lower_bound, size)
        upper_bound = jnp.broadcast_to(constraint.upper_bound, size)
        return random.randint(key, size, lower_bound, upper_bound + 1)
    elif isinstance(constraint, constraints._IntegerGreaterThan):
        return constraint.lower_bound + random.poisson(key, np.array(5), shape=size)
    elif isinstance(constraint, constraints._Interval):
        lower_bound = jnp.broadcast_to(constraint.lower_bound, size)
        upper_bound = jnp.broadcast_to(constraint.upper_bound, size)
        return random.uniform(key, size, minval=lower_bound, maxval=upper_bound)
    elif isinstance(constraint, (constraints._Real, constraints._RealVector)):
        return random.normal(key, size)
    elif isinstance(constraint, constraints._Simplex):
        return osp.dirichlet.rvs(alpha=jnp.ones((size[-1],)), size=size[:-1])
    elif isinstance(constraint, constraints._Multinomial):
        n = size[-1]
        return multinomial(key, p=jnp.ones((n,)) / n, n=constraint.upper_bound, shape=size[:-1])
    elif isinstance(constraint, constraints._CorrCholesky):
        return signed_stick_breaking_tril(
            random.uniform(key, size[:-2] + (size[-1] * (size[-1] - 1) // 2,), minval=-1, maxval=1))
    elif isinstance(constraint, constraints._CorrMatrix):
        cholesky = signed_stick_breaking_tril(
            random.uniform(key, size[:-2] + (size[-1] * (size[-1] - 1) // 2,), minval=-1, maxval=1))
        return jnp.matmul(cholesky, jnp.swapaxes(cholesky, -2, -1))
    elif isinstance(constraint, constraints._LowerCholesky):
        return jnp.tril(random.uniform(key, size))
    elif isinstance(constraint, constraints._PositiveDefinite):
        x = random.normal(key, size)
        return jnp.matmul(x, jnp.swapaxes(x, -2, -1))
    elif isinstance(constraint, constraints._OrderedVector):
        x = jnp.cumsum(random.exponential(key, size), -1)
        return x - random.normal(key, size[:-1])
    else:
        raise NotImplementedError('{} not implemented.'.format(constraint)) 
Example #25
Source File: test_distributions.py    From numpyro with Apache License 2.0 5 votes vote down vote up
def gen_values_outside_bounds(constraint, size, key=random.PRNGKey(11)):
    if isinstance(constraint, constraints._Boolean):
        return random.bernoulli(key, shape=size) - 2
    elif isinstance(constraint, constraints._GreaterThan):
        return constraint.lower_bound - jnp.exp(random.normal(key, size))
    elif isinstance(constraint, constraints._IntegerInterval):
        lower_bound = jnp.broadcast_to(constraint.lower_bound, size)
        return random.randint(key, size, lower_bound - 1, lower_bound)
    elif isinstance(constraint, constraints._IntegerGreaterThan):
        return constraint.lower_bound - random.poisson(key, np.array(5), shape=size)
    elif isinstance(constraint, constraints._Interval):
        upper_bound = jnp.broadcast_to(constraint.upper_bound, size)
        return random.uniform(key, size, minval=upper_bound, maxval=upper_bound + 1.)
    elif isinstance(constraint, (constraints._Real, constraints._RealVector)):
        return lax.full(size, jnp.nan)
    elif isinstance(constraint, constraints._Simplex):
        return osp.dirichlet.rvs(alpha=jnp.ones((size[-1],)), size=size[:-1]) + 1e-2
    elif isinstance(constraint, constraints._Multinomial):
        n = size[-1]
        return multinomial(key, p=jnp.ones((n,)) / n, n=constraint.upper_bound, shape=size[:-1]) + 1
    elif isinstance(constraint, constraints._CorrCholesky):
        return signed_stick_breaking_tril(
            random.uniform(key, size[:-2] + (size[-1] * (size[-1] - 1) // 2,),
                           minval=-1, maxval=1)) + 1e-2
    elif isinstance(constraint, constraints._CorrMatrix):
        cholesky = 1e-2 + signed_stick_breaking_tril(
            random.uniform(key, size[:-2] + (size[-1] * (size[-1] - 1) // 2,), minval=-1, maxval=1))
        return jnp.matmul(cholesky, jnp.swapaxes(cholesky, -2, -1))
    elif isinstance(constraint, constraints._LowerCholesky):
        return random.uniform(key, size)
    elif isinstance(constraint, constraints._PositiveDefinite):
        return random.normal(key, size)
    elif isinstance(constraint, constraints._OrderedVector):
        x = jnp.cumsum(random.exponential(key, size), -1)
        return x[..., ::-1]
    else:
        raise NotImplementedError('{} not implemented.'.format(constraint)) 
Example #26
Source File: count.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def predict_distribution(self, exog):
        '''return frozen scipy.stats distribution with mu at estimated prediction
        '''
        if not hasattr(self, result):
            raise ValueError
        else:
            mu = np.exp(np.dot(exog, params))
            return stats.poisson(mu, loc=0) 
Example #27
Source File: discrete_distributions.py    From machine-learning-note with MIT License 5 votes vote down vote up
def poisson_dis(mu=3.0):
    """
    泊松分布
    :param mu: 单位时间(或单位面积)内随机事件的平均发生率
    :return:
    """
    mu = 2
    poisson_dist = stats.poisson(mu)
    X2 = np.arange(5)
    x_prob2 = poisson_dist.pmf(X2)
    plt.plot(X2, x_prob2)
    poisson_dist.pmf(3)  # 0.18, 恰好发生3次的概率 
Example #28
Source File: test_distributions.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_mu0(self):
        # Edge case: mu=0
        vals = stats.poisson.pmf([0, 1, 2], 0)
        expected = [1, 0, 0]
        assert_array_equal(vals, expected)

        interval = stats.poisson.interval(0.95, 0)
        assert_equal(interval, (0, 0)) 
Example #29
Source File: poisson_threshold.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def find_optimal_T_iter(bg_rate, m, P_user, max_iter=int(1e6), debug=False):
    """Returns the T (sec.) that assure prob. P_user or less to have noise.

    Given a background rate (bg_rate) find a T such as Poiss{bg_rate*T} has
    probability to have m or more events (k >= m) lesser than P_user.

    In other words find the max T that satisfies: poisson(lam*T).sf(m) < P_user
    """

    # Initial T in seconds
    T = 1.  # start from a huge T window that gives an enormous rate such as
            # lam*T is so high that poisson(lam*T).sf(m) would be for sure >
            # P_user, then decrease T until poisson(lam*T).sf(m) < T

    converged = False
    for i in range(max_iter):
        prob = prob_noise_above_th(bg_rate,T,m)
        if prob > P_user:
            T /= 2.
        else:
            converged = True
            break
    if not converged: raise StopIteration
    if debug: print("T_min = %.3f ms, T_max = %.3f ms" % (T*1e3, 2*T*1e3))

    step = T/1000.
    T = 2*T
    converged = False
    for i in range(max_iter):
        prob = prob_noise_above_th(bg_rate,T,m)
        if prob > P_user:
            T -= step
        else:
            converged = True
            break
    if not converged: raise StopIteration
    if debug: print(" >T_min = %.3f ms, T_max = %.3f ms" % (T*1e3, (T+step)*1e3))
    return T 
Example #30
Source File: select_bursts.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def na_bg_p(d, ich=0, P=0.05, F=1.):
    """Select bursts w/ AD signal using P{F*BG>=na} < P."""
    accept_ch_bg_rate = d.bg_mean(Ph_sel(Dex='Aem'))[ich]
    bursts_width = _clk_to_s(d.mburst[ich].width)
    max_num_bg_ph = stats.poisson(F*accept_ch_bg_rate*bursts_width).isf(P)
    #print("Min num. ph = ",  max_num_bg_ph)
    bursts_mask = (d.na[ich] >= max_num_bg_ph)
    return bursts_mask, ''