本文整理汇总了Python中scipy.sparse.csgraph.laplacian方法的典型用法代码示例。如果您正苦于以下问题:Python csgraph.laplacian方法的具体用法?Python csgraph.laplacian怎么用?Python csgraph.laplacian使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.sparse.csgraph
的用法示例。
在下文中一共展示了csgraph.laplacian方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _check_graph_laplacian
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def _check_graph_laplacian(mat, normed):
if not hasattr(mat, 'shape'):
mat = eval(mat, dict(np=np, sparse=sparse))
if sparse.issparse(mat):
sp_mat = mat
mat = sp_mat.todense()
else:
sp_mat = sparse.csr_matrix(mat)
laplacian = csgraph.laplacian(mat, normed=normed)
n_nodes = mat.shape[0]
if not normed:
np.testing.assert_array_almost_equal(laplacian.sum(axis=0),
np.zeros(n_nodes))
np.testing.assert_array_almost_equal(laplacian.T,
laplacian)
np.testing.assert_array_almost_equal(
laplacian,
csgraph.laplacian(sp_mat, normed=normed).todense())
np.testing.assert_array_almost_equal(
laplacian,
_explicit_laplacian(mat, normed=normed))
示例2: test_spectral_embedding_unnormalized
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def test_spectral_embedding_unnormalized():
# Test that spectral_embedding is also processing unnormalized laplacian
# correctly
random_state = np.random.RandomState(36)
data = random_state.randn(10, 30)
sims = rbf_kernel(data)
n_components = 8
embedding_1 = spectral_embedding(sims,
norm_laplacian=False,
n_components=n_components,
drop_first=False)
# Verify using manual computation with dense eigh
laplacian, dd = csgraph.laplacian(sims, normed=False,
return_diag=True)
_, diffusion_map = eigh(laplacian)
embedding_2 = diffusion_map.T[:n_components]
embedding_2 = _deterministic_vector_sign_flip(embedding_2).T
assert_array_almost_equal(embedding_1, embedding_2)
示例3: _check_symmetric_graph_laplacian
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def _check_symmetric_graph_laplacian(mat, normed):
if not hasattr(mat, 'shape'):
mat = eval(mat, dict(np=np, sparse=sparse))
if sparse.issparse(mat):
sp_mat = mat
mat = sp_mat.todense()
else:
sp_mat = sparse.csr_matrix(mat)
laplacian = csgraph.laplacian(mat, normed=normed)
n_nodes = mat.shape[0]
if not normed:
assert_array_almost_equal(laplacian.sum(axis=0), np.zeros(n_nodes))
assert_array_almost_equal(laplacian.T, laplacian)
assert_array_almost_equal(laplacian,
csgraph.laplacian(sp_mat, normed=normed).todense())
assert_array_almost_equal(laplacian,
_explicit_laplacian(mat, normed=normed))
示例4: test_arpack_eigsh_initialization
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def test_arpack_eigsh_initialization():
# Non-regression test that shows null-space computation is better with
# initialization of eigsh from [-1,1] instead of [0,1]
random_state = check_random_state(42)
A = random_state.rand(50, 50)
A = np.dot(A.T, A) # create s.p.d. matrix
A = laplacian(A) + 1e-7 * np.identity(A.shape[0])
k = 5
# Test if eigsh is working correctly
# New initialization [-1,1] (as in original ARPACK)
# Was [0,1] before, with which this test could fail
v0 = random_state.uniform(-1, 1, A.shape[0])
w, _ = eigsh(A, k=k, sigma=0.0, v0=v0)
# Eigenvalues of s.p.d. matrix should be nonnegative, w[0] is smallest
assert_greater_equal(w[0], 0)
示例5: direct_compute_deepwalk_matrix
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def direct_compute_deepwalk_matrix(A, window, b):
n = A.shape[0]
vol = float(A.sum())
L, d_rt = csgraph.laplacian(A, normed=True, return_diag=True)
# X = D^{-1/2} A D^{-1/2}
X = sparse.identity(n) - L
S = np.zeros_like(X)
X_power = sparse.identity(n)
for i in range(window):
logger.info("Compute matrix %d-th power", i+1)
X_power = X_power.dot(X)
S += X_power
S *= vol / window / b
D_rt_inv = sparse.diags(d_rt ** -1)
M = D_rt_inv.dot(D_rt_inv.dot(S).T)
m = T.matrix()
f = theano.function([m], T.log(T.maximum(m, 1)))
Y = f(M.todense().astype(theano.config.floatX))
return sparse.csr_matrix(Y)
示例6: laplacian
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def laplacian(mx, norm):
"""Laplacian-normalize sparse matrix"""
assert (all (len(row) == len(mx) for row in mx)), "Input should be a square matrix"
return csgraph.laplacian(adj, normed = norm)
示例7: _build_graph
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def _build_graph(self):
"""Graph matrix for Label Spreading computes the graph laplacian"""
# compute affinity matrix (or gram matrix)
if self.kernel == 'knn':
self.nn_fit = None
n_samples = self.X_.shape[0]
affinity_matrix = self._get_kernel(self.X_)
laplacian = csgraph.laplacian(affinity_matrix, normed=True)
laplacian = -laplacian
if sparse.isspmatrix(laplacian):
diag_mask = (laplacian.row == laplacian.col)
laplacian.data[diag_mask] = 0.0
else:
laplacian.flat[::n_samples + 1] = 0.0 # set diag to 0.0
return laplacian
示例8: test_laplacian_value_error
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def test_laplacian_value_error():
for t in int, float, complex:
for m in ([1, 1],
[[[1]]],
[[1, 2, 3], [4, 5, 6]],
[[1, 2], [3, 4], [5, 5]]):
A = np.array(m, dtype=t)
assert_raises(ValueError, csgraph.laplacian, A)
示例9: _check_laplacian
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def _check_laplacian(A, desired_L, desired_d, normed, use_out_degree):
for arr_type in np.array, sparse.csr_matrix, sparse.coo_matrix:
for t in int, float, complex:
adj = arr_type(A, dtype=t)
L = csgraph.laplacian(adj, normed=normed, return_diag=False,
use_out_degree=use_out_degree)
_assert_allclose_sparse(L, desired_L, atol=1e-12)
L, d = csgraph.laplacian(adj, normed=normed, return_diag=True,
use_out_degree=use_out_degree)
_assert_allclose_sparse(L, desired_L, atol=1e-12)
_assert_allclose_sparse(d, desired_d, atol=1e-12)
示例10: constructLaplacianMatrix
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def constructLaplacianMatrix(self, W, Gepsilon):
G = W.copy()
#Convert adjacency matrix of weighted graph to adjacency matrix of unweighted graph
for i in self.users:
for j in self.users:
if G[i.id][j.id] > 0:
G[i.id][j.id] = 1
L = csgraph.laplacian(G, normed = False)
print L
I = np.identity(n = G.shape[0])
GW = I + Gepsilon*L # W is a double stochastic matrix
print 'GW', GW
return GW.T
示例11: approximate_normalized_graph_laplacian
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def approximate_normalized_graph_laplacian(A, rank, which="LA"):
n = A.shape[0]
L, d_rt = csgraph.laplacian(A, normed=True, return_diag=True)
# X = D^{-1/2} W D^{-1/2}
X = sparse.identity(n) - L
logger.info("Eigen decomposition...")
#evals, evecs = sparse.linalg.eigsh(X, rank,
# which=which, tol=1e-3, maxiter=300)
evals, evecs = sparse.linalg.eigsh(X, rank, which=which)
logger.info("Maximum eigenvalue %f, minimum eigenvalue %f", np.max(evals), np.min(evals))
logger.info("Computing D^{-1/2}U..")
D_rt_inv = sparse.diags(d_rt ** -1)
D_rt_invU = D_rt_inv.dot(evecs)
return evals, D_rt_invU
示例12: _im_distance
# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import laplacian [as 别名]
def _im_distance(adj1, adj2, hwhm):
"""Computes the Ipsen-Mikhailov distance for two symmetric adjacency
matrices
Base on this paper :
https://journals.aps.org/pre/abstract/10.1103/PhysRevE.66.046109
Note : this is also used by the file hamming_ipsen_mikhailov.py
Parameters
----------
adj1, adj2 (array): adjacency matrices.
hwhm (float) : hwhm of the lorentzian distribution.
Returns
-------
dist (float) : Ipsen-Mikhailov distance.
"""
N = len(adj1)
# get laplacian matrix
L1 = laplacian(adj1, normed=False)
L2 = laplacian(adj2, normed=False)
# get the modes for the positive-semidefinite laplacian
w1 = np.sqrt(np.abs(eigh(L1)[0][1:]))
w2 = np.sqrt(np.abs(eigh(L2)[0][1:]))
# we calculate the norm for both spectrum
norm1 = (N - 1) * np.pi / 2 - np.sum(np.arctan(-w1 / hwhm))
norm2 = (N - 1) * np.pi / 2 - np.sum(np.arctan(-w2 / hwhm))
# define both spectral densities
density1 = lambda w: np.sum(hwhm / ((w - w1) ** 2 + hwhm ** 2)) / norm1
density2 = lambda w: np.sum(hwhm / ((w - w2) ** 2 + hwhm ** 2)) / norm2
func = lambda w: (density1(w) - density2(w)) ** 2
return np.sqrt(quad(func, 0, np.inf, limit=100)[0])