1、邻接矩阵转化成coo格式的稀疏矩阵
在使用pytorch_geometric框架时,他所使用的数据Data(x,edge_index)等数据,edge_index应该是稀疏矩阵,但在使用的过程中,当我们获得临街矩阵后就需要把它编程稀疏矩阵。
如上图所示,在PyG框架下,我们可以构建其邻接矩阵为
A=np.array([[0,1,1]
[1,0,1]
[0,1,0]])
A=torch.LongTensor(A)
但是喂入PyG的邻接矩阵的形式edge_index是[2,边的信息],记录了位置索引信息index和边的权重weight。对于图上的例子来说其
edge_index=[[0,1,1,2]
[1,0,2,1]]
其中edge_index[0]是边的起始点,而edge_index[1]是这条边的终点。
对于复杂的邻接矩阵,那么怎么将邻接矩阵转化成coo形式的稀疏矩阵呢?
使用scipy.sparse这个包
import scipy.sparse as sp
A = np.array([[0, 3, 0, 1],
[1, 0, 2, 0],
[0, 1, 0, 0],
[1, 0, 0, 0]])
ed = sp.coo_matrix(A)
print(ed )
而edge_index[0]就表示图中的第一列,edge_index[1]表示图中第二列,代码如下
indices=np.vstack((ed.row,ed.col))
index=torch.LongTorch(indices)
values=torch.FloatTorch(ed.data)
edge_index=torch.sparse_coo_tensor(index,value,ed.shape)
2、 edge_index矩阵转化coo稀疏矩阵
在调用GCNconv的时候,其forward的数据是已经处理好的Data数据,而最近碰到一个问题,在使用torch.sparse.mm的时候其data.x和data.edge_index的矩阵大小的size是不匹配的,无法直接相乘,需要把edge_index转化成相应的coo格式的稀疏矩阵。需要根据data.x 的节点数量来重构edge_index。
- 首先,需要重构邻接矩阵的size
- 需要边权重矩阵的大小size以及权重value
- 使用torch.sparse_coo_tensor构建
x_sh=X.shape[0]
edge_shape= np.zeros((x_sh,x_sh)).shape
value = th.FloatTensor(np.ones(edge.shape[1]))
edge_index = th.sparse_coo_tensor(edge,value,edge_shape)
假设
X = np.array([[1, 0, 1, 1, 1, 1],
[0, 1, 1, 0, 0, 1],
[-1, 1, 0, 1, -1, 1],
[-1, 0, 0, 1, 1, 1]])
X = torch.FloatTensor(X)
torch.sparse.mm(edge_index,X)