我在python中使用networkx和命令
A = nx.adjacency_matrix(G)
返回csr矩阵,而不是2D数组。因此,当我尝试进行时
np.trace(A)
我得到一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/numpy/core/fromnumeric.py", line 1279, in trace
return asarray(a).trace(offset, axis1, axis2, dtype, out)
ValueError: diag requires an array of at least two dimensions
我怎样才能四处寻找踪迹?
In [543]: A=np.arange(9).reshape(3,3)
对于数组,trace
可以作为函数或方法调用。实际上,np.trace
将操作委派给A.trace
。
In [544]: np.trace(A)
Out[544]: 12
In [545]: A.trace()
Out[545]: 12
In [546]: M=sparse.csr_matrix(A)
通常,在稀疏矩阵上调用numpy函数是不起作用的,除非矩阵有匹配方法。
In [547]: np.trace(M)
...
ValueError: diag requires an array of at least two dimensions
In [548]: M.trace()
...
AttributeError: trace not found
但稀疏矩阵有一种diagonal
方法,它同样好:
In [549]: M.diagonal()
Out[549]: array([0, 4, 8], dtype=int32)
In [550]: M.diagonal().sum()
Out[550]: 12
当然,你可以先把稀疏矩阵变成数组:
In [551]: np.trace(M.A)
Out[551]: 12
不要使用矩阵。networkx
使用nodes_with_selfloops
方法列出具有自循环的节点:
>>> import networkx
>>> G = networkx.Graph()
>>> G.add_node(1)
>>> G.add_node(2)
>>> G.add_node(3)
>>> G.add_edge(2, 2)
>>> G.add_edge(1, 3)
>>> G.nodes_with_selfloops()
[2]
如果你的图表没有加权,跟踪将只是列表中的项目数量,所以你可以这样做:
>>> len(G.nodes_with_selfloops())
1
如果它是加权的,你可以将每个自循环的权重相加:
>>> import networkx
>>> G = networkx.Graph()
>>> G.add_node(1)
>>> G.add_node(2)
>>> G.add_node(3)
>>> G.add_edge(1, 1, weight=2)
>>> G.add_edge(2, 2, weight=1.5)
>>> sum(G.get_edge_data(node, node)['weight'] for node in G.nodes_with_selfloops())
3.5