本文整理汇总了Python中numpy.linalg.LinAlgError方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.LinAlgError方法的具体用法?Python linalg.LinAlgError怎么用?Python linalg.LinAlgError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy.linalg
的用法示例。
在下文中一共展示了linalg.LinAlgError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: lsim
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def lsim(self, u, t, interp=0, returnall=False, X0=None, hmax=None):
"""Find the response of the TransferFunction to the input u
with time vector t. Uses signal.lsim.
return y the response of the system."""
try:
out = signal.lsim(self, u, t, interp=interp, X0=X0)
except LinAlgError:
#if the system has a pure integrator, lsim won't work.
#Call lsim2.
out = self.lsim2(u, t, X0=X0, returnall=True, hmax=hmax)
#override returnall because it is handled below
if returnall:#most users will just want the system output y,
#but some will need the (t, y, x) tuple that
#signal.lsim returns
return out
else:
return out[1]
## def lsim2(self, u, t, returnall=False, X0=None):
## #tempsys=signal.lti(self.num,self.den)
## if returnall:
## return signal.lsim2(self, u, t, X0=X0)
## else:
## return signal.lsim2(self, u, t, X0=X0)[1]
示例2: __call__
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def __call__(self, a):
a = astensor(a)
if a.ndim != 2:
raise LinAlgError('{0}-dimensional tensor given. '
'Tensor must be two-dimensional'.format(a.ndim))
tiny_q, tiny_r = np.linalg.qr(np.ones((1, 1), dtype=a.dtype))
x, y = a.shape
q_shape, r_shape = (a.shape, (y, y)) if x > y else ((x, x), a.shape)
q, r = self.new_tensors([a],
kws=[{'side': 'q', 'dtype': tiny_q.dtype,
'shape': q_shape, 'order': TensorOrder.C_ORDER},
{'side': 'r', 'dtype': tiny_r.dtype,
'shape': r_shape, 'order': TensorOrder.C_ORDER}])
return ExecutableTuple([q, r])
示例3: execute
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def execute(cls, ctx, op):
(a, b), device_id, xp = as_same_device(
[ctx[c.key] for c in op.inputs], device=op.device, ret_extra=True)
chunk = op.outputs[0]
with device(device_id):
if xp is np:
import scipy.linalg
try:
ctx[chunk.key] = scipy.linalg.solve_triangular(a, b, lower=op.lower)
except np.linalg.LinAlgError:
if op.strict is not False:
raise
ctx[chunk.key] = np.linalg.lstsq(a, b, rcond=-1)[0]
elif xp is cp:
import cupyx
ctx[chunk.key] = cupyx.scipy.linalg.solve_triangular(a, b, lower=op.lower)
else:
ctx[chunk.key] = xp.solve_triangular(a, b, lower=op.lower, sparse=op.sparse)
示例4: __call__
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def __call__(self, a):
a = astensor(a)
if a.ndim != 2:
raise LinAlgError('{0}-dimensional tensor given. '
'Tensor must be two-dimensional'.format(a.ndim))
tiny_U, tiny_s, tiny_V = np.linalg.svd(np.ones((1, 1), dtype=a.dtype))
# if a's shape is (6, 18), U's shape is (6, 6), s's shape is (6,), V's shape is (6, 18)
# if a's shape is (18, 6), U's shape is (18, 6), s's shape is (6,), V's shape is (6, 6)
U_shape, s_shape, V_shape = calc_svd_shapes(a)
U, s, V = self.new_tensors([a],
order=TensorOrder.C_ORDER,
kws=[
{'side': 'U', 'dtype': tiny_U.dtype, 'shape': U_shape},
{'side': 's', 'dtype': tiny_s.dtype, 'shape': s_shape},
{'side': 'V', 'dtype': tiny_V.dtype, 'shape': V_shape}
])
return ExecutableTuple([U, s, V])
示例5: get_nadir_point
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def get_nadir_point(extreme_points, ideal_point, worst_point, worst_of_front, worst_of_population):
""" Calculate the axis intersects for a set of individuals and its extremes (construct hyperplane). """
try:
# find the intercepts using gaussian elimination
M = extreme_points - ideal_point
b = np.ones(extreme_points.shape[1])
plane = np.linalg.solve(M, b)
intercepts = 1 / plane
nadir_point = ideal_point + intercepts
if not np.allclose(np.dot(M, plane), b) or np.any(intercepts <= 1e-6) or np.any(nadir_point > worst_point):
raise LinAlgError()
except LinAlgError:
nadir_point = worst_of_front
b = nadir_point - ideal_point <= 1e-6
nadir_point[b] = worst_of_population[b]
return nadir_point
示例6: _safe_arma_fit
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def _safe_arma_fit(y, order, model_kw, trend, fit_kw, start_params=None):
try:
return ARMA(y, order=order, **model_kw).fit(disp=0, trend=trend,
start_params=start_params,
**fit_kw)
except LinAlgError:
# SVD convergence failure on badly misspecified models
return
except ValueError as error:
if start_params is not None: # don't recurse again
# user supplied start_params only get one chance
return
# try a little harder, should be handled in fit really
elif ('initial' not in error.args[0] or 'initial' in str(error)):
start_params = [.1] * sum(order)
if trend == 'c':
start_params = [.1] + start_params
return _safe_arma_fit(y, order, model_kw, trend, fit_kw,
start_params)
else:
return
except: # no idea what happened
return
示例7: test_State_algebra_truediv_rtruediv
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def test_State_algebra_truediv_rtruediv():
G = State(1, 2, 3, 4)
F = G/0.5
assert_equal(F.b, np.array([[4.]]))
assert_equal(F.d, np.array([[8.]]))
G.d = 0.
with assert_raises(LinAlgError):
G/G
with assert_raises(ValueError):
G/3j
G.d = 4
# nonminimal but acceptable
H = G / G
ha, hb, hc, hd = H.matrices
assert_array_almost_equal(ha, [[1, -1.5], [0, -0.5]])
assert_array_almost_equal(hb, [[0.5], [0.5]])
assert_array_almost_equal(hc, [[3, -3]])
assert_array_almost_equal(hd, [[1]])
G = State(np.eye(3)*0.5)
assert_array_almost_equal((1 / G).to_array(), np.eye(3)*2)
示例8: fast_optimize
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def fast_optimize(endog, exog, n_obs=0, n_vars=0, max_iter=10000, tolerance=1e-10):
"""
A convenience function for the Newton-Raphson method to evaluate a logistic model.
:param endog: Nx1 vector of endogenous predictions
:param exog: NxK vector of exogenous predictors
:param n_obs: Number of observations N
:param n_vars: Number of exogenous predictors K
:param max_iter: Maximum number of iterations
:param tolerance: Margin of error for convergence
:return: The error-minimizing parameters for the model.
"""
iterations = 0
oldparams = np.inf
newparams = np.repeat(0, n_vars)
while iterations < max_iter and np.any(np.abs(newparams - oldparams) > tolerance):
oldparams = newparams
try:
H = logit_hessian(exog, oldparams, n_obs)
newparams = oldparams - dot(
inv(H), logit_score(endog, exog, oldparams, n_obs)
)
except LinAlgError:
raise LinAlgError
iterations += 1
return newparams
示例9: get_nadir_point
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def get_nadir_point(extreme_points, ideal_point, worst_point, worst_of_front, worst_of_population):
try:
# find the intercepts using gaussian elimination
M = extreme_points - ideal_point
b = np.ones(extreme_points.shape[1])
plane = np.linalg.solve(M, b)
warnings.simplefilter("ignore")
intercepts = 1 / plane
nadir_point = ideal_point + intercepts
# check if the hyperplane makes sense
if not np.allclose(np.dot(M, plane), b) or np.any(intercepts <= 1e-6):
raise LinAlgError()
# if the nadir point should be larger than any value discovered so far set it to that value
# NOTE: different to the proposed version in the paper
b = nadir_point > worst_point
nadir_point[b] = worst_point[b]
except LinAlgError:
# fall back to worst of front otherwise
nadir_point = worst_of_front
# if the range is too small set it to worst of population
b = nadir_point - ideal_point <= 1e-6
nadir_point[b] = worst_of_population[b]
return nadir_point
示例10: test_0_size
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def test_0_size(self):
class ArraySubclass(np.ndarray):
pass
# Test system of 0x0 matrices
a = np.arange(8).reshape(2, 2, 2)
b = np.arange(6).reshape(1, 2, 3).view(ArraySubclass)
expected = linalg.solve(a, b)[:, 0:0, :]
result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, :])
assert_array_equal(result, expected)
assert_(isinstance(result, ArraySubclass))
# Test errors for non-square and only b's dimension being 0
assert_raises(linalg.LinAlgError, linalg.solve, a[:, 0:0, 0:1], b)
assert_raises(ValueError, linalg.solve, a, b[:, 0:0, :])
# Test broadcasting error
b = np.arange(6).reshape(1, 3, 2) # broadcasting error
assert_raises(ValueError, linalg.solve, a, b)
assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
# Test zero "single equations" with 0x0 matrices.
b = np.arange(2).reshape(1, 2).view(ArraySubclass)
expected = linalg.solve(a, b)[:, 0:0]
result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0])
assert_array_equal(result, expected)
assert_(isinstance(result, ArraySubclass))
b = np.arange(3).reshape(1, 3)
assert_raises(ValueError, linalg.solve, a, b)
assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
assert_raises(ValueError, linalg.solve, a[:, 0:0, 0:0], b)
示例11: do
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def do(self, a, b, tags):
c = asarray(a) # a might be a matrix
if 'size-0' in tags:
assert_raises(LinAlgError, linalg.cond, c)
return
# +-2 norms
s = linalg.svd(c, compute_uv=False)
assert_almost_equal(
linalg.cond(a), s[..., 0] / s[..., -1],
single_decimal=5, double_decimal=11)
assert_almost_equal(
linalg.cond(a, 2), s[..., 0] / s[..., -1],
single_decimal=5, double_decimal=11)
assert_almost_equal(
linalg.cond(a, -2), s[..., -1] / s[..., 0],
single_decimal=5, double_decimal=11)
# Other norms
cinv = np.linalg.inv(c)
assert_almost_equal(
linalg.cond(a, 1),
abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1),
single_decimal=5, double_decimal=11)
assert_almost_equal(
linalg.cond(a, -1),
abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1),
single_decimal=5, double_decimal=11)
assert_almost_equal(
linalg.cond(a, np.inf),
abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1),
single_decimal=5, double_decimal=11)
assert_almost_equal(
linalg.cond(a, -np.inf),
abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1),
single_decimal=5, double_decimal=11)
assert_almost_equal(
linalg.cond(a, 'fro'),
np.sqrt((abs(c)**2).sum(-1).sum(-1)
* (abs(cinv)**2).sum(-1).sum(-1)),
single_decimal=5, double_decimal=11)
示例12: test_incompatible_dims
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def test_incompatible_dims(self):
# use modified version of docstring example
x = np.array([0, 1, 2, 3])
y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
A = np.vstack([x, np.ones(len(x))]).T
with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
linalg.lstsq(A, y, rcond=None)
示例13: test_exceptions_non_square
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def test_exceptions_non_square(self, dt):
assert_raises(LinAlgError, matrix_power, np.array([1], dt), 1)
assert_raises(LinAlgError, matrix_power, np.array([[1], [2]], dt), 1)
assert_raises(LinAlgError, matrix_power, np.ones((4, 3, 2), dt), 1)
示例14: test_exceptions_not_invertible
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def test_exceptions_not_invertible(self, dt):
if dt in self.dtnoinv:
return
mat = self.noninv.astype(dt)
assert_raises(LinAlgError, matrix_power, mat, -1)
示例15: test_non_square_handling
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import LinAlgError [as 别名]
def test_non_square_handling(self, arr, ind):
with assert_raises(LinAlgError):
linalg.tensorinv(arr, ind=ind)