本文整理汇总了Python中scipy.sparse.eye方法的典型用法代码示例。如果您正苦于以下问题:Python sparse.eye方法的具体用法?Python sparse.eye怎么用?Python sparse.eye使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.sparse
的用法示例。
在下文中一共展示了sparse.eye方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _N
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def _N(self,s,r):
"""
Lagrange's interpolate function
params:
s,r:natural position of evalue point.2-array.
returns:
2x(2x4) shape function matrix.
"""
la1=(1-s)/2
la2=(1+s)/2
lb1=(1-r)/2
lb2=(1+r)/2
N1=la1*lb1
N2=la1*lb2
N3=la2*lb1
N4=la2*lb2
N=np.hstack(N1*np.eye(2),N2*np.eye(2),N3*np.eye(2),N4*np.eye(2))
return N
示例2: chebyshev_polynomials
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def chebyshev_polynomials(adj, k):
"""Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices (tuple representation)."""
print("Calculating Chebyshev polynomials up to order {}...".format(k))
adj_normalized = normalize_adj(adj)
laplacian = sp.eye(adj.shape[0]) - adj_normalized
largest_eigval, _ = eigsh(laplacian, 1, which='LM')
scaled_laplacian = (
2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])
t_k = list()
t_k.append(sp.eye(adj.shape[0]))
t_k.append(scaled_laplacian)
def chebyshev_recurrence(t_k_minus_one, t_k_minus_two, scaled_lap):
s_lap = sp.csr_matrix(scaled_lap, copy=True)
return 2 * s_lap.dot(t_k_minus_one) - t_k_minus_two
for i in range(2, k+1):
t_k.append(chebyshev_recurrence(t_k[-1], t_k[-2], scaled_laplacian))
return sparse_to_tuple(t_k)
示例3: learn_embedding
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def learn_embedding(self):
graph = self.g.G
graph = graph.to_undirected()
t1 = time()
A = nx.to_scipy_sparse_matrix(graph)
# print(np.sum(A.todense(), axis=0))
normalize(A, norm='l1', axis=1, copy=False)
I_n = sp.eye(graph.number_of_nodes())
I_min_A = I_n - A
print(I_min_A)
u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
t2 = time()
self._X = vt.T
self._X = self._X[:, 1:]
return self._X, (t2 - t1)
# I_n = sp.eye(graph.number_of_nodes())
示例4: normalize_adjacency
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def normalize_adjacency(graph, args):
"""
Method to calculate a sparse degree normalized adjacency matrix.
:param graph: Sparse graph adjacency matrix.
:return A: Normalized adjacency matrix.
"""
for node in graph.nodes():
graph.add_edge(node, node)
ind = range(len(graph.nodes()))
degs = [1.0/graph.degree(node) for node in graph.nodes()]
L = sparse.csr_matrix(nx.laplacian_matrix(graph),
dtype=np.float32)
degs = sparse.csr_matrix(sparse.coo_matrix((degs, (ind, ind)),
shape=L.shape,
dtype=np.float32))
propagator = sparse.eye(L.shape[0])-args.gamma*degs.dot(L)
return propagator
示例5: dfs_trunk
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def dfs_trunk(sim, A,alpha = 0.99, QUERYKNN = 10, maxiter = 8, K = 100, tol = 1e-3):
qsim = sim_kernel(sim).T
sortidxs = np.argsort(-qsim, axis = 1)
for i in range(len(qsim)):
qsim[i,sortidxs[i,QUERYKNN:]] = 0
qsims = sim_kernel(qsim)
W = sim_kernel(A)
W = csr_matrix(topK_W(W, K))
out_ranks = []
t =time()
for i in range(qsims.shape[0]):
qs = qsims[i,:]
tt = time()
w_idxs, W_trunk = find_trunc_graph(qs, W, 2);
Wn = normalize_connection_graph(W_trunk)
Wnn = eye(Wn.shape[0]) - alpha * Wn
f,inf = s_linalg.minres(Wnn, qs[w_idxs], tol=tol, maxiter=maxiter)
ranks = w_idxs[np.argsort(-f.reshape(-1))]
missing = np.setdiff1d(np.arange(A.shape[1]), ranks)
out_ranks.append(np.concatenate([ranks.reshape(-1,1), missing.reshape(-1,1)], axis = 0))
#print time() -t, 'qtime'
out_ranks = np.concatenate(out_ranks, axis = 1)
return out_ranks
示例6: localpooling_filter
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def localpooling_filter(A, symmetric=True):
r"""
Computes the graph filter described in
[Kipf & Welling (2017)](https://arxiv.org/abs/1609.02907).
:param A: array or sparse matrix with rank 2 or 3;
:param symmetric: boolean, whether to normalize the matrix as
\(\D^{-\frac{1}{2}}\A\D^{-\frac{1}{2}}\) or as \(\D^{-1}\A\);
:return: array or sparse matrix with rank 2 or 3, same as A;
"""
fltr = A.copy()
if sp.issparse(A):
I = sp.eye(A.shape[-1], dtype=A.dtype)
else:
I = np.eye(A.shape[-1], dtype=A.dtype)
if A.ndim == 3:
for i in range(A.shape[0]):
A_tilde = A[i] + I
fltr[i] = normalized_adjacency(A_tilde, symmetric=symmetric)
else:
A_tilde = A + I
fltr = normalized_adjacency(A_tilde, symmetric=symmetric)
if sp.issparse(fltr):
fltr.sort_indices()
return fltr
示例7: whiten
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def whiten(self, X):
"""
SUR whiten method.
Parameters
-----------
X : list of arrays
Data to be whitened.
Returns
-------
If X is the exogenous RHS of the system.
``np.dot(np.kron(cholsigmainv,np.eye(M)),np.diag(X))``
If X is the endogenous LHS of the system.
"""
nobs = self.nobs
if X is self.endog: # definitely not a robust check
return np.dot(np.kron(self.cholsigmainv,np.eye(nobs)),
X.reshape(-1,1))
elif X is self.sp_exog:
return (sparse.kron(self.cholsigmainv,
sparse.eye(nobs,nobs))*X).toarray()#*=dot until cast to array
示例8: encode_onehot
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def encode_onehot(labels):
"""Convert label to onehot format.
Parameters
----------
labels : numpy.array
node labels
Returns
-------
numpy.array
onehot labels
"""
eye = np.eye(labels.max() + 1)
onehot_mx = eye[labels]
return onehot_mx
示例9: tensor2onehot
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def tensor2onehot(labels):
"""Convert label tensor to label onehot tensor.
Parameters
----------
labels : torch.LongTensor
node labels
Returns
-------
torch.LongTensor
onehot labels tensor
"""
eye = torch.eye(labels.max() + 1)
onehot_mx = eye[labels]
return onehot_mx.to(labels.device)
示例10: normalize_adj_tensor
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def normalize_adj_tensor(adj, sparse=False):
"""Normalize adjacency tensor matrix.
"""
device = torch.device("cuda" if adj.is_cuda else "cpu")
if sparse:
# TODO if this is too slow, uncomment the following code,
# but you need to install torch_scatter
# return normalize_sparse_tensor(adj)
adj = to_scipy(adj)
mx = normalize_adj(adj)
return sparse_mx_to_torch_sparse_tensor(mx).to(device)
else:
mx = adj + torch.eye(adj.shape[0]).to(device)
rowsum = mx.sum(1)
r_inv = rowsum.pow(-1/2).flatten()
r_inv[torch.isinf(r_inv)] = 0.
r_mat_inv = torch.diag(r_inv)
mx = r_mat_inv @ mx
mx = mx @ r_mat_inv
return mx
示例11: chebyshev_polynomials
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def chebyshev_polynomials(adj, k):
"""Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices (tuple representation)."""
print("Calculating Chebyshev polynomials up to order {}...".format(k))
adj_normalized = normalize_adj(adj)
laplacian = sp.eye(adj.shape[0]) - adj_normalized
largest_eigval, _ = eigsh(laplacian, 1, which='LM')
scaled_laplacian = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])
t_k = list()
t_k.append(sp.eye(adj.shape[0]))
t_k.append(scaled_laplacian)
def chebyshev_recurrence(t_k_minus_one, t_k_minus_two, scaled_lap):
s_lap = sp.csr_matrix(scaled_lap, copy=True)
return 2 * s_lap.dot(t_k_minus_one) - t_k_minus_two
for i in range(2, k+1):
t_k.append(chebyshev_recurrence(t_k[-1], t_k[-2], scaled_laplacian))
return sparse_to_tuple(t_k)
示例12: test_dual_infeasible_lp
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def test_dual_infeasible_lp(self):
# Dual infeasible example
self.P = sparse.csc_matrix((2, 2))
self.q = np.array([2, -1])
self.A = sparse.eye(2, format='csc')
self.l = np.array([0., 0.])
self.u = np.array([np.inf, np.inf])
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'))
示例13: setUp
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [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)
示例14: setUp
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [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)
示例15: sakurai
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import eye [as 别名]
def sakurai(n):
""" Example taken from
T. Sakurai, H. Tadano, Y. Inadomi and U. Nagashima
A moment-based method for large-scale generalized eigenvalue problems
Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004) """
A = sparse.eye(n, n)
d0 = array(r_[5,6*ones(n-2),5])
d1 = -4*ones(n)
d2 = ones(n)
B = sparse.spdiags([d2,d1,d0,d1,d2],[-2,-1,0,1,2],n,n)
k = arange(1,n+1)
w_ex = sort(1./(16.*pow(cos(0.5*k*pi/(n+1)),4))) # exact eigenvalues
return A,B, w_ex