Python scipy.sparse.csgraph.laplacian() Examples
The following are 12
code examples of scipy.sparse.csgraph.laplacian().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
scipy.sparse.csgraph
, or try the search function
.
Example #1
Source File: test_graph_laplacian.py From Computable with MIT License | 6 votes |
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))
Example #2
Source File: test_spectral_embedding.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
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)
Example #3
Source File: test_graph_laplacian.py From GraphicDesignPatternByPython with MIT License | 6 votes |
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))
Example #4
Source File: test_utils.py From twitter-stock-recommendation with MIT License | 6 votes |
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)
Example #5
Source File: netmf.py From NetMF with MIT License | 6 votes |
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)
Example #6
Source File: utils.py From graph-cnn.pytorch with MIT License | 5 votes |
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)
Example #7
Source File: label_propagation.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
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
Example #8
Source File: test_graph_laplacian.py From GraphicDesignPatternByPython with MIT License | 5 votes |
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)
Example #9
Source File: test_graph_laplacian.py From GraphicDesignPatternByPython with MIT License | 5 votes |
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)
Example #10
Source File: Simulation_save_file.py From BanditLib with MIT License | 5 votes |
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
Example #11
Source File: netmf.py From NetMF with MIT License | 5 votes |
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
Example #12
Source File: ipsen_mikhailov.py From netrd with MIT License | 4 votes |
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])