本文整理匯總了Python中scipy.sparse.isspmatrix方法的典型用法代碼示例。如果您正苦於以下問題:Python sparse.isspmatrix方法的具體用法?Python sparse.isspmatrix怎麽用?Python sparse.isspmatrix使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類scipy.sparse
的用法示例。
在下文中一共展示了sparse.isspmatrix方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: normalize_adj
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def normalize_adj(A, is_sym=True, exponent=0.5):
"""
Normalize adjacency matrix
is_sym=True: D^{-1/2} A D^{-1/2}
is_sym=False: D^{-1} A
"""
rowsum = np.array(A.sum(1))
if is_sym:
r_inv = np.power(rowsum, -exponent).flatten()
else:
r_inv = np.power(rowsum, -1.0).flatten()
r_inv[np.isinf(r_inv)] = 0.
if sp.isspmatrix(A):
r_mat_inv = sp.diags(r_inv.squeeze())
else:
r_mat_inv = np.diag(r_inv)
if is_sym:
return r_mat_inv.dot(A).dot(r_mat_inv)
else:
return r_mat_inv.dot(A)
示例2: safe_onenorm
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def safe_onenorm(A):
"""
Computes the 1-norm of the dense or sparse matrix `A`.
Parameters
----------
A : ndarray or sparse matrix
The matrix or vector to take the norm of.
Returns
-------
float
"""
if _sps.isspmatrix(A):
return sparse_onenorm(A)
else:
return _np.linalg.norm(A, 1)
示例3: _graph_is_connected
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def _graph_is_connected(graph):
""" Return whether the graph is connected (True) or Not (False)
Parameters
----------
graph : array-like or sparse matrix, shape: (n_samples, n_samples)
adjacency matrix of the graph, non-zero weight means an edge
between the nodes
Returns
-------
is_connected : bool
True means the graph is fully connected and False means not
"""
if sparse.isspmatrix(graph):
# sparse graph, find all the connected components
n_connected_components, _ = connected_components(graph)
return n_connected_components == 1
else:
# dense graph, find all connected components start from node 0
return _graph_connected_component(graph, 0).sum() == graph.shape[0]
示例4: _decision_function
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def _decision_function(self, X):
"""Decision function of the linear model
Parameters
----------
X : numpy array or scipy.sparse matrix of shape (n_samples, n_features)
Returns
-------
T : array, shape (n_samples,)
The predicted decision function
"""
check_is_fitted(self, 'n_iter_')
if sparse.isspmatrix(X):
return safe_sparse_dot(X, self.coef_.T,
dense_output=True) + self.intercept_
else:
return super()._decision_function(X)
###############################################################################
# Lasso model
示例5: _dense_array
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def _dense_array(arr):
"""Converts the input array to dense array.
Parameters
----------
arr : numpy array or csr_matrix
The array to be densified.
Returns
-------
array-like
Dense numpy array representing arr.
"""
if isspmatrix(arr):
return arr.todense()
return arr
示例6: test_csr_to_sps
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [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])
示例7: _decision_function
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def _decision_function(self, X):
"""Decision function of the linear model
Parameters
----------
X : numpy array or scipy.sparse matrix of shape (n_samples, n_features)
Returns
-------
T : array, shape (n_samples,)
The predicted decision function
"""
check_is_fitted(self, 'n_iter_')
if sparse.isspmatrix(X):
return safe_sparse_dot(X, self.coef_.T,
dense_output=True) + self.intercept_
else:
return super(ElasticNet, self)._decision_function(X)
###############################################################################
# Lasso model
示例8: _check_b
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def _check_b(self, A, b):
if sp.isspmatrix(b):
warnings.warn('PyPardiso requires the right-hand side b to be a dense array for maximum efficiency',
SparseEfficiencyWarning)
b = b.todense()
# pardiso expects fortran (column-major) order if b is a matrix
if b.ndim == 2:
b = np.asfortranarray(b)
if b.shape[0] != A.shape[0]:
raise ValueError("Dimension mismatch: Matrix A {} and array b {}".format(A.shape, b.shape))
if b.dtype != np.float64:
if b.dtype in [np.float16, np.float32, np.int16, np.int32, np.int64]:
warnings.warn("Array b's data type was converted from {} to float64".format(str(b.dtype)),
PyPardisoWarning)
b = b.astype(np.float64)
else:
raise TypeError('Dtype {} for array b is not supported'.format(str(b.dtype)))
return b
示例9: _graph_is_connected
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def _graph_is_connected(graph):
"""
Return whether the graph is connected (True) or Not (False)
Parameters
----------
graph : array-like or sparse matrix, shape: (n_samples, n_samples)
adjacency matrix of the graph, non-zero weight means an edge
between the nodes
Returns
-------
is_connected : bool
True means the graph is fully connected and False means not
"""
if sparse.isspmatrix(graph):
# sparse graph, find all the connected components
n_connected_components, _ = connected_components(graph)
return n_connected_components == 1
else:
# dense graph, find all connected components start from node 0
return _graph_connected_component(graph, 0).sum() == graph.shape[0]
示例10: affinity_matrix
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def affinity_matrix(self, adjacency_matrix):
A = check_array(adjacency_matrix, dtype=float, copy=True,
accept_sparse=['csr', 'csc', 'coo'])
if isspmatrix(A):
data = A.data
else:
data = A
# in-place computation of
# data = np.exp(-(data / radius) ** 2)
data **= 2
data /= -self.radius ** 2
np.exp(data, out=data)
if self.symmetrize:
A = self._symmetrize(A)
# for sparse, need a true zero on the diagonal
# TODO: make this more efficient?
if isspmatrix(A):
A.setdiag(1)
return A
示例11: convert_to_adjacency_matrix
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def convert_to_adjacency_matrix(matrix):
"""
Converts transition matrix into adjacency matrix
:param matrix: The matrix to be converted
:returns: adjacency matrix
"""
for i in range(matrix.shape[0]):
if isspmatrix(matrix):
col = find(matrix[:,i])[2]
else:
col = matrix[:,i].T.tolist()[0]
coeff = max( Fraction(c).limit_denominator().denominator for c in col )
matrix[:,i] *= coeff
return matrix
示例12: delta_matrix
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def delta_matrix(matrix, clusters):
"""
Compute delta matrix where delta[i,j]=1 if i and j belong
to same cluster and i!=j
:param matrix: The adjacency matrix
:param clusters: The clusters returned by get_clusters
:returns: delta matrix
"""
if isspmatrix(matrix):
delta = dok_matrix(matrix.shape)
else:
delta = np.zeros(matrix.shape)
for i in clusters :
for j in permutations(i, 2):
delta[j] = 1
return delta
示例13: add_self_loops
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def add_self_loops(matrix, loop_value):
"""
Add self-loops to the matrix by setting the diagonal
to loop_value
:param matrix: The matrix to add loops to
:param loop_value: Value to use for self-loops
:returns: The matrix with self-loops
"""
shape = matrix.shape
assert shape[0] == shape[1], "Error, matrix is not square"
if isspmatrix(matrix):
new_matrix = matrix.todok()
else:
new_matrix = matrix.copy()
for i in range(shape[0]):
new_matrix[i, i] = loop_value
if isspmatrix(matrix):
return new_matrix.tocsc()
return new_matrix
示例14: prune
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def prune(matrix, threshold):
"""
Prune the matrix so that very small edges are removed.
The maximum value in each column is never pruned.
:param matrix: The matrix to be pruned
:param threshold: The value below which edges will be removed
:returns: The pruned matrix
"""
if isspmatrix(matrix):
pruned = dok_matrix(matrix.shape)
pruned[matrix >= threshold] = matrix[matrix >= threshold]
pruned = pruned.tocsc()
else:
pruned = matrix.copy()
pruned[pruned < threshold] = 0
# keep max value in each column. same behaviour for dense/sparse
num_cols = matrix.shape[1]
row_indices = matrix.argmax(axis=0).reshape((num_cols,))
col_indices = np.arange(num_cols)
pruned[row_indices, col_indices] = matrix[row_indices, col_indices]
return pruned
示例15: get_clusters
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import isspmatrix [as 別名]
def get_clusters(matrix):
"""
Retrieve the clusters from the matrix
:param matrix: The matrix produced by the MCL algorithm
:returns: A list of tuples where each tuple represents a cluster and
contains the indices of the nodes belonging to the cluster
"""
if not isspmatrix(matrix):
# cast to sparse so that we don't need to handle different
# matrix types
matrix = csc_matrix(matrix)
# get the attractors - non-zero elements of the matrix diagonal
attractors = matrix.diagonal().nonzero()[0]
# somewhere to put the clusters
clusters = set()
# the nodes in the same row as each attractor form a cluster
for attractor in attractors:
cluster = tuple(matrix.getrow(attractor).nonzero()[1].tolist())
clusters.add(cluster)
return sorted(list(clusters))