当前位置: 首页>>代码示例>>Python>>正文


Python sparse.isspmatrix_csr方法代码示例

本文整理汇总了Python中scipy.sparse.isspmatrix_csr方法的典型用法代码示例。如果您正苦于以下问题:Python sparse.isspmatrix_csr方法的具体用法?Python sparse.isspmatrix_csr怎么用?Python sparse.isspmatrix_csr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.sparse的用法示例。


在下文中一共展示了sparse.isspmatrix_csr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: save_hdf5

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def save_hdf5(X, y, path):
    """Save data as a HDF5 file.

    Args:
        X (numpy or scipy sparse matrix): Data matrix
        y (numpy array): Target vector.
        path (str): Path to the HDF5 file to save data.
    """

    with h5py.File(path, 'w') as f:
        is_sparse = 1 if sparse.issparse(X) else 0
        f['issparse'] = is_sparse
        f['target'] = y

        if is_sparse:
            if not sparse.isspmatrix_csr(X):
                X = X.tocsr()

            f['shape'] = np.array(X.shape)
            f['data'] = X.data
            f['indices'] = X.indices
            f['indptr'] = X.indptr
        else:
            f['data'] = X 
开发者ID:jeongyoonlee,项目名称:Kaggler,代码行数:26,代码来源:data_io.py

示例2: safereal

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def safereal(A, inplace=False, check=False):
    """
    Returns the real-part of `A` correctly when `A` is either a dense array or
    a sparse matrix
    """
    if check:
        assert(safenorm(A, 'imag') < 1e-6), "Check failed: taking real-part of matrix w/nonzero imaginary part"
    if _sps.issparse(A):
        if _sps.isspmatrix_csr(A):
            if inplace:
                ret = _sps.csr_matrix((_np.real(A.data), A.indices, A.indptr), shape=A.shape, dtype='d')
            else:  # copy
                ret = _sps.csr_matrix((_np.real(A.data).copy(), A.indices.copy(),
                                       A.indptr.copy()), shape=A.shape, dtype='d')
            ret.eliminate_zeros()
            return ret
        else:
            raise NotImplementedError("safereal() doesn't work with %s matrices yet" % str(type(A)))
    else:
        return _np.real(A) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:22,代码来源:matrixtools.py

示例3: safeimag

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def safeimag(A, inplace=False, check=False):
    """
    Returns the imaginary-part of `A` correctly when `A` is either a dense array
    or a sparse matrix
    """
    if check:
        assert(safenorm(A, 'real') < 1e-6), "Check failed: taking imag-part of matrix w/nonzero real part"
    if _sps.issparse(A):
        if _sps.isspmatrix_csr(A):
            if inplace:
                ret = _sps.csr_matrix((_np.imag(A.data), A.indices, A.indptr), shape=A.shape, dtype='d')
            else:  # copy
                ret = _sps.csr_matrix((_np.imag(A.data).copy(), A.indices.copy(),
                                       A.indptr.copy()), shape=A.shape, dtype='d')
            ret.eliminate_zeros()
            return ret
        else:
            raise NotImplementedError("safereal() doesn't work with %s matrices yet" % str(type(A)))
    else:
        return _np.imag(A) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:22,代码来源:matrixtools.py

示例4: GetPreconditioner

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def GetPreconditioner(self,A, type="amg_smoothed_aggregation"):
        """Applies a suitable preconditioner to sparse matrix A
            based on algebraic multigrid of incomplete LU/Cholesky factorisation

            input:
                A:                      [csc_matrix or csc_matrix]
                type:                   [str] either "amg_smoothed_aggregation" for
                                        a preconditioner based on algebraic multigrid
                                        or "incomplete_lu" for scipy's spilu linear
                                        operator

            returns:                    A preconditioner that can be used in conjunction
                                        with scipy's sparse linear iterative solvers
                                        (the M keyword in scipy's iterative solver)
        """

        if not (isspmatrix_csc(A) or isspmatrix_csr(A)):
            raise TypeError("Matrix must be in CSC or CSR sparse format for preconditioning")

        ml = smoothed_aggregation_solver(A)
        return ml.aspreconditioner() 
开发者ID:romeric,项目名称:florence,代码行数:23,代码来源:LinearSolver.py

示例5: GetCuthillMcKeePermutation

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def GetCuthillMcKeePermutation(self,A):
        """Applies Cuthill-Mckee permutation to reduce the sparse matrix bandwidth

            input:
                A:                    [csc_matrix or csr_matrix]

            returns:
                perm:                 [1D array] of permutation such that A[perm,:][:,perm]
                                      has its non-zero elements closer to the diagonal
        """

        if not (isspmatrix_csc(A) or isspmatrix_csr(A)):
            raise TypeError("Matrix must be in CSC or CSR sparse format "
                "for Cuthill-McKee permutation")

        if int(sp.__version__.split('.')[1]) >= 15:
            from scipy.sparse.csgraph import reverse_cuthill_mckee
            perm = reverse_cuthill_mckee(A)
        else:
            from Florence.Tensor import symrcm
            perm = symrcm(A)

        return perm 
