本文整理汇总了Python中scipy.stats.rv_discrete方法的典型用法代码示例。如果您正苦于以下问题:Python stats.rv_discrete方法的具体用法?Python stats.rv_discrete怎么用?Python stats.rv_discrete使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.stats
的用法示例。
在下文中一共展示了stats.rv_discrete方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: probs_to_word_ix
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def probs_to_word_ix(pk, is_first):
if is_first:
pk[0] = 0.0
pk /= np.sum(pk)
else:
pk *= pk
pk /= np.sum(pk)
#for i in range(3):
# max_val = np.amax(pk)
# if max_val > 0.5:
# break
# pk *= pk
# pk /= np.sum(pk)
xk = np.arange(pk.shape[0], dtype=np.int32)
custm = stats.rv_discrete(name='custm', values=(xk, pk))
return custm.rvs()
示例2: check_edge_support
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def check_edge_support(distfn, args):
# Make sure that x=self.a and self.b are handled correctly.
x = [distfn.a, distfn.b]
if isinstance(distfn, stats.rv_discrete):
x = [distfn.a - 1, distfn.b]
npt.assert_equal(distfn.cdf(x, *args), [0.0, 1.0])
npt.assert_equal(distfn.sf(x, *args), [1.0, 0.0])
if distfn.name not in ('skellam', 'dlaplace'):
# with a = -inf, log(0) generates warnings
npt.assert_equal(distfn.logcdf(x, *args), [-np.inf, 0.0])
npt.assert_equal(distfn.logsf(x, *args), [0.0, -np.inf])
npt.assert_equal(distfn.ppf([0.0, 1.0], *args), x)
npt.assert_equal(distfn.isf([0.0, 1.0], *args), x[::-1])
# out-of-bounds for isf & ppf
npt.assert_(np.isnan(distfn.isf([-1, 2], *args)).all())
npt.assert_(np.isnan(distfn.ppf([-1, 2], *args)).all())
示例3: test_pickling
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [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: perform
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def perform(self, action):
# get distribution about outcomes
probabilities = self.belief[action] / np.sum(self.belief[action])
distrib = rv_discrete(values=(range(len(probabilities)),
probabilities))
# draw sample
sample = distrib.rvs()
# update belief accordingly
belief = deepcopy(self.belief)
belief[action][sample] += 1
# manual found
if (self.pos == self.world.manual).all():
print("m", end="")
belief = {ToyWorldAction(np.array([0, 1])): [50, 1, 1, 1],
ToyWorldAction(np.array([0, -1])): [1, 50, 1, 1],
ToyWorldAction(np.array([1, 0])): [1, 1, 50, 1],
ToyWorldAction(np.array([-1, 0])): [1, 1, 1, 50]}
# build next state
pos = self._correct_position(self.pos + self.actions[sample].action)
return ToyWorldState(pos, self.world, belief)
示例5: sample
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def sample(self, X):
""" sample from the conditional mixture distributions - requires the model to be fitted
Args:
X: values to be conditioned on when sampling - numpy array of shape (n_instances, n_dim_x)
Returns: tuple (X, Y)
- X - the values to conditioned on that were provided as argument - numpy array of shape (n_samples, ndim_x)
- Y - conditional samples from the model p(y|x) - numpy array of shape (n_samples, ndim_y)
"""
assert self.fitted
X = self._handle_input_dimensionality(X)
weights = np.multiply(self.alpha, self._gaussian_kernel(X))
weights = weights / np.sum(weights, axis=1)[:,None]
Y = np.zeros(shape=(X.shape[0], self.ndim_y))
for i in range(X.shape[0]):
discrete_dist = stats.rv_discrete(values=(range(weights.shape[1]), weights[i, :]))
idx = discrete_dist.rvs()
Y[i, :] = self.gaussians_y[idx].rvs()
return X, Y
示例6: custom_made_discrete_dis_pmf
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def custom_made_discrete_dis_pmf():
"""
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_discrete.html
:return:
"""
xk = np.arange(7) # 所有可能的取值
print(xk) # [0 1 2 3 4 5 6]
pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2) # 各个取值的概率
custm = stats.rv_discrete(name='custm', values=(xk, pk))
X = custm.rvs(size=20)
print(X)
fig, ax = plt.subplots(1, 1)
ax.plot(xk, custm.pmf(xk), 'ro', ms=8, mec='r')
ax.vlines(xk, 0, custm.pmf(xk), colors='r', linestyles='-', lw=2)
plt.title('Custom made discrete distribution(PMF)')
plt.ylabel('Probability')
plt.show()
# custom_made_discrete_dis_pmf()
示例7: choice_faces
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def choice_faces(verts, faces):
num = 4000
u1, u2, u3 = np.split(verts[faces[:, 0]] - verts[faces[:, 1]], 3, axis=1)
v1, v2, v3 = np.split(verts[faces[:, 1]] - verts[faces[:, 2]], 3, axis=1)
a = (u2 * v3 - u3 * v2) ** 2
b = (u3 * v1 - u1 * v3) ** 2
c = (u1 * v2 - u2 * v1) ** 2
Areas = np.sqrt(a + b + c) / 2
Areas = Areas / np.sum(Areas)
choices = np.expand_dims(np.arange(Areas.shape[0]), 1)
dist = stats.rv_discrete(name='custm', values=(choices, Areas))
choices = dist.rvs(size=num)
select_faces = faces[choices]
return select_faces
示例8: simulate
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def simulate(self):
endog, exog, group, time = [], [], [], []
for i in range(self.ngroups):
gsize = np.random.randint(self.group_size_range[0],
self.group_size_range[1])
group.append([i,] * gsize)
time1 = np.random.normal(size=(gsize,2))
time.append(time1)
exog1 = np.random.normal(size=(gsize, len(self.params[0])))
exog.append(exog1)
# Probabilities for each outcome
prob = [np.exp(np.dot(exog1, p)) for p in self.params]
prob = np.vstack(prob).T
prob /= prob.sum(1)[:, None]
m = len(self.params)
endog1 = []
for k in range(gsize):
pdist = stats.rv_discrete(values=(lrange(m),
prob[k,:]))
endog1.append(pdist.rvs())
endog.append(np.asarray(endog1))
self.exog = np.concatenate(exog, axis=0)
self.endog = np.concatenate(endog).astype(np.int32)
self.time = np.concatenate(time, axis=0)
self.group = np.concatenate(group)
self.offset = np.zeros(len(self.endog), dtype=np.float64)
示例9: test_rvs
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def test_rvs(self):
states = [-1,0,1,2,3,4]
probability = [0.0,0.3,0.4,0.0,0.3,0.0]
samples = 1000
r = stats.rv_discrete(name='sample',values=(states,probability))
x = r.rvs(size=samples)
assert_(isinstance(x, numpy.ndarray))
for s,p in zip(states,probability):
assert_(abs(sum(x == s)/float(samples) - p) < 0.05)
x = r.rvs()
assert_(isinstance(x, int))
示例10: test_entropy
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def test_entropy(self):
# Basic tests of entropy.
pvals = np.array([0.25, 0.45, 0.3])
p = stats.rv_discrete(values=([0, 1, 2], pvals))
expected_h = -sum(xlogy(pvals, pvals))
h = p.entropy()
assert_allclose(h, expected_h)
p = stats.rv_discrete(values=([0, 1, 2], [1.0, 0, 0]))
h = p.entropy()
assert_equal(h, 0.0)
示例11: test_no_name_arg
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def test_no_name_arg(self):
# If name is not given, construction shouldn't fail. See #1508.
stats.rv_continuous()
stats.rv_discrete()
示例12: test_docstrings
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def test_docstrings():
badones = [',\s*,', '\(\s*,', '^\s*:']
for distname in stats.__all__:
dist = getattr(stats, distname)
if isinstance(dist, (stats.rv_discrete, stats.rv_continuous)):
for regex in badones:
assert_( re.search(regex, dist.__doc__) is None)
示例13: generate_observation_from_state
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def generate_observation_from_state(self, state_index):
"""
Generate a single synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
Returns
-------
observation : float
A single observation from the given state.
Examples
--------
Generate an observation model.
>>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]]))
Generate sample from each state.
>>> observation = output_model.generate_observation_from_state(0)
"""
# generate random generator (note that this is inefficient - better use one of the next functions
import scipy.stats
gen = scipy.stats.rv_discrete(values=(range(len(self._output_probabilities[state_index])),
self._output_probabilities[state_index]))
gen.rvs(size=1)
示例14: generate_observations_from_state
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def generate_observations_from_state(self, state_index, nobs):
"""
Generate synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
nobs : int
The number of observations to generate.
Returns
-------
observations : numpy.array of shape(nobs,) with type dtype
A sample of `nobs` observations from the specified state.
Examples
--------
Generate an observation model.
>>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]]))
Generate sample from each state.
>>> observations = [output_model.generate_observations_from_state(state_index, nobs=100) for state_index in range(output_model.nstates)]
"""
import scipy.stats
gen = scipy.stats.rv_discrete(values=(range(self._nsymbols), self._output_probabilities[state_index]))
gen.rvs(size=nobs)
示例15: test_rvs
# 需要导入模块: from scipy import stats [as 别名]
# 或者: from scipy.stats import rv_discrete [as 别名]
def test_rvs(self):
states = [-1, 0, 1, 2, 3, 4]
probability = [0.0, 0.3, 0.4, 0.0, 0.3, 0.0]
samples = 1000
r = stats.rv_discrete(name='sample', values=(states, probability))
x = r.rvs(size=samples)
assert_(isinstance(x, numpy.ndarray))
for s, p in zip(states, probability):
assert_(abs(sum(x == s)/float(samples) - p) < 0.05)
x = r.rvs()
assert_(isinstance(x, int))