本文整理匯總了Python中scipy.stats.multivariate_normal.pdf方法的典型用法代碼示例。如果您正苦於以下問題:Python multivariate_normal.pdf方法的具體用法?Python multivariate_normal.pdf怎麽用?Python multivariate_normal.pdf使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類scipy.stats.multivariate_normal
的用法示例。
在下文中一共展示了multivariate_normal.pdf方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_marginalization
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def test_marginalization(self):
# Integrating out one of the variables of a 2D Gaussian should
# yield a 1D Gaussian
mean = np.array([2.5, 3.5])
cov = np.array([[.5, 0.2], [0.2, .6]])
n = 2 ** 8 + 1 # Number of samples
delta = 6 / (n - 1) # Grid spacing
v = np.linspace(0, 6, n)
xv, yv = np.meshgrid(v, v)
pos = np.empty((n, n, 2))
pos[:, :, 0] = xv
pos[:, :, 1] = yv
pdf = multivariate_normal.pdf(pos, mean, cov)
# Marginalize over x and y axis
margin_x = romb(pdf, delta, axis=0)
margin_y = romb(pdf, delta, axis=1)
# Compare with standard normal distribution
gauss_x = norm.pdf(v, loc=mean[0], scale=cov[0, 0] ** 0.5)
gauss_y = norm.pdf(v, loc=mean[1], scale=cov[1, 1] ** 0.5)
assert_allclose(margin_x, gauss_x, rtol=1e-2, atol=1e-2)
assert_allclose(margin_y, gauss_y, rtol=1e-2, atol=1e-2)
示例2: test_frozen_matrix_normal
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def test_frozen_matrix_normal(self):
for i in range(1,5):
for j in range(1,5):
M = 0.3 * np.ones((i,j))
U = 0.5 * np.identity(i) + 0.5 * np.ones((i,i))
V = 0.7 * np.identity(j) + 0.3 * np.ones((j,j))
frozen = matrix_normal(mean=M, rowcov=U, colcov=V)
rvs1 = frozen.rvs(random_state=1234)
rvs2 = matrix_normal.rvs(mean=M, rowcov=U, colcov=V,
random_state=1234)
assert_equal(rvs1, rvs2)
X = frozen.rvs(random_state=1234)
pdf1 = frozen.pdf(X)
pdf2 = matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V)
assert_equal(pdf1, pdf2)
logpdf1 = frozen.logpdf(X)
logpdf2 = matrix_normal.logpdf(X, mean=M, rowcov=U, colcov=V)
assert_equal(logpdf1, logpdf2)
示例3: test_frozen_dirichlet
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def test_frozen_dirichlet(self):
np.random.seed(2846)
n = np.random.randint(1, 32)
alpha = np.random.uniform(10e-10, 100, n)
d = dirichlet(alpha)
assert_equal(d.var(), dirichlet.var(alpha))
assert_equal(d.mean(), dirichlet.mean(alpha))
assert_equal(d.entropy(), dirichlet.entropy(alpha))
num_tests = 10
for i in range(num_tests):
x = np.random.uniform(10e-10, 100, n)
x /= np.sum(x)
assert_equal(d.pdf(x[:-1]), dirichlet.pdf(x[:-1], alpha))
assert_equal(d.logpdf(x[:-1]), dirichlet.logpdf(x[:-1], alpha))
示例4: _compute_probabilities
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def _compute_probabilities(self, probs, values, num_qubits, low, high, x=None):
for y in np.linspace(low[0], high[0], 2 ** num_qubits[0]):
x__ = y if x is None else np.append(x, y)
if len(num_qubits) == 1:
# map probabilities from normal to log-normal
# reference:
# https://stats.stackexchange.com/questions/214997/multivariate-log-normal-probabiltiy-density-function-pdf
if np.min(x__) > 0.0:
phi_x_ = np.log(x__)
det_j_phi = 1 / np.prod(x__)
prob = multivariate_normal.pdf(phi_x_, mean=self.mu, cov=self.cov) * det_j_phi
probs.append(prob)
else:
probs.append(0.0)
values.append(x__)
else:
probs, values = self._compute_probabilities(probs,
values,
num_qubits[1:], low[1:], high[1:], x__)
return probs, values
示例5: logpdf
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def logpdf(cls, x: Numeric, mean: Numeric = None, cov: Numeric = 1, df: float = None):
"""
Log of probability density function.
Parameters
----------
x: array like
Quantiles, with the last axis of `x` denoting the components
mean: array like, optional
Mean of the distribution (default zero)
cov: array like, optional
Covariance matrix of the distribution (default 1.0)
df: float, optional
Degrees of freedom for the distribution (default 4.6692)
Returns
-------
pdf: ndarray or scalar
Log of probability density function evaluated at `x`
"""
return np.log(cls.pdf(x, mean, cov, df))
示例6: gaussian
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def gaussian(self, mu, sigma, i_tot):
""" create a 3D gaussian signal normalized to a given intensity
Args:
mu: average value of the gaussian signal (usually set to 0)
sigma: standard deviation
i_tot: sum total of activation (numerical integral over the gaussian returns this value)
"""
x, y, z = np.mgrid[0:self.brain_mask.shape[0], 0:self.brain_mask.shape[1], 0:self.brain_mask.shape[2]]
# Need an (N, 3) array of (x, y) pairs.
xyz = np.column_stack([x.flat, y.flat, z.flat])
covariance = np.diag(sigma**2)
g = multivariate_normal.pdf(xyz, mean=mu, cov=covariance)
# Reshape back to a 3D grid.
g = g.reshape(x.shape).astype(float)
# select only the regions within the brain mask
g = np.multiply(self.brain_mask.get_data(), g)
# adjust total intensity of gaussian
g = np.multiply(i_tot/np.sum(g), g)
return g
示例7: test_batch_exec_2
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def test_batch_exec_2(self):
from scipy.stats import multivariate_normal
def pdf(X, Y):
std = 1
ndim_y = Y.shape[1]
return multivariate_normal.pdf(Y, mean=np.zeros(ndim_y), cov=np.eye(ndim_y)*std**2)
n_queries = 8*10 ** 4
X = np.ones((n_queries, 2)) * 2
Y = np.stack([np.linspace(-3, 3, num=n_queries), np.linspace(-3, 3, num=n_queries)], axis=-1)
p_true = pdf(X, Y)
p_batched = execute_batch_async_pdf(pdf, X, Y, batch_size=10000, n_jobs=8)
self.assertLessEqual(np.mean((p_true - p_batched) ** 2), 0.00001)
示例8: _get_peak_probs
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def _get_peak_probs(self, model):
"""
Compute a matrix giving p(x|r,t), using all x values in a model
object, and each topic's spatial parameters.
Returns
-------
peak_probs : :obj:`numpy.ndarray` of :obj:`numpy.float64`
nPeaks x nTopics x nRegions matrix of probabilities, giving
probability of sampling each peak (x) from all subregions.
"""
peak_probs = np.zeros(
(len(model.data['ptoken_doc_idx']), self.params['n_topics'],
self.params['n_regions']), dtype=float)
for i_topic in range(self.params['n_topics']):
for j_region in range(self.params['n_regions']):
pdf = multivariate_normal.pdf(
model.data['peak_vals'],
mean=self.topics['regions_mu'][i_topic, j_region, 0, :],
cov=self.topics['regions_sigma'][i_topic, j_region, ...])
peak_probs[:, i_topic, j_region] = pdf
return peak_probs
示例9: pdf
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def pdf(self, control_vec):
"""The value of the probability density function (pdf) at a test point
Parameters
----------
control_vec : :class:`numpy.ndarray`
The control vector at the test point
Returns
-------
float
The value of the pdf at :obj:`control_vec`
"""
return multivariate_normal.pdf(control_vec,
mean=self.control_input(),
cov=self.control_noise).reshape(-1, 1)
示例10: test_angle_pdf
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def test_angle_pdf():
model = CartesianToBearingRange(ndim_state=2,
mapping=(0, 1),
noise_covar=np.diag([np.radians(10), 2]))
# Around 0 degrees
measurement = State(StateVector([[Bearing(np.radians(1.))], [10.]]))
x, y = pol2cart(10, np.radians(-1))
state = State(StateVector([[x], [y]]))
reference_probability = model.pdf(measurement, state)
# Check same result around 90 degrees
measurement.state_vector[0, 0] += np.radians(90)
x, y = pol2cart(10, np.radians(89))
state = State(StateVector([[x], [y]]))
assert approx(reference_probability) == model.pdf(measurement, state)
# Check same result around 180 degrees
measurement.state_vector[0, 0] += np.radians(90)
x, y = pol2cart(10, np.radians(179))
state = State(StateVector([[x], [y]]))
assert approx(reference_probability) == model.pdf(measurement, state)
示例11: sample_normal_expectations
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def sample_normal_expectations(self, gaussian_state):
"""Returns the expectation value E(f) and the variance var(f)
for some normal distribution X~N(mu, cov).
Args:
mu (array): means vector
cov (array): covariance matrix
func (function): function acting on the random variables X, P, XP,
returning a second order polynomial
Returns:
tuple: tuple of expectation value and variance.
"""
def _sample(func, correction=0, mu=None, cov=None):
"""wrapped function"""
if mu is None:
mu = gaussian_state[0]
if cov is None:
cov = gaussian_state[1]
X, P = np.mgrid[-7:7:0.01, -7:7:0.01]
grid = np.dstack((X, P))
XP = np.prod(grid, axis=2)
poly = func(X, P, XP)
PDF = multivariate_normal.pdf(grid, mu, cov)
Ex = simps(simps(poly * PDF, P[0]), X.T[0])
ExSq = simps(simps(poly ** 2 * PDF, P[0]), X.T[0])
var = ExSq - Ex ** 2 + correction
return Ex, var
return _sample
示例12: _expectations
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def _expectations(self, point):
responsibilities = [0 for i in range(self.c)]
for k in range(self.c):
probability = multivariate_normal.pdf(point,
mean=self.mus[k],
cov=self.covs[k]) * \
self.priors[k]
responsibilities[k] = probability
responsibilities = [float(i) / sum(responsibilities)
for i in responsibilities]
return responsibilities
示例13: predict
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def predict(self, x, probs=False):
"""
Note: currenly only works on single vector and not matrices
Args:
x (np.ndarray): Training data of shape[1, n_features]
probs (bool): if True, returns probability of each class as well
Returns:
float: Returns predicted class
Raises:
ValueError if model has not been fit
"""
if not self.learned:
raise NameError('Fit model first')
probabilities = [0 for i in range(self.c)]
for k in range(self.c):
probability = multivariate_normal.pdf(x,
mean=self.mus[k],
cov=self.covs[k]) * \
self.priors[k]
probabilities[k] = probability
max_class = np.argmax(probabilities)
class_probs = [float(i)/sum(probabilities) for i in probabilities]
if probs:
return (max_class, class_probs)
return np.argmax(probabilities)
示例14: test_input_shape
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def test_input_shape(self):
mu = np.arange(3)
cov = np.identity(2)
assert_raises(ValueError, multivariate_normal.pdf, (0, 1), mu, cov)
assert_raises(ValueError, multivariate_normal.pdf, (0, 1, 2), mu, cov)
assert_raises(ValueError, multivariate_normal.cdf, (0, 1), mu, cov)
assert_raises(ValueError, multivariate_normal.cdf, (0, 1, 2), mu, cov)
示例15: test_scalar_values
# 需要導入模塊: from scipy.stats import multivariate_normal [as 別名]
# 或者: from scipy.stats.multivariate_normal import pdf [as 別名]
def test_scalar_values(self):
np.random.seed(1234)
# When evaluated on scalar data, the pdf should return a scalar
x, mean, cov = 1.5, 1.7, 2.5
pdf = multivariate_normal.pdf(x, mean, cov)
assert_equal(pdf.ndim, 0)
# When evaluated on a single vector, the pdf should return a scalar
x = np.random.randn(5)
mean = np.random.randn(5)
cov = np.abs(np.random.randn(5)) # Diagonal values for cov. matrix
pdf = multivariate_normal.pdf(x, mean, cov)
assert_equal(pdf.ndim, 0)
# When evaluated on scalar data, the cdf should return a scalar
x, mean, cov = 1.5, 1.7, 2.5
cdf = multivariate_normal.cdf(x, mean, cov)
assert_equal(cdf.ndim, 0)
# When evaluated on a single vector, the cdf should return a scalar
x = np.random.randn(5)
mean = np.random.randn(5)
cov = np.abs(np.random.randn(5)) # Diagonal values for cov. matrix
cdf = multivariate_normal.cdf(x, mean, cov)
assert_equal(cdf.ndim, 0)