Python networkx.normalized_laplacian_matrix() Examples
The following are 18
code examples of networkx.normalized_laplacian_matrix().
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
networkx
, or try the search function
.
Example #1
Source File: fgsd.py From karateclub with GNU General Public License v3.0 | 6 votes |
def _calculate_fgsd(self, graph): """ Calculating the features of a graph. Arg types: * **graph** *(NetworkX graph)* - A graph to be embedded. Return types: * **hist** *(Numpy array)* - The embedding of a single graph. """ L = nx.normalized_laplacian_matrix(graph).todense() fL = np.linalg.pinv(L) ones = np.ones(L.shape[0]) S = np.outer(np.diag(fL), ones)+np.outer(ones, np.diag(fL))-2*fL hist, bin_edges = np.histogram(S.flatten(), bins=self.hist_bins, range=self.hist_range) return hist
Example #2
Source File: sf.py From karateclub with GNU General Public License v3.0 | 6 votes |
def _calculate_sf(self, graph): """ Calculating the features of a graph. Arg types: * **graph** *(NetworkX graph)* - A graph to be embedded. Return types: * **embedding** *(Numpy array)* - The embedding of a single graph. """ number_of_nodes = graph.number_of_nodes() L_tilde = nx.normalized_laplacian_matrix(graph, nodelist=range(number_of_nodes)) if number_of_nodes <= self.dimensions: embedding = eigsh(L_tilde, k=number_of_nodes-1, which='LM', ncv=10*self.dimensions, return_eigenvectors=False) shape_diff = self.dimensions - embedding.shape[0] - 1 embedding = np.pad(embedding, (1, shape_diff), 'constant', constant_values=0) else: embedding = eigsh(L_tilde, k=self.dimensions, which='LM', ncv=10*self.dimensions, return_eigenvectors=False) return embedding
Example #3
Source File: lap.py From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License | 6 votes |
def learn_embedding(self, graph=None, edge_f=None, is_weighted=False, no_python=False): if not graph and not edge_f: raise Exception('graph/edge_f needed') if not graph: graph = graph_util.loadGraphFromEdgeListTxt(edge_f) graph = graph.to_undirected() t1 = time() L_sym = nx.normalized_laplacian_matrix(graph) try: w, v = lg.eigs(L_sym, k=self._d + 1, which='SM') t2 = time() self._X = v[:, 1:] p_d_p_t = np.dot(v, np.dot(np.diag(w), v.T)) eig_err = np.linalg.norm(p_d_p_t - L_sym) print ('Laplacian matrix recon. error (low rank): %f' % eig_err) return self._X, (t2 - t1) except: print ('SVD did not converge. Assigning random emebdding') self._X = np.random.randn(L_sym.shape[0], self._d) t2 = time() return self._X, (t2 - t1)
Example #4
Source File: test_laplacian.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def test_normalized_laplacian(self): "Generalized Graph Laplacian" GL = numpy.array([[1.00, -0.408, -0.408, -0.577, 0.00], [-0.408, 1.00, -0.50, 0.00, 0.00], [-0.408, -0.50, 1.00, 0.00, 0.00], [-0.577, 0.00, 0.00, 1.00, 0.00], [0.00, 0.00, 0.00, 0.00, 0.00]]) Lsl = numpy.array([[0.75, -0.2887, -0.2887, -0.3536, 0.], [-0.2887, 0.6667, -0.3333, 0., 0.], [-0.2887, -0.3333, 0.6667, 0., 0.], [-0.3536, 0., 0., 0.5, 0.], [0., 0., 0., 0., 0.]]) assert_almost_equal(nx.normalized_laplacian_matrix(self.G).todense(), GL, decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.MG).todense(), GL, decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.WG).todense(), GL, decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.WG, weight='other').todense(), GL, decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.Gsl).todense(), Lsl, decimal=3)
Example #5
Source File: lap.py From GEM with BSD 3-Clause "New" or "Revised" License | 6 votes |
def learn_embedding(self, graph=None, edge_f=None, is_weighted=False, no_python=False): if not graph and not edge_f: raise Exception('graph/edge_f needed') if not graph: graph = graph_util.loadGraphFromEdgeListTxt(edge_f) graph = graph.to_undirected() t1 = time() L_sym = nx.normalized_laplacian_matrix(graph) w, v = lg.eigs(L_sym, k=self._d + 1, which='SM') idx = np.argsort(w) # sort eigenvalues w = w[idx] v = v[:, idx] t2 = time() self._X = v[:, 1:] p_d_p_t = np.dot(v, np.dot(np.diag(w), v.T)) eig_err = np.linalg.norm(p_d_p_t - L_sym) print('Laplacian matrix recon. error (low rank): %f' % eig_err) return self._X.real, (t2 - t1)
Example #6
Source File: test_laplacian.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_normalized_laplacian(self): "Generalized Graph Laplacian" GL=numpy.array([[ 1.00, -0.408, -0.408, -0.577, 0.00], [-0.408, 1.00, -0.50, 0.00 , 0.00], [-0.408, -0.50, 1.00, 0.00, 0.00], [-0.577, 0.00, 0.00, 1.00, 0.00], [ 0.00, 0.00, 0.00, 0.00, 0.00]]) Lsl = numpy.array([[ 0.75 , -0.2887, -0.2887, -0.3536, 0.], [-0.2887, 0.6667, -0.3333, 0. , 0.], [-0.2887, -0.3333, 0.6667, 0. , 0.], [-0.3536, 0. , 0. , 0.5 , 0.], [ 0. , 0. , 0. , 0. , 0.]]) assert_almost_equal(nx.normalized_laplacian_matrix(self.G).todense(), GL,decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.MG).todense(), GL,decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.WG).todense(), GL,decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.WG,weight='other').todense(), GL,decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.Gsl).todense(), Lsl, decimal=3)
Example #7
Source File: test_laplacian.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_normalized_laplacian(self): "Generalized Graph Laplacian" GL = numpy.array([[1.00, -0.408, -0.408, -0.577, 0.00], [-0.408, 1.00, -0.50, 0.00, 0.00], [-0.408, -0.50, 1.00, 0.00, 0.00], [-0.577, 0.00, 0.00, 1.00, 0.00], [0.00, 0.00, 0.00, 0.00, 0.00]]) Lsl = numpy.array([[0.75, -0.2887, -0.2887, -0.3536, 0.], [-0.2887, 0.6667, -0.3333, 0., 0.], [-0.2887, -0.3333, 0.6667, 0., 0.], [-0.3536, 0., 0., 0.5, 0.], [0., 0., 0., 0., 0.]]) assert_almost_equal(nx.normalized_laplacian_matrix(self.G).todense(), GL, decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.MG).todense(), GL, decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.WG).todense(), GL, decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.WG, weight='other').todense(), GL, decimal=3) assert_almost_equal(nx.normalized_laplacian_matrix(self.Gsl).todense(), Lsl, decimal=3)
Example #8
Source File: lap.py From BioNEV with MIT License | 6 votes |
def getLap(self): # degree_mat = np.diagflat(np.sum(self.adj_mat, axis=1)) # print('np.diagflat(np.sum(self.adj_mat, axis=1))') # deg_trans = np.diagflat(np.reciprocal(np.sqrt(np.sum(self.adj_mat, axis=1)))) # print('np.diagflat(np.reciprocal(np.sqrt(np.sum(self.adj_mat, axis=1))))') # deg_trans = np.nan_to_num(deg_trans) # L = degree_mat-self.adj_mat # print('begin norm_lap_mat') # # eye = np.eye(self.node_size) # # norm_lap_mat = np.matmul(np.matmul(deg_trans, L), deg_trans) G = self.g.G.to_undirected() print('begin norm_lap_mat') norm_lap_mat = nx.normalized_laplacian_matrix(G) print('finish norm_lap_mat') return norm_lap_mat
Example #9
Source File: test_graphs.py From pygsp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_empty_graph(self, n_vertices=11): """Empty graphs have either no edge, or self-loops only. The Laplacian doesn't see self-loops, as the gradient on those edges is always zero. """ adjacencies = [ np.zeros((n_vertices, n_vertices)), np.identity(n_vertices), ] for adjacency, n_edges in zip(adjacencies, [0, n_vertices]): graph = graphs.Graph(adjacency) self.assertEqual(graph.n_vertices, n_vertices) self.assertEqual(graph.n_edges, n_edges) self.assertEqual(graph.W.nnz, n_edges) for laplacian in ['combinatorial', 'normalized']: graph.compute_laplacian(laplacian) self.assertEqual(graph.L.nnz, 0) sources, targets, weights = graph.get_edge_list() self.assertEqual(len(sources), n_edges) self.assertEqual(len(targets), n_edges) self.assertEqual(len(weights), n_edges) graph.compute_differential_operator() self.assertEqual(graph.D.nnz, 0) graph.compute_fourier_basis() np.testing.assert_allclose(graph.U, np.identity(n_vertices)) np.testing.assert_allclose(graph.e, np.zeros(n_vertices)) # NetworkX uses the same conventions. G = nx.from_scipy_sparse_matrix(graph.W) self.assertEqual(nx.laplacian_matrix(G).nnz, 0) self.assertEqual(nx.normalized_laplacian_matrix(G).nnz, 0) self.assertEqual(nx.incidence_matrix(G).nnz, 0)
Example #10
Source File: manager.py From gnn-comparison with GNU General Public License v3.0 | 5 votes |
def _precompute_kron_indices(self, G): laplacians = [] # laplacian matrices (represented as 1D vectors) v_plus_list = [] # reduction matrices X = G.get_x(self.use_node_attrs, self.use_node_degree, self.use_one) lap = torch.Tensor(normalized_laplacian_matrix(G).todense()) # I - D^{-1/2}AD^{-1/2} # print(X.shape, lap.shape) laplacians.append(lap) for _ in range(self.KRON_REDUCTIONS): if lap.shape[0] == 1: # Can't reduce further: v_plus, lap = torch.tensor([1]), torch.eye(1) # print(lap.shape) else: v_plus, lap = self._vertex_decimation(lap) # print(lap.shape) # print(lap) laplacians.append(lap.clone()) v_plus_list.append(v_plus.clone().long()) return laplacians, v_plus_list # For the Perron–Frobenius theorem, if A is > 0 for all ij then the leading eigenvector is > 0 # A Laplacian matrix is symmetric (=> diagonalizable) # and dominant eigenvalue (true in most cases? can we enforce it?) # => we have sufficient conditions for power method to converge
Example #11
Source File: test_algebraic_connectivity.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_buckminsterfullerene(self): G = nx.Graph( [(1, 10), (1, 41), (1, 59), (2, 12), (2, 42), (2, 60), (3, 6), (3, 43), (3, 57), (4, 8), (4, 44), (4, 58), (5, 13), (5, 56), (5, 57), (6, 10), (6, 31), (7, 14), (7, 56), (7, 58), (8, 12), (8, 32), (9, 23), (9, 53), (9, 59), (10, 15), (11, 24), (11, 53), (11, 60), (12, 16), (13, 14), (13, 25), (14, 26), (15, 27), (15, 49), (16, 28), (16, 50), (17, 18), (17, 19), (17, 54), (18, 20), (18, 55), (19, 23), (19, 41), (20, 24), (20, 42), (21, 31), (21, 33), (21, 57), (22, 32), (22, 34), (22, 58), (23, 24), (25, 35), (25, 43), (26, 36), (26, 44), (27, 51), (27, 59), (28, 52), (28, 60), (29, 33), (29, 34), (29, 56), (30, 51), (30, 52), (30, 53), (31, 47), (32, 48), (33, 45), (34, 46), (35, 36), (35, 37), (36, 38), (37, 39), (37, 49), (38, 40), (38, 50), (39, 40), (39, 51), (40, 52), (41, 47), (42, 48), (43, 49), (44, 50), (45, 46), (45, 54), (46, 55), (47, 54), (48, 55)]) for normalized in (False, True): if not normalized: A = nx.laplacian_matrix(G) sigma = 0.2434017461399311 else: A = nx.normalized_laplacian_matrix(G) sigma = 0.08113391537997749 for method in methods: try: assert_almost_equal(nx.algebraic_connectivity( G, normalized=normalized, tol=1e-12, method=method), sigma) x = nx.fiedler_vector(G, normalized=normalized, tol=1e-12, method=method) check_eigenvector(A, sigma, x) except nx.NetworkXError as e: if e.args not in (('Cholesky solver unavailable.',), ('LU solver unavailable.',)): raise
Example #12
Source File: test_algebraic_connectivity.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_buckminsterfullerene(self): G = nx.Graph( [(1, 10), (1, 41), (1, 59), (2, 12), (2, 42), (2, 60), (3, 6), (3, 43), (3, 57), (4, 8), (4, 44), (4, 58), (5, 13), (5, 56), (5, 57), (6, 10), (6, 31), (7, 14), (7, 56), (7, 58), (8, 12), (8, 32), (9, 23), (9, 53), (9, 59), (10, 15), (11, 24), (11, 53), (11, 60), (12, 16), (13, 14), (13, 25), (14, 26), (15, 27), (15, 49), (16, 28), (16, 50), (17, 18), (17, 19), (17, 54), (18, 20), (18, 55), (19, 23), (19, 41), (20, 24), (20, 42), (21, 31), (21, 33), (21, 57), (22, 32), (22, 34), (22, 58), (23, 24), (25, 35), (25, 43), (26, 36), (26, 44), (27, 51), (27, 59), (28, 52), (28, 60), (29, 33), (29, 34), (29, 56), (30, 51), (30, 52), (30, 53), (31, 47), (32, 48), (33, 45), (34, 46), (35, 36), (35, 37), (36, 38), (37, 39), (37, 49), (38, 40), (38, 50), (39, 40), (39, 51), (40, 52), (41, 47), (42, 48), (43, 49), (44, 50), (45, 46), (45, 54), (46, 55), (47, 54), (48, 55)]) for normalized in (False, True): if not normalized: A = nx.laplacian_matrix(G) sigma = 0.2434017461399311 else: A = nx.normalized_laplacian_matrix(G) sigma = 0.08113391537997749 for method in methods: try: assert_almost_equal(nx.algebraic_connectivity( G, normalized=normalized, tol=1e-12, method=method), sigma) x = nx.fiedler_vector(G, normalized=normalized, tol=1e-12, method=method) check_eigenvector(A, sigma, x) except nx.NetworkXError as e: if e.args not in (('Cholesky solver unavailable.',), ('LU solver unavailable.',)): raise
Example #13
Source File: spectrum.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def normalized_laplacian_spectrum(G, weight='weight'): """Return eigenvalues of the normalized Laplacian of G Parameters ---------- G : graph A NetworkX graph weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each edge has weight 1. Returns ------- evals : NumPy array Eigenvalues Notes ----- For MultiGraph/MultiDiGraph, the edges weights are summed. See to_numpy_matrix for other options. See Also -------- normalized_laplacian_matrix """ from scipy.linalg import eigvalsh return eigvalsh(nx.normalized_laplacian_matrix(G, weight=weight).todense())
Example #14
Source File: test_algebraic_connectivity.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_buckminsterfullerene(self): G = nx.Graph( [(1, 10), (1, 41), (1, 59), (2, 12), (2, 42), (2, 60), (3, 6), (3, 43), (3, 57), (4, 8), (4, 44), (4, 58), (5, 13), (5, 56), (5, 57), (6, 10), (6, 31), (7, 14), (7, 56), (7, 58), (8, 12), (8, 32), (9, 23), (9, 53), (9, 59), (10, 15), (11, 24), (11, 53), (11, 60), (12, 16), (13, 14), (13, 25), (14, 26), (15, 27), (15, 49), (16, 28), (16, 50), (17, 18), (17, 19), (17, 54), (18, 20), (18, 55), (19, 23), (19, 41), (20, 24), (20, 42), (21, 31), (21, 33), (21, 57), (22, 32), (22, 34), (22, 58), (23, 24), (25, 35), (25, 43), (26, 36), (26, 44), (27, 51), (27, 59), (28, 52), (28, 60), (29, 33), (29, 34), (29, 56), (30, 51), (30, 52), (30, 53), (31, 47), (32, 48), (33, 45), (34, 46), (35, 36), (35, 37), (36, 38), (37, 39), (37, 49), (38, 40), (38, 50), (39, 40), (39, 51), (40, 52), (41, 47), (42, 48), (43, 49), (44, 50), (45, 46), (45, 54), (46, 55), (47, 54), (48, 55)]) for normalized in (False, True): if not normalized: A = nx.laplacian_matrix(G) sigma = 0.2434017461399311 else: A = nx.normalized_laplacian_matrix(G) sigma = 0.08113391537997749 for method in methods: try: assert_almost_equal(nx.algebraic_connectivity( G, normalized=normalized, tol=1e-12, method=method), sigma) x = nx.fiedler_vector(G, normalized=normalized, tol=1e-12, method=method) check_eigenvector(A, sigma, x) except nx.NetworkXError as e: if e.args not in (('Cholesky solver unavailable.',), ('LU solver unavailable.',)): raise
Example #15
Source File: spectral.py From cogdl with MIT License | 5 votes |
def train(self, G): matrix = nx.normalized_laplacian_matrix(G).todense() matrix = np.eye(matrix.shape[0]) - np.asarray(matrix) ut, s, _ = sp.linalg.svds(matrix, self.dimension) emb_matrix = ut * np.sqrt(s) emb_matrix = preprocessing.normalize(emb_matrix, "l2") return emb_matrix
Example #16
Source File: laplacianeigenmaps.py From karateclub with GNU General Public License v3.0 | 5 votes |
def fit(self, graph): """ Fitting a Laplacian EigenMaps model. Arg types: * **graph** *(NetworkX graph)* - The graph to be embedded. """ self._set_seed() self._check_graph(graph) number_of_nodes = graph.number_of_nodes() L_tilde = nx.normalized_laplacian_matrix(graph, nodelist=range(number_of_nodes)) eigenvalues, embedding = sps.linalg.eigsh(L_tilde, k=self.dimensions, return_eigenvectors=True) self._embedding = embedding
Example #17
Source File: netlsd.py From karateclub with GNU General Public License v3.0 | 5 votes |
def _calculate_netlsd(self, graph): """ Calculating the features of a graph. Arg types: * **graph** *(NetworkX graph)* - A graph to be embedded. Return types: * **hist** *(Numpy array)* - The embedding of a single graph. """ graph.remove_edges_from(nx.selfloop_edges(graph)) laplacian = sps.coo_matrix(nx.normalized_laplacian_matrix(graph, nodelist = range(graph.number_of_nodes())), dtype=np.float32) eigen_values = self._calculate_eigenvalues(laplacian) heat_kernel_trace = self._calculate_heat_kernel_trace(eigen_values) return heat_kernel_trace
Example #18
Source File: netlsd.py From netrd with MIT License | 4 votes |
def dist(self, G1, G2, normalization=None, timescales=None): """NetLSD: Hearing the Shape of a Graph. A network similarity measure based on spectral node signature distributions. The results dictionary includes the underlying signature vectors in `'signatures'`. Parameters ---------- G1, G2 (nx.Graph) two undirected networkx graphs to be compared. normalization (str) type of normalization of the heat kernel vectors. either `'complete'`, `'empty'` or `'none'` timescales (np.ndarray) timescales for the comparison. None yields default. Returns ------- dist (float) the distance between `G1` and `G2`. References ---------- .. [1] A. Tsitsulin, D. Mottin, P. Karras, A. Bronstein & E. Müller. NetLSD: Hearing the Shape of a Graph. KDD 2018 """ if normalization is None: normalization = 'none' if timescales is None: timescales = np.logspace(-2, 2, 256) assert isinstance( normalization, str ), 'Normalization parameter must be of string type' lap1 = nx.normalized_laplacian_matrix(G1) lap2 = nx.normalized_laplacian_matrix(G2) # Note: this is O(n^3) worst-case. eigs1 = spl.eigvalsh(lap1.todense()) eigs2 = spl.eigvalsh(lap2.todense()) hkt1 = _lsd_signature(eigs1, timescales, normalization) hkt2 = _lsd_signature(eigs2, timescales, normalization) self.results['signatures'] = (hkt1, hkt2) self.results['dist'] = np.linalg.norm(hkt1 - hkt2) return self.results['dist']