pyG edge_index矩阵 转 普通邻接矩阵,COO稀疏矩阵,包含同质图和异质图

搜这个转化实在难找,在此记录一下!

**pyG的edge_index 转 COO

同质图**


import torch_geometric
torch_geometric.utils.to_scipy_sparse_matrix(data.edge_index)

异质图

import numpy as np
# 假如异质图size:N*M
from scipy.sparse import coo_matrix
row = (hetedata['节点1','边', '节点2'].edge_index)[0]
col = (hetedata['节点1','边', '节点2'].edge_index)[1]
value = torch.ones(hetedata['节点1','边', '节点2'].num_edges)
adj = coo_matrix((value, (row, col)), shape=(hetedata['节点1'].num_nodes, hetedata['节点2'].num_nodes))

下面是pytorch版本

edge_shape= torch.zeros((N,M)).shape
value = torch.ones(hetedata['节点1','边', '节点2'].num_edges))
adj = torch.sparse_coo_tensor(hetedata['节点1','边', '节点2'].edge_index,value,edge_shape)

**pyG的edge_index 转 coo 再转普通矩阵

python
adj = adj.toarray()
pytorch
adj = adj.to_dense() 

你可能感兴趣的:(pytorch,pyG,python)