當前位置: 首頁>>代碼示例>>Python>>正文


Python linalg.LinAlgError方法代碼示例

本文整理匯總了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 
開發者ID:sods,項目名稱:paramz,代碼行數:24,代碼來源:model.py

示例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 
開發者ID:sods,項目名稱:paramz,代碼行數:24,代碼來源:model.py

示例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 
開發者ID:python-control,項目名稱:python-control,代碼行數:33,代碼來源:statesp.py

示例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 
開發者ID:sods,項目名稱:paramz,代碼行數:14,代碼來源:model.py

示例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 
開發者ID:ektormak,項目名稱:Lyssandra,代碼行數:41,代碼來源:sparse_coding.py

示例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 
開發者ID:ektormak,項目名稱:Lyssandra,代碼行數:39,代碼來源:sparse_coding.py

示例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 
開發者ID:nipreps,項目名稱:niworkflows,代碼行數:16,代碼來源:patches.py

示例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) 
開發者ID:tenpy,項目名稱:tenpy,代碼行數:54,代碼來源:svd_robust.py

示例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 
開發者ID:ektormak,項目名稱:Lyssandra,代碼行數:49,代碼來源:sparse_coding.py

示例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 
開發者ID:mcgillmrl,項目名稱:kusanagi,代碼行數:49,代碼來源:extra_ops.py


注:本文中的numpy.linalg.linalg.LinAlgError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。