AttributeError Traceback (most recent call last)
<ipython-input-85-6e1936149908> in <cell line: 2>()
1 fig, ax = plt.subplots(figsize=(8, 8))
----> 2 ax = draw_graph(A, ax=ax, size_factor=1)
<ipython-input-83-384ee4aa675e> in draw_graph(A, m, ax, spring_layout, size_factor)
26 assert m**2 == A.shape[0] == A.shape[1]
27 # Create the nx.Graph object
---> 28 G = nx.from_scipy_sparse_matrix(A)
29 print('Number of nodes: %d; Number of edges: %d' % \
30 (G.number_of_nodes(), G.number_of_edges()))
AttributeError: module 'networkx' has no attribute 'from_scipy_sparse_matrix'
以下错误发生:
fig, ax = plt.subplots(figsize=(8, 8))
ax = draw_graph(A, ax=ax, size_factor=1)
定义图表的代码:
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=28, ax=None, spring_layout=False, size_factor=10):
'''Draw the graph given adjacency matrix(A),
optionally with spring_layout.
'''
assert m**2 == A.shape[0] == A.shape[1]
# Create the nx.Graph object
G = nx.from_scipy_sparse_matrix(A)
print('Number of nodes: %d; Number of edges: %d' % \
(G.number_of_nodes(), G.number_of_edges()))
grid_coords = 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
NetworkX 2.6 版本中引入了 from_scipy_sparse_matrix 函数。如果您使用的是旧版本的 NetworkX,您将无法使用此功能。要解决此问题,您可以将 NetworkX 版本升级到 2.6
pip uninstall networkx -y
pip install networkx==2.6.0