I am currently working on trying to write code to calculate the degree matrix, so that I may compute the Laplacian L = D - A, where D=degree matrix, A=adjacency matrix.
This will be later used in my spectral clustering algorithm. I am using Python. So for this toy example, I am having trouble doing it. Can anyone provide an efficient way of doing this, or if there is an API for calculating the degree matrix? My question is simply, what is an efficient way of calculating the degree of connectivity matrix, or is there a python module for that?
Example:
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
How can I compute the degree(matrix) that gives me 5 3 4 4, which represent the degree of connectivity for each node? Thank you.
There is a special package for graphs 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()
Result:
array([[ 3, -1, -1, -1],
[-1, 2, -1, 0],
[-1, -1, 3, -1],
[-1, 0, -1, 2]], dtype=int64)
Well I figured it out, but I don't know if this is the most efficient way of doing this. However, here was the answer I found.
#### 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.]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With