本文整理汇总了Python中networkx.laplacian_matrix方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.laplacian_matrix方法的具体用法?Python networkx.laplacian_matrix怎么用?Python networkx.laplacian_matrix使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.laplacian_matrix方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: normalize_adjacency
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [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
示例2: train
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def train(self, G):
num_node = G.number_of_nodes()
model = SDNE_layer(num_node, self.hidden_size1, self.hidden_size2, self.droput, self.alpha, self.beta, self.nu1, self.nu2)
A = torch.from_numpy(nx.adjacency_matrix(G).todense().astype(np.float32))
L = torch.from_numpy(nx.laplacian_matrix(G).todense().astype(np.float32))
A, L = A.to(self.device), L.to(self.device)
model = model.to(self.device)
opt = torch.optim.Adam(model.parameters(), lr=self.lr)
epoch_iter = tqdm(range(self.max_epoch))
for epoch in epoch_iter:
opt.zero_grad()
L_1st, L_2nd, L_all, L_reg = model.forward(A, L)
Loss = L_all + L_reg
Loss.backward()
epoch_iter.set_description(
f"Epoch: {epoch:03d}, L_1st: {L_1st:.4f}, L_2nd: {L_2nd:.4f}, L_reg: {L_reg:.4f}"
)
opt.step()
embedding = model.get_emb(A)
return embedding.detach().cpu().numpy()
示例3: test_laplacian
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def test_laplacian(self):
"Graph Laplacian"
NL=numpy.array([[ 3, -1, -1, -1, 0],
[-1, 2, -1, 0, 0],
[-1, -1, 2, 0, 0],
[-1, 0, 0, 1, 0],
[ 0, 0, 0, 0, 0]])
WL=0.5*NL
OL=0.3*NL
assert_equal(nx.laplacian_matrix(self.G).todense(),NL)
assert_equal(nx.laplacian_matrix(self.MG).todense(),NL)
assert_equal(nx.laplacian_matrix(self.G,nodelist=[0,1]).todense(),
numpy.array([[ 1, -1],[-1, 1]]))
assert_equal(nx.laplacian_matrix(self.WG).todense(),WL)
assert_equal(nx.laplacian_matrix(self.WG,weight=None).todense(),NL)
assert_equal(nx.laplacian_matrix(self.WG,weight='other').todense(),OL)
示例4: test_two_nodes
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def test_two_nodes(self):
G = nx.Graph()
G.add_edge(0, 1, weight=1)
A = nx.laplacian_matrix(G)
for method in self._methods:
assert_almost_equal(nx.algebraic_connectivity(
G, tol=1e-12, method=method), 2)
x = nx.fiedler_vector(G, tol=1e-12, method=method)
check_eigenvector(A, 2, x)
G = nx.MultiGraph()
G.add_edge(0, 0, spam=1e8)
G.add_edge(0, 1, spam=1)
G.add_edge(0, 1, spam=-2)
A = -3 * nx.laplacian_matrix(G, weight='spam')
for method in self._methods:
assert_almost_equal(nx.algebraic_connectivity(
G, weight='spam', tol=1e-12, method=method), 6)
x = nx.fiedler_vector(G, weight='spam', tol=1e-12, method=method)
check_eigenvector(A, 6, x)
示例5: test_cycle
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def test_cycle(self):
path = list(range(10))
G = nx.Graph()
G.add_path(path, weight=5)
G.add_edge(path[-1], path[0], weight=1)
A = nx.laplacian_matrix(G).todense()
for normalized in (False, True):
for method in methods:
try:
order = nx.spectral_ordering(G, normalized=normalized,
method=method)
except nx.NetworkXError as e:
if e.args not in (('Cholesky solver unavailable.',),
('LU solver unavailable.',)):
raise
else:
if not normalized:
ok_(order in [[1, 2, 0, 3, 4, 5, 6, 9, 7, 8],
[8, 7, 9, 6, 5, 4, 3, 0, 2, 1]])
else:
ok_(order in [[1, 2, 3, 0, 4, 5, 9, 6, 7, 8],
[8, 7, 6, 9, 5, 4, 0, 3, 2, 1]])
示例6: test_eigenvectors
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def test_eigenvectors(self):
try:
import numpy as N
eigenval=N.linalg.eigvals
import scipy
except ImportError:
raise SkipTest('SciPy not available.')
cs='ddiiddid'
G=nxt.threshold_graph(cs)
(tgeval,tgevec)=nxt.eigenvectors(cs)
dot=N.dot
assert_equal([ abs(dot(lv,lv)-1.0)<1e-9 for lv in tgevec ], [True]*8)
lapl=nx.laplacian_matrix(G)
# tgev=[ dot(lv,dot(lapl,lv)) for lv in tgevec ]
# assert_true(sum([abs(c-d) for c,d in zip(tgev,tgeval)]) < 1e-9)
# tgev.sort()
# lev=list(eigenval(lapl))
# lev.sort()
# assert_true(sum([abs(c-d) for c,d in zip(tgev,lev)]) < 1e-9)
示例7: test_laplacian
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def test_laplacian(self):
"Graph Laplacian"
NL = numpy.array([[3, -1, -1, -1, 0],
[-1, 2, -1, 0, 0],
[-1, -1, 2, 0, 0],
[-1, 0, 0, 1, 0],
[0, 0, 0, 0, 0]])
WL = 0.5 * NL
OL = 0.3 * NL
assert_equal(nx.laplacian_matrix(self.G).todense(), NL)
assert_equal(nx.laplacian_matrix(self.MG).todense(), NL)
assert_equal(nx.laplacian_matrix(self.G, nodelist=[0, 1]).todense(),
numpy.array([[1, -1], [-1, 1]]))
assert_equal(nx.laplacian_matrix(self.WG).todense(), WL)
assert_equal(nx.laplacian_matrix(self.WG, weight=None).todense(), NL)
assert_equal(nx.laplacian_matrix(self.WG, weight='other').todense(), OL)
示例8: test_cycle
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def test_cycle(self):
path = list(range(10))
G = nx.Graph()
nx.add_path(G, path, weight=5)
G.add_edge(path[-1], path[0], weight=1)
A = nx.laplacian_matrix(G).todense()
for normalized in (False, True):
for method in methods:
try:
order = nx.spectral_ordering(G, normalized=normalized,
method=method)
except nx.NetworkXError as e:
if e.args not in (('Cholesky solver unavailable.',),
('LU solver unavailable.',)):
raise
else:
if not normalized:
ok_(order in [[1, 2, 0, 3, 4, 5, 6, 9, 7, 8],
[8, 7, 9, 6, 5, 4, 3, 0, 2, 1]])
else:
ok_(order in [[1, 2, 3, 0, 4, 5, 9, 6, 7, 8],
[8, 7, 6, 9, 5, 4, 0, 3, 2, 1]])
示例9: test_eigenvectors
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def test_eigenvectors(self):
try:
import numpy as N
eigenval = N.linalg.eigvals
import scipy
except ImportError:
raise SkipTest('SciPy not available.')
cs = 'ddiiddid'
G = nxt.threshold_graph(cs)
(tgeval, tgevec) = nxt.eigenvectors(cs)
dot = N.dot
assert_equal([abs(dot(lv, lv) - 1.0) < 1e-9 for lv in tgevec], [True] * 8)
lapl = nx.laplacian_matrix(G)
# tgev=[ dot(lv,dot(lapl,lv)) for lv in tgevec ]
# assert_true(sum([abs(c-d) for c,d in zip(tgev,tgeval)]) < 1e-9)
# tgev.sort()
# lev=list(eigenval(lapl))
# lev.sort()
# assert_true(sum([abs(c-d) for c,d in zip(tgev,lev)]) < 1e-9)
示例10: _setup_target_matrices
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def _setup_target_matrices(self, graph):
"""
Setup target matrix for pre-training process.
Arg types:
* **graph** *(NetworkX graph)* - The graph being clustered.
"""
self._graph = graph
self._A = nx.adjacency_matrix(self._graph, nodelist=range(self._graph.number_of_nodes()))
self._L = nx.laplacian_matrix(self._graph, nodelist=range(self._graph.number_of_nodes()))
self._D = self._L+self._A
示例11: __init__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def __init__(self, graph, args):
"""
Initializing a DANMF object.
:param graph: Networkx graph.
:param args: Arguments object.
"""
self.graph = graph
self.A = nx.adjacency_matrix(self.graph)
self.L = nx.laplacian_matrix(self.graph)
self.D = self.L+self.A
self.args = args
self.p = len(self.args.layers)
示例12: spanning_tree_count
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def spanning_tree_count(graph: nx.Graph) -> int:
"""Return the number of unique spanning trees of a graph, using
Kirchhoff's matrix tree theorem.
"""
laplacian = nx.laplacian_matrix(graph).toarray()
comatrix = laplacian[:-1, :-1]
det = np.linalg.det(comatrix)
count = int(round(det))
return count
示例13: laplacian_spectrum
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def laplacian_spectrum(G, weight='weight'):
"""Return eigenvalues of the 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
--------
laplacian_matrix
"""
from scipy.linalg import eigvalsh
return eigvalsh(nx.laplacian_matrix(G,weight=weight).todense())
示例14: test_path
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def test_path(self):
G = nx.path_graph(8)
A = nx.laplacian_matrix(G)
sigma = 2 - sqrt(2 + sqrt(2))
for method in self._methods:
assert_almost_equal(nx.algebraic_connectivity(
G, tol=1e-12, method=method), sigma)
x = nx.fiedler_vector(G, tol=1e-12, method=method)
check_eigenvector(A, sigma, x)
示例15: laplacian_spectrum
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import laplacian_matrix [as 别名]
def laplacian_spectrum(G, weight='weight'):
"""Returns eigenvalues of the 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
--------
laplacian_matrix
"""
from scipy.linalg import eigvalsh
return eigvalsh(nx.laplacian_matrix(G, weight=weight).todense())