本文整理汇总了Python中numpy.linalg.linalg.LinAlgError方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.LinAlgError方法的具体用法?Python linalg.LinAlgError怎么用?Python linalg.LinAlgError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy.linalg.linalg
的用法示例。
在下文中一共展示了linalg.LinAlgError方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _grads
# 需要导入模块: from numpy.linalg import linalg [as 别名]
# 或者: from numpy.linalg.linalg import LinAlgError [as 别名]
def _grads(self, x):
"""
Gets the gradients from the likelihood and the priors.
Failures are handled robustly. The algorithm will try several times to
return the gradients, and will raise the original exception if
the objective cannot be computed.
:param x: the parameters of the model.
:type x: np.array
"""
try:
# self._set_params_transformed(x)
self.optimizer_array = x
self.obj_grads = self._transform_gradients(self.objective_function_gradients())
self._fail_count = 0
except (LinAlgError, ZeroDivisionError, ValueError): #pragma: no cover
if self._fail_count >= self._allowed_failures:
raise
self._fail_count += 1
self.obj_grads = np.clip(self._transform_gradients(self.objective_function_gradients()), -1e100, 1e100)
return self.obj_grads
示例2: _objective
# 需要导入模块: from numpy.linalg import linalg [as 别名]
# 或者: from numpy.linalg.linalg import LinAlgError [as 别名]
def _objective(self, x):
"""
The objective function passed to the optimizer. It combines
the likelihood and the priors.
Failures are handled robustly. The algorithm will try several times to
return the objective, and will raise the original exception if
the objective cannot be computed.
:param x: the parameters of the model.
:parameter type: np.array
"""
try:
self.optimizer_array = x
obj = self.objective_function()
self._fail_count = 0
except (LinAlgError, ZeroDivisionError, ValueError):#pragma: no cover
if self._fail_count >= self._allowed_failures:
raise
self._fail_count += 1
return np.inf
return obj
示例3: dcgain
# 需要导入模块: from numpy.linalg import linalg [as 别名]
# 或者: from numpy.linalg.linalg import LinAlgError [as 别名]
def dcgain(self):
"""Return the zero-frequency gain
The zero-frequency gain of a continuous-time state-space
system is given by:
.. math: G(0) = - C A^{-1} B + D
and of a discrete-time state-space system by:
.. math: G(1) = C (I - A)^{-1} B + D
Returns
-------
gain : ndarray
An array of shape (outputs,inputs); the array will either
be the zero-frequency (or DC) gain, or, if the frequency
response is singular, the array will be filled with np.nan.
"""
try:
if self.isctime():
gain = np.asarray(self.D-self.C.dot(np.linalg.solve(self.A, self.B)))
else:
gain = self.horner(1)
except LinAlgError:
# eigenvalue at DC
gain = np.tile(np.nan, (self.outputs, self.inputs))
return np.squeeze(gain)
# TODO: add discrete time check
示例4: _objective_grads
# 需要导入模块: from numpy.linalg import linalg [as 别名]
# 或者: from numpy.linalg.linalg import LinAlgError [as 别名]
def _objective_grads(self, x):
try:
self.optimizer_array = x
obj_f, self.obj_grads = self.objective_function(), self._transform_gradients(self.objective_function_gradients())
self._fail_count = 0
except (LinAlgError, ZeroDivisionError, ValueError):#pragma: no cover
if self._fail_count >= self._allowed_failures:
raise
self._fail_count += 1
obj_f = np.inf
self.obj_grads = np.clip(self._transform_gradients(self.objective_function_gradients()), -1e10, 1e10)
return obj_f, self.obj_grads
示例5: _omp
# 需要导入模块: from numpy.linalg import linalg [as 别名]
# 或者: from numpy.linalg.linalg import LinAlgError [as 别名]
def _omp(x, D, Gram, alpha, n_nonzero_coefs=None, tol=None):
_, n_atoms = D.shape
# the dict indexes of the atoms this datapoint uses
Dx = np.array([]).astype(int)
z = np.zeros(n_atoms)
# the residual
r = np.copy(x)
i = 0
if n_nonzero_coefs is not None:
tol = 1e-10
def cont_criterion():
not_reached_sparsity = i < n_nonzero_coefs
return (not_reached_sparsity and norm(r) > tol)
else:
cont_criterion = lambda: norm(r) >= tol
while (cont_criterion()):
# find the atom that correlates the
# most with the residual
k = np.argmax(np.abs(alpha))
if k in Dx:
break
Dx = np.append(Dx, k)
# solve the Least Squares problem to find the coefs z
G = Gram[Dx, :][:, Dx]
G = np.atleast_2d(G)
try:
G_inv = inv(G)
except LinAlgError:
print gram_singular_msg
break
z[Dx] = np.dot(G_inv, np.dot(D.T, x)[Dx])
r = x - np.dot(D[:, Dx], z[Dx])
alpha = np.dot(D.T, r)
i += 1
return z
示例6: _somp
# 需要导入模块: from numpy.linalg import linalg [as 别名]
# 或者: from numpy.linalg.linalg import LinAlgError [as 别名]
def _somp(X_g, D, Gram, n_nonzero_coefs=None):
n_atoms = D.shape[1]
n_group_samples = X_g.shape[1]
Z = np.zeros((n_atoms, n_group_samples))
Dx = np.array([])
Dx = Dx.astype(int)
R = X_g
if n_nonzero_coefs is not None:
tol = 1e-20
def cont_criterion():
not_reached_sparsity = i < n_nonzero_coefs
return (not_reached_sparsity and frobenius_squared(R) > tol)
else:
cont_criterion = lambda: frobenius_squared(R) > tol
i = 0
while (cont_criterion()):
A = fast_dot(D.T, R)
j = np.argmax([norm(A[k, :]) for k in range(n_atoms)])
Dx = np.append(Dx, j)
G = Gram[Dx, :][:, Dx]
G = np.atleast_2d(G)
try:
G_inv = inv(G)
except LinAlgError:
print gram_singular_msg
break
Z[Dx, :] = fast_dot(fast_dot(inv(G_inv), D[:, Dx].T), X_g)
R = X_g - fast_dot(D, Z)
i += 1
return Z
示例7: _run_interface
# 需要导入模块: from numpy.linalg import linalg [as 别名]
# 或者: from numpy.linalg.linalg import LinAlgError [as 别名]
def _run_interface(self, runtime):
failures = 0
while True:
try:
runtime = super(RobustACompCor, self)._run_interface(runtime)
break
except LinAlgError:
failures += 1
if failures > 10:
raise
start = (failures - 1) * 10
sleep(randint(start + 4, start + 10))
return runtime
示例8: svd
# 需要导入模块: from numpy.linalg import linalg [as 别名]
# 或者: from numpy.linalg.linalg import LinAlgError [as 别名]
def svd(a,
full_matrices=True,
compute_uv=True,
overwrite_a=False,
check_finite=True,
lapack_driver='gesdd',
warn=True):
"""Wrapper around :func:`scipy.linalg.svd` with `gesvd` backup plan.
Tries to avoid raising an LinAlgError by using using the lapack_driver `gesvd`,
if `gesdd` failed.
Parameters not described below are as in :func:`scipy.linalg.svd`
Parameters
----------
overwrite_a : bool
Ignored (i.e. set to ``False``) if ``lapack_driver='gesdd'``.
Otherwise described in :func:`scipy.linalg.svd`.
lapack_driver : {'gesdd', 'gesvd'}, optional
Whether to use the more efficient divide-and-conquer approach (``'gesdd'``)
or general rectangular approach (``'gesvd'``) to compute the SVD.
MATLAB and Octave use the ``'gesvd'`` approach.
Default is ``'gesdd'``.
If ``'gesdd'`` fails, ``'gesvd'`` is used as backup.
warn : bool
Whether to create a warning when the SVD failed.
Returns
-------
U, S, Vh : ndarray
As described in doc-string of :func:`scipy.linalg.svd`.
"""
if lapack_driver == 'gesdd':
try:
return scipy.linalg.svd(a, full_matrices, compute_uv, False, check_finite)
except np.linalg.LinAlgError:
# 'gesdd' failed to converge, so we continue with the backup plan
if warn:
warnings.warn("SVD with lapack_driver 'gesdd' failed. Use backup 'gesvd'",
stacklevel=2)
pass
if lapack_driver not in ['gesdd', 'gesvd']:
raise ValueError("invalid `lapack_driver`: " + str(lapack_driver))
# 'gesvd' lapack driver
if not _old_scipy:
# use LAPACK wrapper included in scipy version >= 0.18.0
return scipy.linalg.svd(a, full_matrices, compute_uv, overwrite_a, check_finite, 'gesvd')
else: # for backwards compatibility
_load_lapack(warn=warn)
return svd_gesvd(a, full_matrices, compute_uv, check_finite)
示例9: _group_omp
# 需要导入模块: from numpy.linalg import linalg [as 别名]
# 或者: from numpy.linalg.linalg import LinAlgError [as 别名]
def _group_omp(x, D, Gram, alpha, groups=None, n_groups=None, tol=None):
# TODO: also use a tolerance parameter
_, n_atoms = D.shape
# the dict indexes of the groups
# this datapoint uses
Gx = np.array([]).astype(int)
z = np.zeros(n_atoms)
# the residual
r = np.copy(x)
i = 0
if n_groups is not None:
tol = 1e-10
def cont_criterion():
not_reached_sparsity = i < n_groups
return (not_reached_sparsity and norm(r) > tol)
else:
cont_criterion = lambda: norm(r) > tol
while (cont_criterion()):
# find the group of atoms that correlates
# the most with the residual
if i == 0:
group_scores = [norm(alpha[group]) for group in groups]
else:
group_scores = [norm(np.dot(D[:, group].T, r)) for group in groups]
g = np.argmax(group_scores)
if g in Gx or norm(r) < 1e-10:
# group already selected
break
Gx = np.append(Gx, g)
# solve the Least Squares problem
# to find the coefs z
idx = np.array([k for g_idx in Gx for k in groups[g_idx]])
G = Gram[idx, :][:, idx]
try:
G_inv = inv(G)
except LinAlgError:
print gram_singular_msg
break
z[idx] = np.dot(np.dot(G_inv, D[:, idx].T), x)
approx = np.dot(D[:, idx], z[idx])
r = x - approx
i += 1
return z
示例10: perform
# 需要导入模块: from numpy.linalg import linalg [as 别名]
# 或者: from numpy.linalg.linalg import LinAlgError [as 别名]
def perform(self, node, inputs, outputs):
context = inputs[0][0].context
# Input matrix.
A = inputs[0]
l, n = A.shape
if l != n:
raise ValueError('A must be a square matrix')
lda = max(1, n)
# cusolver operates on F ordered matrices
if not self.inplace:
LU = pygpu.array(A, copy=True, order='F')
else:
LU = A.T if A.flags['C_CONTIGUOUS'] else A
LU_ptr = LU.gpudata
with context:
workspace_size = cusolver.cusolverDnSgetrf_bufferSize(
context.cusolver_handle, n, n, LU_ptr, lda)
workspace = pygpu.zeros(workspace_size, dtype='float32',
context=context)
pivots = pygpu.zeros(n, dtype='int32', context=context)
dev_info = pygpu.zeros((1,), dtype='int32', context=context)
workspace_ptr = workspace.gpudata
pivots_ptr = pivots.gpudata
dev_info_ptr = dev_info.gpudata
cusolver.cusolverDnSgetrf(
context.cusolver_handle, n, n, LU_ptr, lda, workspace_ptr,
pivots_ptr, dev_info_ptr)
if self.check_output:
val_dev_info = np.asarray(dev_info)[0]
if val_dev_info > 0:
raise LinAlgError('LU decomposition failed')
outputs[1][0] = pivots
outputs[0][0] = LU