Python计算顶点度矩阵

ajl*_*123 4 python graph-theory cluster-analysis adjacency-matrix

我目前正在尝试编写代码来计算度矩阵,以便我可以计算拉普拉斯 L = D - A,其中 D=度矩阵,A=邻接矩阵。

这将在我的光谱聚类算法中使用。我正在使用 Python。所以对于这个玩具示例,我在做这件事时遇到了麻烦。任何人都可以提供一种有效的方法来做到这一点,或者是否有用于计算度矩阵的 API?我的问题很简单,计算连接矩阵度的有效方法是什么,或者是否有一个 python 模块?

例子:

import numpy as np
matrix = np.matrix('1, 1, 1, 1; 1, 0, 0, 0; 0, 0, 1, 1')

matrix =

 1     1     1     1
 1     0     0     0
 0     1     0     1
 0     0     1     1
Run Code Online (Sandbox Code Playgroud)

我如何计算给我 5 3 4 4 的度(矩阵),它代表每个节点的连接度?谢谢你。

ajl*_*123 5

好吧,我想通了,但我不知道这是否是最有效的方法。然而,这是我找到的答案。

#### Example of Computing Degree Matrix
import numpy as np
matrix = np.matrix('1, 1, 1, 1;'
                   '1, 0, 0, 0;'
                   '0, 1, 0, 1;'
                   '0, 0, 1, 1')

degree = np.zeros(len(matrix)) # initialize list to hold values of degree

# calculate the sums along rows and sum along columns
colsum = matrix.sum(axis=0)
rowsum = matrix.sum(axis=1)

# loop through matrix and add up all degree connections
for j in range(0, len(matrix)):
    degree[j] = colsum[0,j] + rowsum[j,0]

# get the diagonal entries to correct the for loop oversumming
A = matrix.diagonal()
d = A.flat
diagMat = list(d)

# print the degree of connectivity matrix 
print np.diag(degree - diagMat)

[[ 5.  0.  0.  0.]
 [ 0.  3.  0.  0.]
 [ 0.  0.  4.  0.]
 [ 0.  0.  0.  4.]]
Run Code Online (Sandbox Code Playgroud)


Myk*_*tko 5

有一个特殊的图形包networkx

import networkx as nx
import numpy as np

m = np.matrix('1, 1, 1, 1;'
              '1, 0, 0, 0;'
              '0, 1, 0, 1;'
              '0, 0, 1, 1')
G = nx.from_numpy_matrix(m)
nx.laplacian_matrix(G).toarray()
Run Code Online (Sandbox Code Playgroud)

结果:

array([[ 3, -1, -1, -1],
       [-1,  2, -1,  0],
       [-1, -1,  3, -1],
       [-1,  0, -1,  2]], dtype=int64)
Run Code Online (Sandbox Code Playgroud)


Had*_*ekh 5

您可以使用sumand diagof numpy Just 代替矩阵使用数组

import numpy as np
matrix = np.array([[1, 1, 1, 1],[1, 0, 0, 0],[ 0 ,1 ,0 ,1 ],[0, 0, 1, 1]])    
degree = np.diag(np.sum(matrix, axis=1))
Run Code Online (Sandbox Code Playgroud)