开发者ID:romeric,项目名称:florence,代码行数:25,代码来源:LinearSolver.py

示例6: _downsample_total_counts

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def _downsample_total_counts(X, total_counts, random_state, replace):
    total_counts = int(total_counts)
    total = X.sum()
    if total < total_counts:
        return X
    if issparse(X):
        original_type = type(X)
        if not isspmatrix_csr(X):
            X = csr_matrix(X)
        _downsample_array(
            X.data,
            total_counts,
            random_state=random_state,
            replace=replace,
            inplace=True,
        )
        X.eliminate_zeros()
        if original_type is not csr_matrix:
            X = original_type(X)
    else:
        v = X.reshape(np.multiply(*X.shape))
        _downsample_array(
            v, total_counts, random_state, replace=replace, inplace=True
        )
    return X 
开发者ID:theislab,项目名称:scanpy,代码行数:27,代码来源:_simple.py

示例7: top_proportions

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def top_proportions(mtx: Union[np.array, spmatrix], n: int):
    """\
    Calculates cumulative proportions of top expressed genes

    Parameters
    ----------
    mtx
        Matrix, where each row is a sample, each column a feature.
    n
        Rank to calculate proportions up to. Value is treated as 1-indexed,
        `n=50` will calculate cumulative proportions up to the 50th most
        expressed gene.
    """
    if issparse(mtx):
        if not isspmatrix_csr(mtx):
            mtx = csr_matrix(mtx)
        # Allowing numba to do more
        return top_proportions_sparse_csr(mtx.data, mtx.indptr, np.array(n))
    else:
        return top_proportions_dense(mtx, n) 
开发者ID:theislab,项目名称:scanpy,代码行数:22,代码来源:_qc.py

示例8: _sparse_matrix_data

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def _sparse_matrix_data(X):
    """Prepare the sparse matrix for conversion to TensorFlow.

    Parameters
    ----------
    X : sparse matrix

    Returns
    -------
    indices : numpy array with shape (X.nnz, 2)
              describing the indices with values in X.
    values : numpy array with shape (X.nnz)
             describing the values at each index
    """
    if sp.isspmatrix_csr(X):
        return _csr_data(X)
    else:
        return _csr_data(X.tocsr()) 
开发者ID:civisanalytics,项目名称:muffnn,代码行数:20,代码来源:base.py

示例9: __init__

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def __init__(self, matrix, basis=None, z2_symmetries=None, atol=1e-12, name=None):
        """
        Args:
            matrix (numpy.ndarray or scipy.sparse.csr_matrix):
                    a 2-D sparse matrix represents operator (using CSR format internally)
            basis (list[tuple(object, [int])], optional): the grouping basis, each element is a
                                                          tuple composed of the basis
                                                          and the indices to paulis which are
                                                          belonged to that group.
                                                          e.g., if tpb basis is used, the object
                                                          will be a pauli.
                                                          by default, the group is equal to
                                                          non-grouping, each pauli is its own basis.
            z2_symmetries (Z2Symmetries): represent the Z2 symmetries
            atol (float): atol
            name (str): name
        """
        super().__init__(basis, z2_symmetries, name)
        if matrix is not None:
            matrix = matrix if scisparse.issparse(matrix) else scisparse.csr_matrix(matrix)
            matrix = matrix if scisparse.isspmatrix_csr(matrix) else matrix.to_csr(copy=True)
        self._matrix = matrix
        self._atol = atol 
开发者ID:Qiskit,项目名称:qiskit-aqua,代码行数:25,代码来源:matrix_operator.py

示例10: from_scipy

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def from_scipy(cls, mat, copy=True):
        """
        Convert a scipy sparse matrix to an internal CSR.

        Args:
            mat(scipy.sparse.spmatrix): a SciPy sparse matrix.
            copy(bool): if ``False``, reuse the SciPy storage if possible.

        Returns:
            CSR: a CSR matrix.
        """
        if not sps.isspmatrix_csr(mat):
            mat = mat.tocsr(copy=copy)
        rp = np.require(mat.indptr, np.intc, 'C')
        if copy and rp is mat.indptr:
            rp = rp.copy()
        cs = np.require(mat.indices, np.intc, 'C')
        if copy and cs is mat.indices:
            cs = cs.copy()
        vs = mat.data.copy() if copy else mat.data
        return cls(mat.shape[0], mat.shape[1], mat.nnz, rp, cs, vs) 
开发者ID:lenskit,项目名称:lkpy,代码行数:23,代码来源:__init__.py

示例11: test_csr_to_sps

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def test_csr_to_sps():
    # initialize sparse matrix
    mat = np.random.randn(10, 5)
    mat[mat <= 0] = 0
    # get COO
    smat = sps.coo_matrix(mat)
    # make sure it's sparse
    assert smat.nnz == np.sum(mat > 0)

    csr = lm.CSR.from_coo(smat.row, smat.col, smat.data, shape=smat.shape)
    assert csr.nnz == smat.nnz
    assert csr.nrows == smat.shape[0]
    assert csr.ncols == smat.shape[1]

    smat2 = csr.to_scipy()
    assert sps.isspmatrix(smat2)
    assert sps.isspmatrix_csr(smat2)

    for i in range(csr.nrows):
        assert smat2.indptr[i] == csr.rowptrs[i]
        assert smat2.indptr[i+1] == csr.rowptrs[i+1]
        sp = smat2.indptr[i]
        ep = smat2.indptr[i+1]
        assert all(smat2.indices[sp:ep] == csr.colinds[sp:ep])
        assert all(smat2.data[sp:ep] == csr.values[sp:ep]) 
