本文整理汇总了Python中scipy.linalg.LinAlgError方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.LinAlgError方法的具体用法?Python linalg.LinAlgError怎么用?Python linalg.LinAlgError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.linalg
的用法示例。
在下文中一共展示了linalg.LinAlgError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _covariance_factor
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def _covariance_factor(Sigma):
# Assume it is positive-definite and try Cholesky decomposition.
try:
return Covariance_Cholesky(Sigma)
except la.LinAlgError:
pass
# XXX In the past, we tried LU decomposition if, owing to
# floating-point rounding error, the matrix is merely nonsingular,
# not positive-definite. However, empirically, that seemed to lead
# to bad numerical results. Until we have better numerical analysis
# of the situation, let's try just falling back to least-squares
# pseudoinverse approximation.
# Otherwise, fall back to whatever heuristics scipy can manage.
return Covariance_Loser(Sigma)
示例2: solve
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def solve(self, f, tol=0):
dx = -self.alpha*f
n = len(self.dx)
if n == 0:
return dx
df_f = np.empty(n, dtype=f.dtype)
for k in xrange(n):
df_f[k] = vdot(self.df[k], f)
try:
gamma = solve(self.a, df_f)
except LinAlgError:
# singular; reset the Jacobian approximation
del self.dx[:]
del self.df[:]
return dx
for m in xrange(n):
dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m])
return dx
示例3: log_multivariate_normal_density
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [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 LinAlgError [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: _log_multivariate_normal_density_full
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [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
示例6: optimize
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def optimize(self, optimizer=None, start=None, **kwargs):
self._IN_OPTIMIZATION_ = True
if self.mpi_comm is None:
super(DeepGP, self).optimize(optimizer,start,**kwargs)
elif self.mpi_comm.rank==self.mpi_root:
super(DeepGP, self).optimize(optimizer,start,**kwargs)
self.mpi_comm.Bcast(np.int32(-1),root=self.mpi_root)
elif self.mpi_comm.rank!=self.mpi_root:
x = self.optimizer_array.copy()
flag = np.empty(1,dtype=np.int32)
while True:
self.mpi_comm.Bcast(flag,root=self.mpi_root)
if flag==1:
try:
self.optimizer_array = x
except (LinAlgError, ZeroDivisionError, ValueError):
pass
elif flag==-1:
break
else:
self._IN_OPTIMIZATION_ = False
raise Exception("Unrecognizable flag for synchronization!")
self._IN_OPTIMIZATION_ = False
示例7: _log_multivariate_normal_density_full
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [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
示例8: __init__
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def __init__(self, data):
self._data = np.atleast_2d(data)
self._mean = np.mean(data, axis=0)
self._cov = None
if self.data.shape[0] > 1:
try:
self._cov = np.cov(data.T)
# Try factoring now to see if regularization is needed
la.cho_factor(self._cov)
except la.LinAlgError:
self._cov = oas_cov(data)
self._set_bandwidth()
# store transformation variables for drawing random values
alphas = np.std(data, axis=0)
ms = 1./alphas
m_i, m_j = np.meshgrid(ms, ms)
ms = m_i * m_j
self._draw_cov = ms * self._kernel_cov
self._scale_fac = alphas
示例9: _nystrom_svd
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def _nystrom_svd(self, X, n_components):
"""Compute the top eigensystem of a kernel
operator using Nystrom method
Parameters
----------
X : {float, array}, shape = [n_subsamples, n_features]
Subsample feature matrix.
n_components : int
Number of top eigencomponents to be restored.
Returns
-------
E : {float, array}, shape = [k]
Top eigenvalues.
Lambda : {float, array}, shape = [n_subsamples, k]
Top eigenvectors of a subsample kernel matrix (which can be
directly used to approximate the eigenfunctions of the kernel
operator).
"""
m, _ = X.shape
K = self._kernel(X, X)
W = K / m
try:
E, Lambda = eigh(W, eigvals=(m - n_components, m - 1))
except LinAlgError:
# Use float64 when eigh fails due to precision
W = np.float64(W)
E, Lambda = eigh(W, eigvals=(m - n_components, m - 1))
E, Lambda = np.float32(E), np.float32(Lambda)
# Flip so eigenvalues are in descending order.
E = np.maximum(np.float32(1e-7), np.flipud(E))
Lambda = np.fliplr(Lambda)[:, :n_components] / np.sqrt(
m, dtype="float32"
)
return E, Lambda
示例10: optimize_transformations
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def optimize_transformations(verts0, W, C):
X = form_X_matrix(verts0, W)
try:
Tr = linalg.solve(np.dot(X, X.T), np.dot(C, X.T).T).T
except linalg.LinAlgError:
print("singular matrix in optimize_transformations, using slower pseudo-inverse")
Tr = np.dot(
np.linalg.pinv(np.dot(X, X.T)),
np.dot(C, X.T).T).T
return Tr
#T = np.dot(B, Tr)
#T2 = linalg.solve(np.dot(X, X.T), np.dot(A, X.T).T).T
示例11: update
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def update(self, v):
"""Adds point v"""
self.t += 1
g = self.gamma()
self.mu = (1. - g) * self.mu + g * v
mv = v - self.mu
self.Sigma = ((1. - g) * self.Sigma
+ g * np.dot(mv[:, np.newaxis], mv[np.newaxis, :]))
try:
self.L = cholesky(self.Sigma, lower=True)
except LinAlgError:
self.L = self.L0
示例12: __init__
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def __init__(self, x, scale=None, adaptive=True):
if adaptive:
if scale is None:
scale = 2.38 / np.sqrt(x.shape[1])
cov = np.cov(x.T)
try:
self.L = scale * cholesky(cov, lower=True)
except LinAlgError:
self.L = scale * np.diag(np.sqrt(np.diag(cov)))
print('Warning: could not compute Cholesky decomposition, using diag matrix instead')
else:
if scale is None:
scale = 1.
self.L = scale * np.eye(x.shape[1])
示例13: test_economic_1_col_bad_update
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def test_economic_1_col_bad_update(self):
# When the column to be added lies in the span of Q, the update is
# not meaningful. This is detected, and a LinAlgError is issued.
q = np.eye(5, 3, dtype=self.dtype)
r = np.eye(3, dtype=self.dtype)
u = np.array([1, 0, 0, 0, 0], self.dtype)
assert_raises(linalg.LinAlgError, qr_insert, q, r, u, 0, 'col')
# for column adds to economic matrices there are three cases to test
# eco + pcol --> eco
# eco + pcol --> sqr
# eco + pcol --> fat
示例14: statdist
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def statdist(generator):
"""Compute the stationary distribution of a Markov chain.
Parameters
----------
generator : array_like
Infinitesimal generator matrix of the Markov chain.
Returns
-------
dist : numpy.ndarray
The unnormalized stationary distribution of the Markov chain.
Raises
------
ValueError
If the Markov chain does not have a unique stationary distribution.
"""
generator = np.asarray(generator)
n = generator.shape[0]
with warnings.catch_warnings():
# The LU decomposition raises a warning when the generator matrix is
# singular (which it, by construction, is!).
warnings.filterwarnings("ignore")
lu, piv = spl.lu_factor(generator.T, check_finite=False)
# The last row contains 0's only.
left = lu[:-1,:-1]
right = -lu[:-1,-1]
# Solves system `left * x = right`. Assumes that `left` is
# upper-triangular (ignores lower triangle).
try:
res = spl.solve_triangular(left, right, check_finite=False)
except:
# Ideally we would like to catch `spl.LinAlgError` only, but there seems
# to be a bug in scipy, in the code that raises the LinAlgError (!!).
raise ValueError(
"stationary distribution could not be computed. "
"Perhaps the Markov chain has more than one absorbing class?")
res = np.append(res, 1.0)
return (n / res.sum()) * res
示例15: makeAMatrix
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import LinAlgError [as 别名]
def makeAMatrix(self):
"""
Calculates the "A" matrix, that uses the existing data to find a new
component of the new phase vector.
"""
# Cholsky solve can fail - if so do brute force inversion
try:
cf = linalg.cho_factor(self.cov_mat_zz)
inv_cov_zz = linalg.cho_solve(cf, numpy.identity(self.cov_mat_zz.shape[0]))
except linalg.LinAlgError:
raise linalg.LinAlgError("Could not invert Covariance Matrix to for A and B Matrices. Try with a larger pixel scale")
self.A_mat = self.cov_mat_xz.dot(inv_cov_zz)