本文整理汇总了Python中scipy.sparse.diags方法的典型用法代码示例。如果您正苦于以下问题:Python sparse.diags方法的具体用法?Python sparse.diags怎么用?Python sparse.diags使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.sparse
的用法示例。
在下文中一共展示了sparse.diags方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: normalize_features
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def normalize_features(feat):
degree = np.asarray(feat.sum(1)).flatten()
# set zeros to inf to avoid dividing by zero
degree[degree == 0.] = np.inf
degree_inv = 1. / degree
degree_inv_mat = sp.diags([degree_inv], [0])
feat_norm = degree_inv_mat.dot(feat)
if feat_norm.nnz == 0:
print('ERROR: normalized adjacency matrix has only zero entries!!!!!')
exit
return feat_norm
示例2: normalize_adj
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [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)
示例3: pre_factorization
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def pre_factorization(G, n_components, exponent):
"""
Network Embedding as Sparse Matrix Factorization
"""
C1 = preprocessing.normalize(G, "l1")
# Prepare negative samples
neg = np.array(C1.sum(axis=0))[0] ** exponent
neg = neg / neg.sum()
neg = sparse.diags(neg, format="csr")
neg = G.dot(neg)
# Set negative elements to 1 -> 0 when log
C1.data[C1.data <= 0] = 1
neg.data[neg.data <= 0] = 1
C1.data = np.log(C1.data)
neg.data = np.log(neg.data)
C1 -= neg
features_matrix = ProNE.tsvd_rand(C1, n_components=n_components)
return features_matrix
示例4: degree_power
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def degree_power(A, k):
r"""
Computes \(\D^{k}\) from the given adjacency matrix. Useful for computing
normalised Laplacian.
:param A: rank 2 array or sparse matrix.
:param k: exponent to which elevate the degree matrix.
:return: if A is a dense array, a dense array; if A is sparse, a sparse
matrix in DIA format.
"""
degrees = np.power(np.array(A.sum(1)), k).flatten()
degrees[np.isinf(degrees)] = 0.
if sp.issparse(A):
D = sp.diags(degrees)
else:
D = np.diag(degrees)
return D
示例5: compute_lambda
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def compute_lambda(pairs, Z, lmdb, lmdb_data):
numsamples = len(Z)
R = csr_matrix((lmdb * pairs[:,2], (pairs[:,0].astype(int), pairs[:,1].astype(int))), shape=(numsamples, numsamples))
R = R + R.transpose()
D = diags(np.squeeze(np.array(np.sum(R,1))), 0)
I = diags(lmdb_data, 0)
spndata = np.linalg.norm(I * Z, ord=2)
eiglmdbdata,_ = sparse.linalg.eigsh(I, k=1)
eigM,_ = sparse.linalg.eigsh(D - R, k=1)
_lambda = float(spndata / (eiglmdbdata + eigM))
return _lambda
示例6: _create_A_L
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def _create_A_L(self, graph, node2idx):
node_size = graph.number_of_nodes()
A_data = []
A_row_index = []
A_col_index = []
for edge in graph.edges():
v1, v2 = edge
edge_weight = graph[v1][v2].get('weight', 1)
A_data.append(edge_weight)
A_row_index.append(node2idx[v1])
A_col_index.append(node2idx[v2])
A = sp.csr_matrix((A_data, (A_row_index, A_col_index)), shape=(node_size, node_size))
A_ = sp.csr_matrix((A_data + A_data, (A_row_index + A_col_index, A_col_index + A_row_index)),
shape=(node_size, node_size))
D = sp.diags(A_.sum(axis=1).flatten().tolist()[0])
L = D - A_
return A, L
示例7: normalize_feature
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def normalize_feature(mx):
"""Row-normalize sparse matrix
Parameters
----------
mx : scipy.sparse.csr_matrix
matrix to be normalized
Returns
-------
scipy.sprase.lil_matrix
normalized matrix
"""
if type(mx) is not sp.lil.lil_matrix:
mx = mx.tolil()
rowsum = np.array(mx.sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
mx = r_mat_inv.dot(mx)
return mx
示例8: test_dual_infeasible_qp
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def test_dual_infeasible_qp(self):
# Dual infeasible example
self.P = sparse.diags([4., 0.], format='csc')
self.q = np.array([0, 2])
self.A = sparse.csc_matrix([[1., 1.], [-1., 1.]])
self.l = np.array([-np.inf, -np.inf])
self.u = np.array([2., 3.])
self.model = osqp.OSQP()
self.model.setup(P=self.P, q=self.q, A=self.A, l=self.l, u=self.u,
**self.opts)
# Solve problem with OSQP
res = self.model.solve()
# Assert close
self.assertEqual(res.info.status_val,
constant('OSQP_DUAL_INFEASIBLE'))
示例9: setUp
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def setUp(self):
# Simple QP problem
self.P = sparse.diags([11., 0.1], format='csc')
self.P_new = sparse.eye(2, format='csc')
self.q = np.array([3, 4])
self.A = sparse.csc_matrix([[-1, 0], [0, -1], [-1, -3],
[2, 5], [3, 4]])
self.A_new = sparse.csc_matrix([[-1, 0], [0, -1], [-2, -2],
[2, 5], [3, 4]])
self.u = np.array([0, 0, -15, 100, 80])
self.l = -np.inf * np.ones(len(self.u))
self.n = self.P.shape[0]
self.m = self.A.shape[0]
self.opts = {'verbose': False,
'eps_abs': 1e-08,
'eps_rel': 1e-08,
'alpha': 1.6,
'max_iter': 3000,
'warm_start': True}
self.model = osqp.OSQP()
self.model.setup(P=self.P, q=self.q, A=self.A, l=self.l, u=self.u,
**self.opts)
示例10: setUp
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def setUp(self):
"""
Setup unconstrained quadratic problem
"""
# Unconstrained QP problem
sp.random.seed(4)
self.n = 30
self.m = 0
P = sparse.diags(np.random.rand(self.n)) + 0.2*sparse.eye(self.n)
self.P = P.tocsc()
self.q = np.random.randn(self.n)
self.A = sparse.csc_matrix((self.m, self.n))
self.l = np.array([])
self.u = np.array([])
self.opts = {'verbose': False,
'eps_abs': 1e-08,
'eps_rel': 1e-08,
'polish': False}
self.model = osqp.OSQP()
self.model.setup(P=self.P, q=self.q, A=self.A, l=self.l, u=self.u,
**self.opts)
示例11: test_polish_simple
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def test_polish_simple(self):
# Simple QP problem
self.P = sparse.diags([11., 0.], format='csc')
self.q = np.array([3, 4])
self.A = sparse.csc_matrix([[-1, 0], [0, -1], [-1, -3], [2, 5], [3, 4]])
self.u = np.array([0, 0, -15, 100, 80])
self.l = -np.inf * np.ones(len(self.u))
self.n = self.P.shape[0]
self.m = self.A.shape[0]
self.model = osqp.OSQP()
self.model.setup(P=self.P, q=self.q, A=self.A, l=self.l, u=self.u,
**self.opts)
# Solve problem
res = self.model.solve()
# Assert close
nptest.assert_array_almost_equal(res.x, np.array([0., 5.]))
nptest.assert_array_almost_equal(res.y, np.array([1.66666667, 0.,
1.33333333, 0., 0.]))
nptest.assert_array_almost_equal(res.info.obj_val, 20.)
示例12: setUp
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def setUp(self):
# Simple QP problem
self.P = sparse.diags([11., 0.], format='csc')
self.q = np.array([3, 4])
self.A = sparse.csc_matrix([[-1, 0], [0, -1], [-1, -3], [2, 5], [3, 4]])
self.u = np.array([0, 0, -15, 100, 80])
self.l = -np.inf * np.ones(len(self.u))
self.n = self.P.shape[0]
self.m = self.A.shape[0]
self.opts = {'verbose': False,
'eps_abs': 1e-08,
'eps_rel': 1e-08,
'rho': 0.01,
'alpha': 1.6,
'max_iter': 10000,
'warm_start': True}
self.model = osqp.OSQP()
self.model.setup(P=self.P, q=self.q, A=self.A, l=self.l, u=self.u,
**self.opts)
示例13: matrix
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def matrix(self, shape, *args, **kwargs):
""" Matrix representation of given operator product on an equidistant grid of given shape.
:param shape: tuple with the shape of the grid
:return: scipy sparse matrix representing the operator product
"""
if isinstance(self.left, np.ndarray):
left = sparse.diags(self.left.reshape(-1), 0)
elif isinstance(self.left, LinearMap) or isinstance(self.left, BinaryOperator):
left = self.left.matrix(shape, *args, **kwargs)
else:
left = self.left * sparse.diags(np.ones(shape).reshape(-1), 0)
if isinstance(self.right, np.ndarray):
right = sparse.diags(self.right.reshape(-1), 0)
elif isinstance(self.right, LinearMap) or isinstance(self.right, BinaryOperator):
right = self.right.matrix(shape, *args, **kwargs)
else:
right = self.right * sparse.diags(np.ones(shape).reshape(-1), 0)
return left.dot(right)
示例14: jacobian
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def jacobian(self, x, into=None):
x = flattest(x)
z = sps.diags(-sine(x))
return safe_into(into, z)
示例15: globally_normalize_bipartite_adjacency
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import diags [as 别名]
def globally_normalize_bipartite_adjacency(adjacencies, verbose=False, symmetric=True):
""" Globally Normalizes set of bipartite adjacency matrices """
if verbose:
print('Symmetrically normalizing bipartite adj')
# degree_u and degree_v are row and column sums of adj+I
adj_tot = np.sum(adj for adj in adjacencies)
degree_u = np.asarray(adj_tot.sum(1)).flatten()
degree_v = np.asarray(adj_tot.sum(0)).flatten()
# set zeros to inf to avoid dividing by zero
degree_u[degree_u == 0.] = np.inf
degree_v[degree_v == 0.] = np.inf
degree_u_inv_sqrt = 1. / np.sqrt(degree_u)
degree_v_inv_sqrt = 1. / np.sqrt(degree_v)
degree_u_inv_sqrt_mat = sp.diags([degree_u_inv_sqrt], [0])
degree_v_inv_sqrt_mat = sp.diags([degree_v_inv_sqrt], [0])
degree_u_inv = degree_u_inv_sqrt_mat.dot(degree_u_inv_sqrt_mat)
if symmetric:
adj_norm = [degree_u_inv_sqrt_mat.dot(adj).dot(degree_v_inv_sqrt_mat) for adj in adjacencies]
else:
adj_norm = [degree_u_inv.dot(adj) for adj in adjacencies]
return adj_norm