本文整理汇总了Python中scipy.linalg.solve_triangular方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.solve_triangular方法的具体用法?Python linalg.solve_triangular怎么用?Python linalg.solve_triangular使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.linalg
的用法示例。
在下文中一共展示了linalg.solve_triangular方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: linear_hotelling_test
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def linear_hotelling_test(X, Y, reg=0):
n, p = X.shape
Z = X - Y
Z_bar = Z.mean(axis=0)
Z -= Z_bar
S = Z.T.dot(Z)
S /= (n - 1)
if reg:
S[::p + 1] += reg
# z' inv(S) z = z' inv(L L') z = z' inv(L)' inv(L) z = ||inv(L) z||^2
L = linalg.cholesky(S, lower=True, overwrite_a=True)
Linv_Z_bar = linalg.solve_triangular(L, Z_bar, lower=True, overwrite_b=True)
stat = n * Linv_Z_bar.dot(Linv_Z_bar)
p_val = stats.chi2.sf(stat, p)
return p_val, stat
示例2: _wrap_func
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def _wrap_func(func, xdata, ydata, transform):
if transform is None:
def func_wrapped(params):
return func(xdata, *params) - ydata
elif transform.ndim == 1:
def func_wrapped(params):
return transform * (func(xdata, *params) - ydata)
else:
# Chisq = (y - yd)^T C^{-1} (y-yd)
# transform = L such that C = L L^T
# C^{-1} = L^{-T} L^{-1}
# Chisq = (y - yd)^T L^{-T} L^{-1} (y-yd)
# Define (y-yd)' = L^{-1} (y-yd)
# by solving
# L (y-yd)' = (y-yd)
# and minimize (y-yd)'^T (y-yd)'
def func_wrapped(params):
return solve_triangular(transform, func(xdata, *params) - ydata, lower=True)
return func_wrapped
示例3: log_multivariate_normal_density
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def log_multivariate_normal_density(X, means, covars, min_covar=1.e-7):
"""Log probability for full covariance matrices. """
if hasattr(linalg, 'solve_triangular'):
# only in scipy since 0.9
solve_triangular = linalg.solve_triangular
else:
# slower, but works
solve_triangular = linalg.solve
n_samples, n_dim = X.shape
nmix = len(means)
log_prob = np.empty((n_samples, nmix))
for c, (mu, cv) in enumerate(zip(means, covars)):
try:
cv_chol = linalg.cholesky(cv, lower=True)
except linalg.LinAlgError:
# The model is most probabily stuck in a component with too
# few observations, we need to reinitialize this components
cv_chol = linalg.cholesky(cv + min_covar * np.eye(n_dim),
lower=True)
cv_log_det = 2 * np.sum(np.log(np.diagonal(cv_chol)))
cv_sol = solve_triangular(cv_chol, (X - mu).T, lower=True).T
log_prob[:, c] = - .5 * (np.sum(cv_sol ** 2, axis=1) + \
n_dim * np.log(2 * np.pi) + cv_log_det)
return log_prob
示例4: _log_multivariate_normal_density_full
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def _log_multivariate_normal_density_full(X, means, covars, min_covar=1.e-7):
"""Log probability for full covariance matrices.
"""
n_samples, n_dim = X.shape
nmix = len(means)
log_prob = np.empty((n_samples, nmix))
for c, (mu, cv) in enumerate(zip(means, covars)):
try:
cv_chol = linalg.cholesky(cv, lower=True)
except linalg.LinAlgError:
# The model is most probably stuck in a component with too
# few observations, we need to reinitialize this components
cv_chol = linalg.cholesky(cv + min_covar * np.eye(n_dim),
lower=True)
cv_log_det = 2 * np.sum(np.log(np.diagonal(cv_chol)))
cv_sol = linalg.solve_triangular(cv_chol, (X - mu).T, lower=True).T
log_prob[:, c] = - .5 * (np.sum(cv_sol ** 2, axis=1) +
n_dim * np.log(2 * np.pi) + cv_log_det)
return log_prob
示例5: ols_cholesky
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def ols_cholesky(A, b):
"""
Ordinary Least-Squares Regression Coefficients
Estimation.
If (A.T @ A) @ x = A.T @ b and A is full rank
then there exists an upper triangular matrix
R such that:
(R.T @ R) @ x = A.T @ b
R.T @ w = A.T @ b
R @ x = w
Find R using Cholesky decomposition.
"""
R = cholesky(A.T @ A)
w = solve_triangular(R, A.T @ b, trans='T')
return solve_triangular(R, w)
示例6: _log_multivariate_normal_density_full
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def _log_multivariate_normal_density_full(X, means, covars, min_covar=1.e-7):
'''Log probability for full covariance matrices.
'''
n_samples, n_dimensions = X.shape
nmix = len(means)
log_prob = np.empty((n_samples, nmix))
for c, (mu, cv) in enumerate(zip(means, covars)):
try:
cv_chol = linalg.cholesky(cv, lower=True)
except linalg.LinAlgError:
# The model is most probably stuck in a component with too
# few observations, we need to reinitialize this components
cv_chol = linalg.cholesky(cv + min_covar * np.eye(n_dimensions),
lower=True)
cv_log_det = 2 * np.sum(np.log(np.diagonal(cv_chol)))
cv_sol = linalg.solve_triangular(cv_chol, (X - mu).T, lower=True).T
log_prob[:, c] = - .5 * (np.sum(cv_sol ** 2, axis=1) +
n_dimensions * np.log(2 * np.pi) + cv_log_det)
return log_prob
示例7: pred_constraint_voilation
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def pred_constraint_voilation(self, cand, comp, vals):
# The primary covariances for prediction.
comp_cov = self.cov(self.constraint_amp2, self.constraint_ls, comp)
cand_cross = self.cov(self.constraint_amp2, self.constraint_ls, comp,
cand)
# Compute the required Cholesky.
obsv_cov = comp_cov + self.constraint_noise*np.eye(comp.shape[0])
obsv_chol = spla.cholesky(obsv_cov, lower=True)
cov_grad_func = getattr(gp, 'grad_' + self.cov_func.__name__)
cand_cross_grad = cov_grad_func(self.constraint_ls, comp, cand)
# Predictive things.
# Solve the linear systems.
alpha = spla.cho_solve((obsv_chol, True), self.ff)
beta = spla.solve_triangular(obsv_chol, cand_cross, lower=True)
# Predict the marginal means and variances at candidates.
func_m = np.dot(cand_cross.T, alpha)# + self.constraint_mean
func_m = sps.norm.cdf(func_m*self.constraint_gain)
return func_m
# Compute EI over hyperparameter samples
示例8: log_prior
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def log_prior(self):
# Normal N(mu | mu_0, Sigma / kappa_0)
from scipy.linalg import solve_triangular
sigma = np.linalg.inv(self.J_0)
mu = sigma.dot(self.h_0)
S_chol = np.linalg.cholesky(sigma)
# Stack log pi and W
X = np.vstack((self.logpi, self.W)).T
lp = 0
for d in range(self.D_out):
x = solve_triangular(S_chol, X[d] - mu, lower=True)
lp += -1. / 2. * np.dot(x, x) \
- self.D_in / 2 * np.log(2 * np.pi) \
- np.log(S_chol.diagonal()).sum()
return lp
### HMC
示例9: _log_multivariate_normal_density_full
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def _log_multivariate_normal_density_full(X, means, covars, min_covar=1.e-7):
"""Log probability for full covariance matrices."""
n_samples, n_dim = X.shape
nmix = len(means)
log_prob = np.empty((n_samples, nmix))
for c, (mu, cv) in enumerate(zip(means, covars)):
try:
cv_chol = linalg.cholesky(cv, lower=True)
except linalg.LinAlgError:
# The model is most probably stuck in a component with too
# few observations, we need to reinitialize this components
try:
cv_chol = linalg.cholesky(cv + min_covar * np.eye(n_dim),
lower=True)
except linalg.LinAlgError:
raise ValueError("'covars' must be symmetric, "
"positive-definite")
cv_log_det = 2 * np.sum(np.log(np.diagonal(cv_chol)))
cv_sol = linalg.solve_triangular(cv_chol, (X - mu).T, lower=True).T
log_prob[:, c] = - .5 * (np.sum(cv_sol ** 2, axis=1) +
n_dim * np.log(2 * np.pi) + cv_log_det)
return log_prob
示例10: standardized_forecasts_error
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def standardized_forecasts_error(self):
"""
Standardized forecast errors
"""
if self._standardized_forecasts_error is None:
from scipy import linalg
self._standardized_forecasts_error = np.zeros(
self.forecasts_error.shape, dtype=self.dtype)
for t in range(self.forecasts_error_cov.shape[2]):
if self.nmissing[t] > 0:
self._standardized_forecasts_error[:, t] = np.nan
if self.nmissing[t] < self.k_endog:
mask = ~self.missing[:, t].astype(bool)
F = self.forecasts_error_cov[np.ix_(mask, mask, [t])]
upper, _ = linalg.cho_factor(F[:, :, 0])
self._standardized_forecasts_error[mask, t] = (
linalg.solve_triangular(
upper, self.forecasts_error[mask, t]
)
)
return self._standardized_forecasts_error
示例11: _kalman_correct
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def _kalman_correct(x, P, z, H, R, gain_factor, gain_curve):
PHT = np.dot(P, H.T)
S = np.dot(H, PHT) + R
e = z - H.dot(x)
L = cholesky(S, lower=True)
inn = solve_triangular(L, e, lower=True)
if gain_curve is not None:
q = (np.dot(inn, inn) / inn.shape[0]) ** 0.5
f = gain_curve(q)
if f == 0:
return inn
L *= (q / f) ** 0.5
K = cho_solve((L, True), PHT.T, overwrite_b=True).T
if gain_factor is not None:
K *= gain_factor[:, None]
U = -K.dot(H)
U[np.diag_indices_from(U)] += 1
x += K.dot(z - H.dot(x))
P[:] = U.dot(P).dot(U.T) + K.dot(R).dot(K.T)
return inn
示例12: _wrap_jac
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def _wrap_jac(jac, xdata, transform):
if transform is None:
def jac_wrapped(params):
return jac(xdata, *params)
elif transform.ndim == 1:
def jac_wrapped(params):
return transform[:, np.newaxis] * np.asarray(jac(xdata, *params))
else:
def jac_wrapped(params):
return solve_triangular(transform, np.asarray(jac(xdata, *params)), lower=True)
return jac_wrapped
示例13: ols_qr
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def ols_qr(A, b):
"""
Ordinary Least-Squares Regression
Coefficients Estimation.
This is the QR Factorization solution
to OLS; Ax = b, A = QR, QRx = b,
therefore Rx = Q.T * b
"""
Q, R = qr(A, mode='economic')
return solve_triangular(R, Q.T @ b)
示例14: predict_local_energy_and_var
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def predict_local_energy_and_var(self, x_t: AtomicEnvironment):
"""Predict the local energy of a local environment and its
uncertainty.
Args:
x_t (AtomicEnvironment): Input local environment.
Return:
(float, float): Mean and predictive variance predicted by the GP.
"""
if self.parallel and not self.per_atom_par:
n_cpus = self.n_cpus
else:
n_cpus = 1
_global_training_data[self.name] = self.training_data
_global_training_labels[self.name] = self.training_labels_np
# get kernel vector
k_v = en_kern_vec(self.name,
self.energy_force_kernel,
x_t, self.hyps,
cutoffs=self.cutoffs,
hyps_mask=self.hyps_mask,
n_cpus=n_cpus,
n_sample=self.n_sample)
# get predictive mean
pred_mean = np.matmul(k_v, self.alpha)
# get predictive variance
v_vec = solve_triangular(self.l_mat, k_v, lower=True)
args = from_mask_to_args(self.hyps, self.hyps_mask, self.cutoffs)
self_kern = self.energy_kernel(x_t, x_t, *args)
pred_var = self_kern - np.matmul(v_vec, v_vec)
return pred_mean, pred_var
示例15: step
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import solve_triangular [as 别名]
def step(self, x):
z = stats.norm.rvs(size=x.shape)
y = self.mu + np.dot(z, self.L.T)
zx = solve_triangular(self.L, np.transpose(x - self.mu),
lower=True)
delta_lp = (0.5 * np.sum(z * z, axis=1)
- 0.5 * np.sum(zx * zx, axis=0))
return y, delta_lp