开发者ID:lenskit,项目名称:lkpy,代码行数:27,代码来源:test_matrix_csr.py

示例12: csr_matrix_to_sparse

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def csr_matrix_to_sparse(fp):
    """Sparsify a CSR fingerprint.

    .. versionadded:: 0.6

    Parameters
    ----------
    fp : csr_matrix
        Fingerprint in a CSR form.

    Returns
    -------
    fp : np.array
        Sparse fingerprint - an array of "on" integers. In cas of count vectors,
        the indices are dupplicated according to count.
    """
    if not isspmatrix_csr(fp):
        raise ValueError('fp is not CSR sparse matrix but %s (%s)' %
                         (type(fp), fp))
    # FIXME: change these methods to work for stacked fps (2D)
    return np.repeat(fp.indices, fp.data)


# ranges for hashing function 
开发者ID:oddt,项目名称:oddt,代码行数:26,代码来源:fingerprints.py

示例13: _check_X_input

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def _check_X_input(X):
    if (X.__class__.__name__ == 'DataFrame') or isinstance(X, pd.core.frame.DataFrame):
        X = X.to_numpy()
    if isinstance(X, np.matrixlib.defmatrix.matrix):
        warnings.warn("'defmatrix' will be cast to array.")
        X = np.array(X)
    if not isinstance(X, np.ndarray) and not isspmatrix_csr(X):
        raise ValueError("'X' must be a numpy array or sparse CSR matrix.")
    if len(X.shape) == 1:
        X = X.reshape((1, -1))
    assert len(X.shape) == 2
    return X 
开发者ID:david-cortes,项目名称:contextualbandits,代码行数:14,代码来源:utils.py

示例14: _logistic_grad_norm

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def _logistic_grad_norm(X, y, pred, base_algorithm):
    coef = base_algorithm.coef_.reshape(-1)[:X.shape[1]]
    err = pred - y

    if issparse(X):
        if not isspmatrix_csr(X):
            warnings.warn("Sparse matrix will be cast to CSR format.")
            X = csr_matrix(X)
        grad_norm = X.multiply(err.reshape((-1, 1)))
    else:
        grad_norm = X * err.reshape((-1, 1))

    ### Note: since this is done on a row-by-row basis on two classes only,
    ### it doesn't matter whether the loss function is summed or averaged over
    ### data points, or whether there is regularization or not.

    ## coefficients
    if not issparse(grad_norm):
        grad_norm = np.einsum("ij,ij->i", grad_norm, grad_norm)
    else:
        grad_norm = np.array(grad_norm.multiply(grad_norm).sum(axis=1)).reshape(-1)

    ## intercept
    if base_algorithm.fit_intercept:
        grad_norm += err ** 2

    return grad_norm 
开发者ID:david-cortes,项目名称:contextualbandits,代码行数:29,代码来源:utils.py

示例15: csr_matvec

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix_csr [as 别名]
def csr_matvec(csr, x):

    if not sparse.isspmatrix_csr(csr):
        raise Exception("Matrix must be in csr format")

    nrow, ncol = csr.shape
    nnz = csr.data.shape[0]
    if x.size != ncol:
      print(x.size, ncol)
      raise ValueError("wrong dimension!")

    xx = np.require(x, requirements=["A", "O"])
    
    if csr.dtype == np.float32:
        y = np.zeros((nrow), dtype=np.float32)
        libsparsetools.scsr_matvec(c_int(nrow), c_int(ncol), c_int(nnz), 
                csr.indptr.ctypes.data_as(POINTER(c_int)),
                csr.indices.ctypes.data_as(POINTER(c_int)), 
                csr.data.ctypes.data_as(POINTER(c_float)),
                xx.ctypes.data_as(POINTER(c_float)), 
                y.ctypes.data_as(POINTER(c_float)))

    elif csr.dtype == np.float64:
        y = np.zeros((nrow), dtype=np.float64)
        libsparsetools.dcsr_matvec(c_int(nrow), c_int(ncol), c_int(nnz), 
                csr.indptr.ctypes.data_as(POINTER(c_int)),
                csr.indices.ctypes.data_as(POINTER(c_int)), 
                csr.data.ctypes.data_as(POINTER(c_double)),
                xx.ctypes.data_as(POINTER(c_double)), 
                y.ctypes.data_as(POINTER(c_double)))
    else:
        raise ValueError("Not implemented")

    return y 
开发者ID:pyscf,项目名称:pyscf,代码行数:36,代码来源:m_sparsetools.py


注:本文中的scipy.sparse.isspmatrix_csr方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。