2 回答
TA贡献1839条经验 获得超15个赞
您可以使用矩阵代数;
cluster = np.array(cluster)
# create cluster-node adjacency matrix
aux = np.identity(cluster.max(),int)[cluster-1]
# we can now count by multiplying
out = aux.T@A@aux
# fix diagonal (which was counted twice)
np.einsum("ii->i",out)[...] //= 2
out
# array([[1, 2, 1],
# [2, 1, 1],
# [1, 1, 0]])
为了加快速度,如果节点按集群排序,我们可以用 (1) 替换矩阵乘积:
boundaries = np.diff(cluster,prepend=-1).nonzero()[0]
out = np.add.reduceat(np.add.reduceat(A,boundaries,1),boundaries,0)
(2) 如果不是:
nc = cluster.max()
out = np.zeros((nc,nc),int)
np.add.at(out,(cluster[:,None]-1,cluster-1),A)
TA贡献1873条经验 获得超9个赞
这将返回一个数组,其元素[i,j]是相应簇的边的总和i和j:
n = cluster.max()
degrees = np.zeros((n,n))
idx = [np.where(cluster==i)[0] for i in np.arange(n)+1]
for i in range(n):
degrees[i,i] = A[np.ix_(idx[i],idx[i])].sum()/2
for j in range(i):
degrees[i,j] = degrees[j,i] = A[np.ix_(idx[i],idx[j])].sum()
输出:
[[1. 2. 1.]
[2. 1. 1.]
[1. 1. 0.]]
您也可以使用 itertools,但我认为这可能更快。
添加回答
举报