本文整理汇总了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
示例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)
示例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)
示例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()
示例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
示例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
示例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)
示例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())
示例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
示例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)
示例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])
示例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
示例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
示例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
示例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