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)