`def grid_Graph(m, k=8, corners=False):
'''
To create adjacency matrix as per Defferrard et al. 2016
'''
z = Graph.grid(m)
dist, idx = Graph.distance_sklearn_metrics(z, k=k, metric='euclidean')
A = Graph.adjacency(dist, idx)
# Connections are only vertical or horizontal on the grid.
# Corner vertices are connected to 2 neightbors only.
if corners:
import scipy.sparse
A = A.toarray()
A[A < A.max()/1.5] = 0
A = scipy.sparse.csr_matrix(A)
print('{} edges'.format(A.nnz))
print("{} > {} edges".format(A.nnz//2, k*m**2//2))
return A
def draw_Graph(A, m=32, ax=None, spring_layout=False, size_factor=10):
'''给定邻接矩阵(A)画图,
可选择使用 spring_layout。
'''
断言 m**2 == A.shape[0] == A.shape[1]
# 创建 nx.Graph 对象
G = nx.from_scipy_sparse_matrix(A)
print('节点数:%d;边数:%d' %
(G.number_of_nodes(), G.number_of_edges()))
网格坐标 = Graph.grid(m)
if spring_layout:
# remove nodes without edges
nodes_without_edges = [n for n, k in G.degree() if k == 0]
G.remove_nodes_from(nodes_without_edges)
print('After removing nodes without edges:')
print('Number of nodes: %d; Number of edges: %d' % \
(G.number_of_nodes(), G.number_of_edges()))
z = Graph.grid(m)
# initial positions
pos = {n: z[n] for n in G.nodes()}
if spring_layout:
pos = nx.spring_layout(G,
pos=pos,
iterations=200)
ax = nx.draw(G, pos,
node_size=[G.degree(n) * size_factor for n in G.nodes()],
ax=ax
)
return ax
A = grid_Graph(28, k=8) plt.imshow(A.todense()) `