本文整理汇总了Python中scipy.stats.poisson方法的典型用法代码示例。如果您正苦于以下问题:Python stats.poisson方法的具体用法?Python stats.poisson怎么用?Python stats.poisson使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.stats
的用法示例。
在下文中一共展示了stats.poisson方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_parameters
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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
示例2: navg_layer
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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
示例3: test_pickling
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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]))
示例4: _LL
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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
示例5: __init__
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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
示例6: forward_simulate
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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]
示例7: pmf
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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
示例8: setUp
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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))
示例9: test_resample_1d_statistical_test_poisson
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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
示例10: _resample_parametric
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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)
示例11: poisson_pmf
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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)
示例12: predict_distribution
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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)
示例13: test_rvs
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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'])
示例14: test_stats
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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])
示例15: test_poisson
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import poisson [as 别名]
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)