Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a biadjacency matrix in networkx

I have a csv file containing an m x n biadjacency matrix. Which was exported like:

numpy.savetxt("file.csv", biadjacency_matrix, ...)

Now I have to import the matrix but struggle to find the correct function/method.

I tried the following:

numpy_data = numpy.loadtxt(...)
nx.from_numpy_matrix(numpy_data)

but get:

Input is not a correct numpy matrix or array.

which makes sense as the matrix is not n x n.

Is there a simple way to import the biadjacency_matrix?

Thanks for your help.

like image 333
wpp Avatar asked May 09 '26 14:05

wpp


1 Answers

There isn't a built-in function to import biadjacency matrices. You can create an adjacency matrix A from the biadjacency matrix B as

0  B
BT 0

where BT is the transpose of B.

Then you can load it directly,

In [1]: import numpy as np

In [2]: import networkx as nx

In [3]: b = np.matrix([[1,0,1],[0,1,1]]) 

In [4]: r,s = b.shape

In [5]: a = np.vstack( (np.hstack((np.zeros((r,r)),b)), np.hstack((b.T,np.zeros((s,s)) ))) )

In [6]: G = nx.Graph(a)

In [7]: G.edges()
Out[7]: [(0, 2), (0, 4), (1, 3), (1, 4)]

The nodes are labeled 0,1 (part 1) and 2,3,4 (part 2).

like image 105
Aric Avatar answered May 12 '26 04:05

Aric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!