Networkx degree方法的结果与预期不符
我运行了以下脚本:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1, 1, weight=2)
G.add_edge(1, 3, weight=2)
G.add_edge(1, 4, weight=1)
G.add_edge(1, 5, weight=5)
G.add_edge(2, 3, weight=3)
G.add_edge(2, 4, weight=2)
G.add_edge(3, 5, weight=4)
d = G.degree(1)
print G.edge[1]
print "Degree of node 1:", \
G.degree(1)
print "Weighted degree of node 1:", \
G.degree(1, weight='weight')
nx.draw(G)
plt.show()
输出结果是:
{1: {'weight': 2}, 3: {'weight': 2}, 4: {'weight': 1}, 5: {'weight': 5}}
Weighted degree: 5
Weighted degree: 12
画出来的图像是这样的:
让我困惑的是:
因为有4个节点和节点 1相邻(包括它自己),为什么它的度数是5呢?
而且,节点 1相邻边的总权重是10(2+2+1+5),为什么用度数的方法算出来是12呢?
谢谢
2 个回答
3
根据度的定义,
在图论中,图中一个点的度(或称为连通度)是指与这个点相连的边的数量,如果有环的话,要算两次。(我强调一下)
所以G.degree(1)
的值是5,因为从1到1的环被算了两次。加权度也会把这个环算两次,因此总数是12而不是10,因为这个1号节点的权重是2。
6
在一个无向图中,一个顶点的度数就是和它相连的顶点的数量。
有一种特殊情况叫做自环,它会让度数增加两个。我们可以这样理解:自环的每个连接都算作它自己相邻的顶点。换句话说,带有自环的顶点从边的两个端点都“看到”自己,所以它的度数增加了两个,而不是一个。