Python numpy.linalg.LinAlgError() Examples
The following are 30
code examples of numpy.linalg.LinAlgError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy.linalg
, or try the search function
.
Example #1
Source File: nsgaiii.py From jMetalPy with MIT License | 7 votes |
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
Example #2
Source File: controls.py From python-control with BSD 3-Clause "New" or "Revised" License | 6 votes |
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]
Example #3
Source File: test_classes.py From harold with MIT License | 6 votes |
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)
Example #4
Source File: utils.py From pyprocessmacro with MIT License | 6 votes |
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
Example #5
Source File: svd.py From mars with Apache License 2.0 | 6 votes |
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])
Example #6
Source File: solve_triangular.py From mars with Apache License 2.0 | 6 votes |
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)
Example #7
Source File: stattools.py From vnpy_crypto with MIT License | 6 votes |
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
Example #8
Source File: qr.py From mars with Apache License 2.0 | 6 votes |
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])
Example #9
Source File: util.py From cupy with MIT License | 5 votes |
def _assert_nd_squareness(*arrays): for a in arrays: if max(a.shape[-2:]) != min(a.shape[-2:]): raise linalg.LinAlgError( 'Last 2 dimensions of the array must be square')
Example #10
Source File: util.py From cupy with MIT License | 5 votes |
def _assert_rank2(*arrays): for a in arrays: if a.ndim != 2: raise linalg.LinAlgError( '{}-dimensional array given. Array must be ' 'two-dimensional'.format(a.ndim))
Example #11
Source File: test_linalg.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
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)
Example #12
Source File: test_linalg.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
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)
Example #13
Source File: test_linalg.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
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)
Example #14
Source File: test_linalg.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
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)
Example #15
Source File: test_linalg.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def test_non_square_handling(self, arr, ind): with assert_raises(LinAlgError): linalg.tensorinv(arr, ind=ind)
Example #16
Source File: test_linalg.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
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)
Example #17
Source File: test_linalg.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def do(self, a, b, tags): if 'size-0' in tags: assert_raises(LinAlgError, linalg.svd, a, 0) return u, s, vt = linalg.svd(a, 0) assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[..., None, :], np.asarray(vt)), rtol=get_rtol(u.dtype)) assert_(consistent_subclass(u, a)) assert_(consistent_subclass(vt, a))
Example #18
Source File: test_linalg.py From GraphicDesignPatternByPython with MIT License | 5 votes |
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)
Example #19
Source File: kerascallback.py From delve with MIT License | 5 votes |
def record_saturation(layers: str, obj, epoch: int, logs: dict, write_summary: bool = True): """Records saturation for layers into logs and writes summaries.""" for layer in layers: layer_history = obj.preactivation_states[layer] if len(layer_history) < 2: # ? continue history = np.stack( layer_history)[:, 0, :] # get first representation of each batch history_T = history.T try: cov = np.cov(history_T) except LinAlgError: continue eig_vals, eig_vecs = np.linalg.eigh(cov) # Make a list of (eigenvalue, eigenvector) tuples eig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:, i]) for i in range(len(eig_vals))] # Sort the (eigenvalue, eigenvector) tuples from high to low eig_pairs = sorted(eig_pairs, key=lambda x: x[0], reverse=True) eig_vals, eig_vecs = zip(*eig_pairs) tot = sum(eig_vals) # Get explained variance var_exp = [(i / tot) for i in eig_vals] # Get Simpson-diversity-index-based saturation weighted_sum = sum([x**2 for x in var_exp]) # logs[layer] = weighted_sum if write_summary: tf.summary.scalar(layer, weighted_sum, collections=['preactivation_state']) return logs
Example #20
Source File: _array_validators.py From harold with MIT License | 5 votes |
def _assert_2d(*arrays): for a in arrays: if a.ndim != 2: raise LinAlgError('{}-dimensional array given. Array must be ' 'two-dimensional'.format(a.ndim))
Example #21
Source File: test_classes.py From harold with MIT License | 5 votes |
def test_Transfer_algebra_truediv_rtruediv(): G = Transfer(1, [1, 2]) F = G/0.5 assert_equal(F.num, np.array([[2.]])) assert_equal(F.den, np.array([[1., 2.]])) # invert a nonproper system with assert_raises(ValueError): G/G # invert a singular system with assert_raises(LinAlgError): 1 / (np.ones((2, 2))*(1+G)) with assert_raises(ValueError): G/3j # invert an invertible system J = 1 / (np.eye(2) * G + np.array([[1, 2], [3, 4]])) nn, dd = J.polynomials nnact = np.array([[x[0].tolist() for x in y] for y in nn]) ddact = np.array([[x[0].tolist() for x in y] for y in dd]) nndes = np.array([[[-2., -8.5, -9.], [1., 4., 4.]], [[1.5, 6., 6.], [-0.5, -2.5, -3.]]]) dddes = np.array([[[1., 1.5, -1.5], [1., 1.5, -1.5]], [[1., 1.5, -1.5], [1., 1.5, -1.5]]]) assert_array_almost_equal(nnact, nndes) assert_array_almost_equal(ddact, dddes) G = Transfer(np.eye(3)*0.5) assert_array_almost_equal((1 / G).to_array(), np.eye(3)*2)
Example #22
Source File: test_array_validators.py From harold with MIT License | 5 votes |
def test_assert_2d(): a, b, c = np.array([[1, 2, 3]]), np.eye(2), np.array([[[1, 2], [3, 5]]]) assert_raises(LinAlgError, _assert_2d, a, b, c)
Example #23
Source File: test_array_validators.py From harold with MIT License | 5 votes |
def test_assert_square(): a, b, c = np.array([[1, 2, 3]]), np.eye(2), np.array([[[1, 2], [3, 5]]]) assert_raises(LinAlgError, _assert_square, a, b, c)
Example #24
Source File: test_linalg.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
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)
Example #25
Source File: _array_validators.py From harold with MIT License | 5 votes |
def _assert_finite(*arrays): for a in arrays: if not np.isfinite(a).all(): raise LinAlgError("Array must not contain infs or NaNs")
Example #26
Source File: test_linalg.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
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)
Example #27
Source File: test_linalg.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
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)
Example #28
Source File: test_linalg.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
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)
Example #29
Source File: _array_validators.py From harold with MIT License | 5 votes |
def _assert_square(*arrays): for a in arrays: m, n = a.shape[-2:] if m != n: raise LinAlgError('Last 2 dimensions of the array must be square' '. Found an array with shape: {}x{}'.format(m, n) )
Example #30
Source File: test_linalg.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def test_non_square_handling(self, arr, ind): with assert_raises(LinAlgError): linalg.tensorinv(arr, ind=ind)